sqlite3.c
Go to the documentation of this file.
00001 /******************************************************************************
00002 ** This file is an amalgamation of many separate C source files from SQLite
00003 ** version 3.8.2.  By combining all the individual C code files into this 
00004 ** single large file, the entire code can be compiled as a single translation
00005 ** unit.  This allows many compilers to do optimizations that would not be
00006 ** possible if the files were compiled separately.  Performance improvements
00007 ** of 5% or more are commonly seen when SQLite is compiled as a single
00008 ** translation unit.
00009 **
00010 ** This file is all you need to compile SQLite.  To use SQLite in other
00011 ** programs, you need this file and the "sqlite3.h" header file that defines
00012 ** the programming interface to the SQLite library.  (If you do not have 
00013 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
00014 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
00015 ** of the embedded sqlite3.h header file.) Additional code files may be needed
00016 ** if you want a wrapper to interface SQLite with your choice of programming
00017 ** language. The code for the "sqlite3" command-line shell is also in a
00018 ** separate file. This file contains only code for the core SQLite library.
00019 */
00020 #define SQLITE_CORE 1
00021 #define SQLITE_AMALGAMATION 1
00022 #ifndef SQLITE_PRIVATE
00023 # define SQLITE_PRIVATE static
00024 #endif
00025 #ifndef SQLITE_API
00026 # define SQLITE_API
00027 #endif
00028 /************** Begin file sqlite3.h *****************************************/
00029 /*
00030 ** 2001 September 15
00031 **
00032 ** The author disclaims copyright to this source code.  In place of
00033 ** a legal notice, here is a blessing:
00034 **
00035 **    May you do good and not evil.
00036 **    May you find forgiveness for yourself and forgive others.
00037 **    May you share freely, never taking more than you give.
00038 **
00039 *************************************************************************
00040 ** This header file defines the interface that the SQLite library
00041 ** presents to client programs.  If a C-function, structure, datatype,
00042 ** or constant definition does not appear in this file, then it is
00043 ** not a published API of SQLite, is subject to change without
00044 ** notice, and should not be referenced by programs that use SQLite.
00045 **
00046 ** Some of the definitions that are in this file are marked as
00047 ** "experimental".  Experimental interfaces are normally new
00048 ** features recently added to SQLite.  We do not anticipate changes
00049 ** to experimental interfaces but reserve the right to make minor changes
00050 ** if experience from use "in the wild" suggest such changes are prudent.
00051 **
00052 ** The official C-language API documentation for SQLite is derived
00053 ** from comments in this file.  This file is the authoritative source
00054 ** on how SQLite interfaces are suppose to operate.
00055 **
00056 ** The name of this file under configuration management is "sqlite.h.in".
00057 ** The makefile makes some minor changes to this file (such as inserting
00058 ** the version number) and changes its name to "sqlite3.h" as
00059 ** part of the build process.
00060 */
00061 #ifndef _SQLITE3_H_
00062 #define _SQLITE3_H_
00063 #include <stdarg.h>     /* Needed for the definition of va_list */
00064 
00065 /*
00066 ** Make sure we can call this stuff from C++.
00067 */
00068 #if 0
00069 extern "C" {
00070 #endif
00071 
00072 
00073 /*
00074 ** Add the ability to override 'extern'
00075 */
00076 #ifndef SQLITE_EXTERN
00077 # define SQLITE_EXTERN extern
00078 #endif
00079 
00080 #ifndef SQLITE_API
00081 # define SQLITE_API
00082 #endif
00083 
00084 
00085 /*
00086 ** These no-op macros are used in front of interfaces to mark those
00087 ** interfaces as either deprecated or experimental.  New applications
00088 ** should not use deprecated interfaces - they are support for backwards
00089 ** compatibility only.  Application writers should be aware that
00090 ** experimental interfaces are subject to change in point releases.
00091 **
00092 ** These macros used to resolve to various kinds of compiler magic that
00093 ** would generate warning messages when they were used.  But that
00094 ** compiler magic ended up generating such a flurry of bug reports
00095 ** that we have taken it all out and gone back to using simple
00096 ** noop macros.
00097 */
00098 #define SQLITE_DEPRECATED
00099 #define SQLITE_EXPERIMENTAL
00100 
00101 /*
00102 ** Ensure these symbols were not defined by some previous header file.
00103 */
00104 #ifdef SQLITE_VERSION
00105 # undef SQLITE_VERSION
00106 #endif
00107 #ifdef SQLITE_VERSION_NUMBER
00108 # undef SQLITE_VERSION_NUMBER
00109 #endif
00110 
00111 /*
00112 ** CAPI3REF: Compile-Time Library Version Numbers
00113 **
00114 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
00115 ** evaluates to a string literal that is the SQLite version in the
00116 ** format "X.Y.Z" where X is the major version number (always 3 for
00117 ** SQLite3) and Y is the minor version number and Z is the release number.)^
00118 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
00119 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
00120 ** numbers used in [SQLITE_VERSION].)^
00121 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
00122 ** be larger than the release from which it is derived.  Either Y will
00123 ** be held constant and Z will be incremented or else Y will be incremented
00124 ** and Z will be reset to zero.
00125 **
00126 ** Since version 3.6.18, SQLite source code has been stored in the
00127 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
00128 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
00129 ** a string which identifies a particular check-in of SQLite
00130 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
00131 ** string contains the date and time of the check-in (UTC) and an SHA1
00132 ** hash of the entire source tree.
00133 **
00134 ** See also: [sqlite3_libversion()],
00135 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
00136 ** [sqlite_version()] and [sqlite_source_id()].
00137 */
00138 #define SQLITE_VERSION        "3.8.2"
00139 #define SQLITE_VERSION_NUMBER 3008002
00140 #define SQLITE_SOURCE_ID      "2013-12-06 14:53:30 27392118af4c38c5203a04b8013e1afdb1cebd0d"
00141 
00142 /*
00143 ** CAPI3REF: Run-Time Library Version Numbers
00144 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
00145 **
00146 ** These interfaces provide the same information as the [SQLITE_VERSION],
00147 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
00148 ** but are associated with the library instead of the header file.  ^(Cautious
00149 ** programmers might include assert() statements in their application to
00150 ** verify that values returned by these interfaces match the macros in
00151 ** the header, and thus insure that the application is
00152 ** compiled with matching library and header files.
00153 **
00154 ** <blockquote><pre>
00155 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
00156 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
00157 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
00158 ** </pre></blockquote>)^
00159 **
00160 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
00161 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
00162 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
00163 ** function is provided for use in DLLs since DLL users usually do not have
00164 ** direct access to string constants within the DLL.  ^The
00165 ** sqlite3_libversion_number() function returns an integer equal to
00166 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
00167 ** a pointer to a string constant whose value is the same as the 
00168 ** [SQLITE_SOURCE_ID] C preprocessor macro.
00169 **
00170 ** See also: [sqlite_version()] and [sqlite_source_id()].
00171 */
00172 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
00173 SQLITE_API const char *sqlite3_libversion(void);
00174 SQLITE_API const char *sqlite3_sourceid(void);
00175 SQLITE_API int sqlite3_libversion_number(void);
00176 
00177 /*
00178 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
00179 **
00180 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
00181 ** indicating whether the specified option was defined at 
00182 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
00183 ** option name passed to sqlite3_compileoption_used().  
00184 **
00185 ** ^The sqlite3_compileoption_get() function allows iterating
00186 ** over the list of options that were defined at compile time by
00187 ** returning the N-th compile time option string.  ^If N is out of range,
00188 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
00189 ** prefix is omitted from any strings returned by 
00190 ** sqlite3_compileoption_get().
00191 **
00192 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
00193 ** and sqlite3_compileoption_get() may be omitted by specifying the 
00194 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
00195 **
00196 ** See also: SQL functions [sqlite_compileoption_used()] and
00197 ** [sqlite_compileoption_get()] and the [compile_options pragma].
00198 */
00199 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
00200 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
00201 SQLITE_API const char *sqlite3_compileoption_get(int N);
00202 #endif
00203 
00204 /*
00205 ** CAPI3REF: Test To See If The Library Is Threadsafe
00206 **
00207 ** ^The sqlite3_threadsafe() function returns zero if and only if
00208 ** SQLite was compiled with mutexing code omitted due to the
00209 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
00210 **
00211 ** SQLite can be compiled with or without mutexes.  When
00212 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
00213 ** are enabled and SQLite is threadsafe.  When the
00214 ** [SQLITE_THREADSAFE] macro is 0, 
00215 ** the mutexes are omitted.  Without the mutexes, it is not safe
00216 ** to use SQLite concurrently from more than one thread.
00217 **
00218 ** Enabling mutexes incurs a measurable performance penalty.
00219 ** So if speed is of utmost importance, it makes sense to disable
00220 ** the mutexes.  But for maximum safety, mutexes should be enabled.
00221 ** ^The default behavior is for mutexes to be enabled.
00222 **
00223 ** This interface can be used by an application to make sure that the
00224 ** version of SQLite that it is linking against was compiled with
00225 ** the desired setting of the [SQLITE_THREADSAFE] macro.
00226 **
00227 ** This interface only reports on the compile-time mutex setting
00228 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
00229 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
00230 ** can be fully or partially disabled using a call to [sqlite3_config()]
00231 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
00232 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
00233 ** sqlite3_threadsafe() function shows only the compile-time setting of
00234 ** thread safety, not any run-time changes to that setting made by
00235 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
00236 ** is unchanged by calls to sqlite3_config().)^
00237 **
00238 ** See the [threading mode] documentation for additional information.
00239 */
00240 SQLITE_API int sqlite3_threadsafe(void);
00241 
00242 /*
00243 ** CAPI3REF: Database Connection Handle
00244 ** KEYWORDS: {database connection} {database connections}
00245 **
00246 ** Each open SQLite database is represented by a pointer to an instance of
00247 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
00248 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
00249 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
00250 ** and [sqlite3_close_v2()] are its destructors.  There are many other
00251 ** interfaces (such as
00252 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
00253 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
00254 ** sqlite3 object.
00255 */
00256 typedef struct sqlite3 sqlite3;
00257 
00258 /*
00259 ** CAPI3REF: 64-Bit Integer Types
00260 ** KEYWORDS: sqlite_int64 sqlite_uint64
00261 **
00262 ** Because there is no cross-platform way to specify 64-bit integer types
00263 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
00264 **
00265 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
00266 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
00267 ** compatibility only.
00268 **
00269 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
00270 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
00271 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
00272 ** between 0 and +18446744073709551615 inclusive.
00273 */
00274 #ifdef SQLITE_INT64_TYPE
00275   typedef SQLITE_INT64_TYPE sqlite_int64;
00276   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
00277 #elif defined(_MSC_VER) || defined(__BORLANDC__)
00278   typedef __int64 sqlite_int64;
00279   typedef unsigned __int64 sqlite_uint64;
00280 #else
00281   typedef long long int sqlite_int64;
00282   typedef unsigned long long int sqlite_uint64;
00283 #endif
00284 typedef sqlite_int64 sqlite3_int64;
00285 typedef sqlite_uint64 sqlite3_uint64;
00286 
00287 /*
00288 ** If compiling for a processor that lacks floating point support,
00289 ** substitute integer for floating-point.
00290 */
00291 #ifdef SQLITE_OMIT_FLOATING_POINT
00292 # define double sqlite3_int64
00293 #endif
00294 
00295 /*
00296 ** CAPI3REF: Closing A Database Connection
00297 **
00298 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
00299 ** for the [sqlite3] object.
00300 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
00301 ** the [sqlite3] object is successfully destroyed and all associated
00302 ** resources are deallocated.
00303 **
00304 ** ^If the database connection is associated with unfinalized prepared
00305 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
00306 ** will leave the database connection open and return [SQLITE_BUSY].
00307 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
00308 ** and unfinished sqlite3_backups, then the database connection becomes
00309 ** an unusable "zombie" which will automatically be deallocated when the
00310 ** last prepared statement is finalized or the last sqlite3_backup is
00311 ** finished.  The sqlite3_close_v2() interface is intended for use with
00312 ** host languages that are garbage collected, and where the order in which
00313 ** destructors are called is arbitrary.
00314 **
00315 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
00316 ** [sqlite3_blob_close | close] all [BLOB handles], and 
00317 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
00318 ** with the [sqlite3] object prior to attempting to close the object.  ^If
00319 ** sqlite3_close_v2() is called on a [database connection] that still has
00320 ** outstanding [prepared statements], [BLOB handles], and/or
00321 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
00322 ** of resources is deferred until all [prepared statements], [BLOB handles],
00323 ** and [sqlite3_backup] objects are also destroyed.
00324 **
00325 ** ^If an [sqlite3] object is destroyed while a transaction is open,
00326 ** the transaction is automatically rolled back.
00327 **
00328 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
00329 ** must be either a NULL
00330 ** pointer or an [sqlite3] object pointer obtained
00331 ** from [sqlite3_open()], [sqlite3_open16()], or
00332 ** [sqlite3_open_v2()], and not previously closed.
00333 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
00334 ** argument is a harmless no-op.
00335 */
00336 SQLITE_API int sqlite3_close(sqlite3*);
00337 SQLITE_API int sqlite3_close_v2(sqlite3*);
00338 
00339 /*
00340 ** The type for a callback function.
00341 ** This is legacy and deprecated.  It is included for historical
00342 ** compatibility and is not documented.
00343 */
00344 typedef int (*sqlite3_callback)(void*,int,char**, char**);
00345 
00346 /*
00347 ** CAPI3REF: One-Step Query Execution Interface
00348 **
00349 ** The sqlite3_exec() interface is a convenience wrapper around
00350 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
00351 ** that allows an application to run multiple statements of SQL
00352 ** without having to use a lot of C code. 
00353 **
00354 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
00355 ** semicolon-separate SQL statements passed into its 2nd argument,
00356 ** in the context of the [database connection] passed in as its 1st
00357 ** argument.  ^If the callback function of the 3rd argument to
00358 ** sqlite3_exec() is not NULL, then it is invoked for each result row
00359 ** coming out of the evaluated SQL statements.  ^The 4th argument to
00360 ** sqlite3_exec() is relayed through to the 1st argument of each
00361 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
00362 ** is NULL, then no callback is ever invoked and result rows are
00363 ** ignored.
00364 **
00365 ** ^If an error occurs while evaluating the SQL statements passed into
00366 ** sqlite3_exec(), then execution of the current statement stops and
00367 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
00368 ** is not NULL then any error message is written into memory obtained
00369 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
00370 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
00371 ** on error message strings returned through the 5th parameter of
00372 ** of sqlite3_exec() after the error message string is no longer needed.
00373 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
00374 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
00375 ** NULL before returning.
00376 **
00377 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
00378 ** routine returns SQLITE_ABORT without invoking the callback again and
00379 ** without running any subsequent SQL statements.
00380 **
00381 ** ^The 2nd argument to the sqlite3_exec() callback function is the
00382 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
00383 ** callback is an array of pointers to strings obtained as if from
00384 ** [sqlite3_column_text()], one for each column.  ^If an element of a
00385 ** result row is NULL then the corresponding string pointer for the
00386 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
00387 ** sqlite3_exec() callback is an array of pointers to strings where each
00388 ** entry represents the name of corresponding result column as obtained
00389 ** from [sqlite3_column_name()].
00390 **
00391 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
00392 ** to an empty string, or a pointer that contains only whitespace and/or 
00393 ** SQL comments, then no SQL statements are evaluated and the database
00394 ** is not changed.
00395 **
00396 ** Restrictions:
00397 **
00398 ** <ul>
00399 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
00400 **      is a valid and open [database connection].
00401 ** <li> The application must not close the [database connection] specified by
00402 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
00403 ** <li> The application must not modify the SQL statement text passed into
00404 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
00405 ** </ul>
00406 */
00407 SQLITE_API int sqlite3_exec(
00408   sqlite3*,                                  /* An open database */
00409   const char *sql,                           /* SQL to be evaluated */
00410   int (*callback)(void*,int,char**,char**),  /* Callback function */
00411   void *,                                    /* 1st argument to callback */
00412   char **errmsg                              /* Error msg written here */
00413 );
00414 
00415 /*
00416 ** CAPI3REF: Result Codes
00417 ** KEYWORDS: SQLITE_OK {error code} {error codes}
00418 ** KEYWORDS: {result code} {result codes}
00419 **
00420 ** Many SQLite functions return an integer result code from the set shown
00421 ** here in order to indicate success or failure.
00422 **
00423 ** New error codes may be added in future versions of SQLite.
00424 **
00425 ** See also: [SQLITE_IOERR_READ | extended result codes],
00426 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
00427 */
00428 #define SQLITE_OK           0   /* Successful result */
00429 /* beginning-of-error-codes */
00430 #define SQLITE_ERROR        1   /* SQL error or missing database */
00431 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
00432 #define SQLITE_PERM         3   /* Access permission denied */
00433 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
00434 #define SQLITE_BUSY         5   /* The database file is locked */
00435 #define SQLITE_LOCKED       6   /* A table in the database is locked */
00436 #define SQLITE_NOMEM        7   /* A malloc() failed */
00437 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
00438 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
00439 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
00440 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
00441 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
00442 #define SQLITE_FULL        13   /* Insertion failed because database is full */
00443 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
00444 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
00445 #define SQLITE_EMPTY       16   /* Database is empty */
00446 #define SQLITE_SCHEMA      17   /* The database schema changed */
00447 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
00448 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
00449 #define SQLITE_MISMATCH    20   /* Data type mismatch */
00450 #define SQLITE_MISUSE      21   /* Library used incorrectly */
00451 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
00452 #define SQLITE_AUTH        23   /* Authorization denied */
00453 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
00454 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
00455 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
00456 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
00457 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
00458 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
00459 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
00460 /* end-of-error-codes */
00461 
00462 /*
00463 ** CAPI3REF: Extended Result Codes
00464 ** KEYWORDS: {extended error code} {extended error codes}
00465 ** KEYWORDS: {extended result code} {extended result codes}
00466 **
00467 ** In its default configuration, SQLite API routines return one of 26 integer
00468 ** [SQLITE_OK | result codes].  However, experience has shown that many of
00469 ** these result codes are too coarse-grained.  They do not provide as
00470 ** much information about problems as programmers might like.  In an effort to
00471 ** address this, newer versions of SQLite (version 3.3.8 and later) include
00472 ** support for additional result codes that provide more detailed information
00473 ** about errors. The extended result codes are enabled or disabled
00474 ** on a per database connection basis using the
00475 ** [sqlite3_extended_result_codes()] API.
00476 **
00477 ** Some of the available extended result codes are listed here.
00478 ** One may expect the number of extended result codes will increase
00479 ** over time.  Software that uses extended result codes should expect
00480 ** to see new result codes in future releases of SQLite.
00481 **
00482 ** The SQLITE_OK result code will never be extended.  It will always
00483 ** be exactly zero.
00484 */
00485 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
00486 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
00487 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
00488 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
00489 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
00490 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
00491 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
00492 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
00493 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
00494 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
00495 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
00496 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
00497 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
00498 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
00499 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
00500 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
00501 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
00502 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
00503 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
00504 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
00505 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
00506 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
00507 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
00508 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
00509 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
00510 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
00511 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
00512 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
00513 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
00514 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
00515 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
00516 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
00517 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
00518 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
00519 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
00520 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
00521 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
00522 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
00523 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
00524 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
00525 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
00526 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
00527 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
00528 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
00529 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
00530 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
00531 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
00532 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
00533 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
00534 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
00535 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
00536 
00537 /*
00538 ** CAPI3REF: Flags For File Open Operations
00539 **
00540 ** These bit values are intended for use in the
00541 ** 3rd parameter to the [sqlite3_open_v2()] interface and
00542 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
00543 */
00544 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
00545 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
00546 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
00547 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
00548 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
00549 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
00550 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
00551 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
00552 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
00553 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
00554 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
00555 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
00556 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
00557 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
00558 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
00559 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
00560 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
00561 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
00562 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
00563 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
00564 
00565 /* Reserved:                         0x00F00000 */
00566 
00567 /*
00568 ** CAPI3REF: Device Characteristics
00569 **
00570 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
00571 ** object returns an integer which is a vector of these
00572 ** bit values expressing I/O characteristics of the mass storage
00573 ** device that holds the file that the [sqlite3_io_methods]
00574 ** refers to.
00575 **
00576 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
00577 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
00578 ** mean that writes of blocks that are nnn bytes in size and
00579 ** are aligned to an address which is an integer multiple of
00580 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
00581 ** that when data is appended to a file, the data is appended
00582 ** first then the size of the file is extended, never the other
00583 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
00584 ** information is written to disk in the same order as calls
00585 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
00586 ** after reboot following a crash or power loss, the only bytes in a
00587 ** file that were written at the application level might have changed
00588 ** and that adjacent bytes, even bytes within the same sector are
00589 ** guaranteed to be unchanged.
00590 */
00591 #define SQLITE_IOCAP_ATOMIC                 0x00000001
00592 #define SQLITE_IOCAP_ATOMIC512              0x00000002
00593 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
00594 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
00595 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
00596 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
00597 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
00598 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
00599 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
00600 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
00601 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
00602 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
00603 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
00604 
00605 /*
00606 ** CAPI3REF: File Locking Levels
00607 **
00608 ** SQLite uses one of these integer values as the second
00609 ** argument to calls it makes to the xLock() and xUnlock() methods
00610 ** of an [sqlite3_io_methods] object.
00611 */
00612 #define SQLITE_LOCK_NONE          0
00613 #define SQLITE_LOCK_SHARED        1
00614 #define SQLITE_LOCK_RESERVED      2
00615 #define SQLITE_LOCK_PENDING       3
00616 #define SQLITE_LOCK_EXCLUSIVE     4
00617 
00618 /*
00619 ** CAPI3REF: Synchronization Type Flags
00620 **
00621 ** When SQLite invokes the xSync() method of an
00622 ** [sqlite3_io_methods] object it uses a combination of
00623 ** these integer values as the second argument.
00624 **
00625 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
00626 ** sync operation only needs to flush data to mass storage.  Inode
00627 ** information need not be flushed. If the lower four bits of the flag
00628 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
00629 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
00630 ** to use Mac OS X style fullsync instead of fsync().
00631 **
00632 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
00633 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
00634 ** settings.  The [synchronous pragma] determines when calls to the
00635 ** xSync VFS method occur and applies uniformly across all platforms.
00636 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
00637 ** energetic or rigorous or forceful the sync operations are and
00638 ** only make a difference on Mac OSX for the default SQLite code.
00639 ** (Third-party VFS implementations might also make the distinction
00640 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
00641 ** operating systems natively supported by SQLite, only Mac OSX
00642 ** cares about the difference.)
00643 */
00644 #define SQLITE_SYNC_NORMAL        0x00002
00645 #define SQLITE_SYNC_FULL          0x00003
00646 #define SQLITE_SYNC_DATAONLY      0x00010
00647 
00648 /*
00649 ** CAPI3REF: OS Interface Open File Handle
00650 **
00651 ** An [sqlite3_file] object represents an open file in the 
00652 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
00653 ** implementations will
00654 ** want to subclass this object by appending additional fields
00655 ** for their own use.  The pMethods entry is a pointer to an
00656 ** [sqlite3_io_methods] object that defines methods for performing
00657 ** I/O operations on the open file.
00658 */
00659 typedef struct sqlite3_file sqlite3_file;
00660 struct sqlite3_file {
00661   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
00662 };
00663 
00664 /*
00665 ** CAPI3REF: OS Interface File Virtual Methods Object
00666 **
00667 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
00668 ** [sqlite3_file] object (or, more commonly, a subclass of the
00669 ** [sqlite3_file] object) with a pointer to an instance of this object.
00670 ** This object defines the methods used to perform various operations
00671 ** against the open file represented by the [sqlite3_file] object.
00672 **
00673 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
00674 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
00675 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
00676 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
00677 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
00678 ** to NULL.
00679 **
00680 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
00681 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
00682 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
00683 ** flag may be ORed in to indicate that only the data of the file
00684 ** and not its inode needs to be synced.
00685 **
00686 ** The integer values to xLock() and xUnlock() are one of
00687 ** <ul>
00688 ** <li> [SQLITE_LOCK_NONE],
00689 ** <li> [SQLITE_LOCK_SHARED],
00690 ** <li> [SQLITE_LOCK_RESERVED],
00691 ** <li> [SQLITE_LOCK_PENDING], or
00692 ** <li> [SQLITE_LOCK_EXCLUSIVE].
00693 ** </ul>
00694 ** xLock() increases the lock. xUnlock() decreases the lock.
00695 ** The xCheckReservedLock() method checks whether any database connection,
00696 ** either in this process or in some other process, is holding a RESERVED,
00697 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
00698 ** if such a lock exists and false otherwise.
00699 **
00700 ** The xFileControl() method is a generic interface that allows custom
00701 ** VFS implementations to directly control an open file using the
00702 ** [sqlite3_file_control()] interface.  The second "op" argument is an
00703 ** integer opcode.  The third argument is a generic pointer intended to
00704 ** point to a structure that may contain arguments or space in which to
00705 ** write return values.  Potential uses for xFileControl() might be
00706 ** functions to enable blocking locks with timeouts, to change the
00707 ** locking strategy (for example to use dot-file locks), to inquire
00708 ** about the status of a lock, or to break stale locks.  The SQLite
00709 ** core reserves all opcodes less than 100 for its own use.
00710 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
00711 ** Applications that define a custom xFileControl method should use opcodes
00712 ** greater than 100 to avoid conflicts.  VFS implementations should
00713 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
00714 ** recognize.
00715 **
00716 ** The xSectorSize() method returns the sector size of the
00717 ** device that underlies the file.  The sector size is the
00718 ** minimum write that can be performed without disturbing
00719 ** other bytes in the file.  The xDeviceCharacteristics()
00720 ** method returns a bit vector describing behaviors of the
00721 ** underlying device:
00722 **
00723 ** <ul>
00724 ** <li> [SQLITE_IOCAP_ATOMIC]
00725 ** <li> [SQLITE_IOCAP_ATOMIC512]
00726 ** <li> [SQLITE_IOCAP_ATOMIC1K]
00727 ** <li> [SQLITE_IOCAP_ATOMIC2K]
00728 ** <li> [SQLITE_IOCAP_ATOMIC4K]
00729 ** <li> [SQLITE_IOCAP_ATOMIC8K]
00730 ** <li> [SQLITE_IOCAP_ATOMIC16K]
00731 ** <li> [SQLITE_IOCAP_ATOMIC32K]
00732 ** <li> [SQLITE_IOCAP_ATOMIC64K]
00733 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
00734 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
00735 ** </ul>
00736 **
00737 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
00738 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
00739 ** mean that writes of blocks that are nnn bytes in size and
00740 ** are aligned to an address which is an integer multiple of
00741 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
00742 ** that when data is appended to a file, the data is appended
00743 ** first then the size of the file is extended, never the other
00744 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
00745 ** information is written to disk in the same order as calls
00746 ** to xWrite().
00747 **
00748 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
00749 ** in the unread portions of the buffer with zeros.  A VFS that
00750 ** fails to zero-fill short reads might seem to work.  However,
00751 ** failure to zero-fill short reads will eventually lead to
00752 ** database corruption.
00753 */
00754 typedef struct sqlite3_io_methods sqlite3_io_methods;
00755 struct sqlite3_io_methods {
00756   int iVersion;
00757   int (*xClose)(sqlite3_file*);
00758   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
00759   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
00760   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
00761   int (*xSync)(sqlite3_file*, int flags);
00762   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
00763   int (*xLock)(sqlite3_file*, int);
00764   int (*xUnlock)(sqlite3_file*, int);
00765   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
00766   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
00767   int (*xSectorSize)(sqlite3_file*);
00768   int (*xDeviceCharacteristics)(sqlite3_file*);
00769   /* Methods above are valid for version 1 */
00770   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
00771   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
00772   void (*xShmBarrier)(sqlite3_file*);
00773   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
00774   /* Methods above are valid for version 2 */
00775   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
00776   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
00777   /* Methods above are valid for version 3 */
00778   /* Additional methods may be added in future releases */
00779 };
00780 
00781 /*
00782 ** CAPI3REF: Standard File Control Opcodes
00783 **
00784 ** These integer constants are opcodes for the xFileControl method
00785 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
00786 ** interface.
00787 **
00788 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
00789 ** opcode causes the xFileControl method to write the current state of
00790 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
00791 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
00792 ** into an integer that the pArg argument points to. This capability
00793 ** is used during testing and only needs to be supported when SQLITE_TEST
00794 ** is defined.
00795 ** <ul>
00796 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
00797 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
00798 ** layer a hint of how large the database file will grow to be during the
00799 ** current transaction.  This hint is not guaranteed to be accurate but it
00800 ** is often close.  The underlying VFS might choose to preallocate database
00801 ** file space based on this hint in order to help writes to the database
00802 ** file run faster.
00803 **
00804 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
00805 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
00806 ** extends and truncates the database file in chunks of a size specified
00807 ** by the user. The fourth argument to [sqlite3_file_control()] should 
00808 ** point to an integer (type int) containing the new chunk-size to use
00809 ** for the nominated database. Allocating database file space in large
00810 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
00811 ** improve performance on some systems.
00812 **
00813 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
00814 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
00815 ** to the [sqlite3_file] object associated with a particular database
00816 ** connection.  See the [sqlite3_file_control()] documentation for
00817 ** additional information.
00818 **
00819 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
00820 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
00821 ** SQLite and sent to all VFSes in place of a call to the xSync method
00822 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
00823 ** Some specialized VFSes need this signal in order to operate correctly
00824 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
00825 ** VFSes do not need this signal and should silently ignore this opcode.
00826 ** Applications should not call [sqlite3_file_control()] with this
00827 ** opcode as doing so may disrupt the operation of the specialized VFSes
00828 ** that do require it.  
00829 **
00830 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
00831 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
00832 ** retry counts and intervals for certain disk I/O operations for the
00833 ** windows [VFS] in order to provide robustness in the presence of
00834 ** anti-virus programs.  By default, the windows VFS will retry file read,
00835 ** file write, and file delete operations up to 10 times, with a delay
00836 ** of 25 milliseconds before the first retry and with the delay increasing
00837 ** by an additional 25 milliseconds with each subsequent retry.  This
00838 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
00839 ** to be adjusted.  The values are changed for all database connections
00840 ** within the same process.  The argument is a pointer to an array of two
00841 ** integers where the first integer i the new retry count and the second
00842 ** integer is the delay.  If either integer is negative, then the setting
00843 ** is not changed but instead the prior value of that setting is written
00844 ** into the array entry, allowing the current retry settings to be
00845 ** interrogated.  The zDbName parameter is ignored.
00846 **
00847 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
00848 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
00849 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
00850 ** write ahead log and shared memory files used for transaction control
00851 ** are automatically deleted when the latest connection to the database
00852 ** closes.  Setting persistent WAL mode causes those files to persist after
00853 ** close.  Persisting the files is useful when other processes that do not
00854 ** have write permission on the directory containing the database file want
00855 ** to read the database file, as the WAL and shared memory files must exist
00856 ** in order for the database to be readable.  The fourth parameter to
00857 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
00858 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
00859 ** WAL mode.  If the integer is -1, then it is overwritten with the current
00860 ** WAL persistence setting.
00861 **
00862 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
00863 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
00864 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
00865 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
00866 ** xDeviceCharacteristics methods. The fourth parameter to
00867 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
00868 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
00869 ** mode.  If the integer is -1, then it is overwritten with the current
00870 ** zero-damage mode setting.
00871 **
00872 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
00873 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
00874 ** a write transaction to indicate that, unless it is rolled back for some
00875 ** reason, the entire database file will be overwritten by the current 
00876 ** transaction. This is used by VACUUM operations.
00877 **
00878 ** <li>[[SQLITE_FCNTL_VFSNAME]]
00879 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
00880 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
00881 ** final bottom-level VFS are written into memory obtained from 
00882 ** [sqlite3_malloc()] and the result is stored in the char* variable
00883 ** that the fourth parameter of [sqlite3_file_control()] points to.
00884 ** The caller is responsible for freeing the memory when done.  As with
00885 ** all file-control actions, there is no guarantee that this will actually
00886 ** do anything.  Callers should initialize the char* variable to a NULL
00887 ** pointer in case this file-control is not implemented.  This file-control
00888 ** is intended for diagnostic use only.
00889 **
00890 ** <li>[[SQLITE_FCNTL_PRAGMA]]
00891 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
00892 ** file control is sent to the open [sqlite3_file] object corresponding
00893 ** to the database file to which the pragma statement refers. ^The argument
00894 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
00895 ** pointers to strings (char**) in which the second element of the array
00896 ** is the name of the pragma and the third element is the argument to the
00897 ** pragma or NULL if the pragma has no argument.  ^The handler for an
00898 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
00899 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
00900 ** or the equivalent and that string will become the result of the pragma or
00901 ** the error message if the pragma fails. ^If the
00902 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
00903 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
00904 ** file control returns [SQLITE_OK], then the parser assumes that the
00905 ** VFS has handled the PRAGMA itself and the parser generates a no-op
00906 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
00907 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
00908 ** that the VFS encountered an error while handling the [PRAGMA] and the
00909 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
00910 ** file control occurs at the beginning of pragma statement analysis and so
00911 ** it is able to override built-in [PRAGMA] statements.
00912 **
00913 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
00914 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
00915 ** file-control may be invoked by SQLite on the database file handle
00916 ** shortly after it is opened in order to provide a custom VFS with access
00917 ** to the connections busy-handler callback. The argument is of type (void **)
00918 ** - an array of two (void *) values. The first (void *) actually points
00919 ** to a function of type (int (*)(void *)). In order to invoke the connections
00920 ** busy-handler, this function should be invoked with the second (void *) in
00921 ** the array as the only argument. If it returns non-zero, then the operation
00922 ** should be retried. If it returns zero, the custom VFS should abandon the
00923 ** current operation.
00924 **
00925 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
00926 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
00927 ** to have SQLite generate a
00928 ** temporary filename using the same algorithm that is followed to generate
00929 ** temporary filenames for TEMP tables and other internal uses.  The
00930 ** argument should be a char** which will be filled with the filename
00931 ** written into memory obtained from [sqlite3_malloc()].  The caller should
00932 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
00933 **
00934 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
00935 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
00936 ** maximum number of bytes that will be used for memory-mapped I/O.
00937 ** The argument is a pointer to a value of type sqlite3_int64 that
00938 ** is an advisory maximum number of bytes in the file to memory map.  The
00939 ** pointer is overwritten with the old value.  The limit is not changed if
00940 ** the value originally pointed to is negative, and so the current limit 
00941 ** can be queried by passing in a pointer to a negative number.  This
00942 ** file-control is used internally to implement [PRAGMA mmap_size].
00943 **
00944 ** <li>[[SQLITE_FCNTL_TRACE]]
00945 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
00946 ** to the VFS about what the higher layers of the SQLite stack are doing.
00947 ** This file control is used by some VFS activity tracing [shims].
00948 ** The argument is a zero-terminated string.  Higher layers in the
00949 ** SQLite stack may generate instances of this file control if
00950 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
00951 **
00952 ** </ul>
00953 */
00954 #define SQLITE_FCNTL_LOCKSTATE               1
00955 #define SQLITE_GET_LOCKPROXYFILE             2
00956 #define SQLITE_SET_LOCKPROXYFILE             3
00957 #define SQLITE_LAST_ERRNO                    4
00958 #define SQLITE_FCNTL_SIZE_HINT               5
00959 #define SQLITE_FCNTL_CHUNK_SIZE              6
00960 #define SQLITE_FCNTL_FILE_POINTER            7
00961 #define SQLITE_FCNTL_SYNC_OMITTED            8
00962 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
00963 #define SQLITE_FCNTL_PERSIST_WAL            10
00964 #define SQLITE_FCNTL_OVERWRITE              11
00965 #define SQLITE_FCNTL_VFSNAME                12
00966 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
00967 #define SQLITE_FCNTL_PRAGMA                 14
00968 #define SQLITE_FCNTL_BUSYHANDLER            15
00969 #define SQLITE_FCNTL_TEMPFILENAME           16
00970 #define SQLITE_FCNTL_MMAP_SIZE              18
00971 #define SQLITE_FCNTL_TRACE                  19
00972 
00973 /*
00974 ** CAPI3REF: Mutex Handle
00975 **
00976 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
00977 ** abstract type for a mutex object.  The SQLite core never looks
00978 ** at the internal representation of an [sqlite3_mutex].  It only
00979 ** deals with pointers to the [sqlite3_mutex] object.
00980 **
00981 ** Mutexes are created using [sqlite3_mutex_alloc()].
00982 */
00983 typedef struct sqlite3_mutex sqlite3_mutex;
00984 
00985 /*
00986 ** CAPI3REF: OS Interface Object
00987 **
00988 ** An instance of the sqlite3_vfs object defines the interface between
00989 ** the SQLite core and the underlying operating system.  The "vfs"
00990 ** in the name of the object stands for "virtual file system".  See
00991 ** the [VFS | VFS documentation] for further information.
00992 **
00993 ** The value of the iVersion field is initially 1 but may be larger in
00994 ** future versions of SQLite.  Additional fields may be appended to this
00995 ** object when the iVersion value is increased.  Note that the structure
00996 ** of the sqlite3_vfs object changes in the transaction between
00997 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
00998 ** modified.
00999 **
01000 ** The szOsFile field is the size of the subclassed [sqlite3_file]
01001 ** structure used by this VFS.  mxPathname is the maximum length of
01002 ** a pathname in this VFS.
01003 **
01004 ** Registered sqlite3_vfs objects are kept on a linked list formed by
01005 ** the pNext pointer.  The [sqlite3_vfs_register()]
01006 ** and [sqlite3_vfs_unregister()] interfaces manage this list
01007 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
01008 ** searches the list.  Neither the application code nor the VFS
01009 ** implementation should use the pNext pointer.
01010 **
01011 ** The pNext field is the only field in the sqlite3_vfs
01012 ** structure that SQLite will ever modify.  SQLite will only access
01013 ** or modify this field while holding a particular static mutex.
01014 ** The application should never modify anything within the sqlite3_vfs
01015 ** object once the object has been registered.
01016 **
01017 ** The zName field holds the name of the VFS module.  The name must
01018 ** be unique across all VFS modules.
01019 **
01020 ** [[sqlite3_vfs.xOpen]]
01021 ** ^SQLite guarantees that the zFilename parameter to xOpen
01022 ** is either a NULL pointer or string obtained
01023 ** from xFullPathname() with an optional suffix added.
01024 ** ^If a suffix is added to the zFilename parameter, it will
01025 ** consist of a single "-" character followed by no more than
01026 ** 11 alphanumeric and/or "-" characters.
01027 ** ^SQLite further guarantees that
01028 ** the string will be valid and unchanged until xClose() is
01029 ** called. Because of the previous sentence,
01030 ** the [sqlite3_file] can safely store a pointer to the
01031 ** filename if it needs to remember the filename for some reason.
01032 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
01033 ** must invent its own temporary name for the file.  ^Whenever the 
01034 ** xFilename parameter is NULL it will also be the case that the
01035 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
01036 **
01037 ** The flags argument to xOpen() includes all bits set in
01038 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
01039 ** or [sqlite3_open16()] is used, then flags includes at least
01040 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
01041 ** If xOpen() opens a file read-only then it sets *pOutFlags to
01042 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
01043 **
01044 ** ^(SQLite will also add one of the following flags to the xOpen()
01045 ** call, depending on the object being opened:
01046 **
01047 ** <ul>
01048 ** <li>  [SQLITE_OPEN_MAIN_DB]
01049 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
01050 ** <li>  [SQLITE_OPEN_TEMP_DB]
01051 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
01052 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
01053 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
01054 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
01055 ** <li>  [SQLITE_OPEN_WAL]
01056 ** </ul>)^
01057 **
01058 ** The file I/O implementation can use the object type flags to
01059 ** change the way it deals with files.  For example, an application
01060 ** that does not care about crash recovery or rollback might make
01061 ** the open of a journal file a no-op.  Writes to this journal would
01062 ** also be no-ops, and any attempt to read the journal would return
01063 ** SQLITE_IOERR.  Or the implementation might recognize that a database
01064 ** file will be doing page-aligned sector reads and writes in a random
01065 ** order and set up its I/O subsystem accordingly.
01066 **
01067 ** SQLite might also add one of the following flags to the xOpen method:
01068 **
01069 ** <ul>
01070 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
01071 ** <li> [SQLITE_OPEN_EXCLUSIVE]
01072 ** </ul>
01073 **
01074 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
01075 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
01076 ** will be set for TEMP databases and their journals, transient
01077 ** databases, and subjournals.
01078 **
01079 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
01080 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
01081 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
01082 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
01083 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
01084 ** be created, and that it is an error if it already exists.
01085 ** It is <i>not</i> used to indicate the file should be opened 
01086 ** for exclusive access.
01087 **
01088 ** ^At least szOsFile bytes of memory are allocated by SQLite
01089 ** to hold the  [sqlite3_file] structure passed as the third
01090 ** argument to xOpen.  The xOpen method does not have to
01091 ** allocate the structure; it should just fill it in.  Note that
01092 ** the xOpen method must set the sqlite3_file.pMethods to either
01093 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
01094 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
01095 ** element will be valid after xOpen returns regardless of the success
01096 ** or failure of the xOpen call.
01097 **
01098 ** [[sqlite3_vfs.xAccess]]
01099 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
01100 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
01101 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
01102 ** to test whether a file is at least readable.   The file can be a
01103 ** directory.
01104 **
01105 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
01106 ** output buffer xFullPathname.  The exact size of the output buffer
01107 ** is also passed as a parameter to both  methods. If the output buffer
01108 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
01109 ** handled as a fatal error by SQLite, vfs implementations should endeavor
01110 ** to prevent this by setting mxPathname to a sufficiently large value.
01111 **
01112 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
01113 ** interfaces are not strictly a part of the filesystem, but they are
01114 ** included in the VFS structure for completeness.
01115 ** The xRandomness() function attempts to return nBytes bytes
01116 ** of good-quality randomness into zOut.  The return value is
01117 ** the actual number of bytes of randomness obtained.
01118 ** The xSleep() method causes the calling thread to sleep for at
01119 ** least the number of microseconds given.  ^The xCurrentTime()
01120 ** method returns a Julian Day Number for the current date and time as
01121 ** a floating point value.
01122 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
01123 ** Day Number multiplied by 86400000 (the number of milliseconds in 
01124 ** a 24-hour day).  
01125 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
01126 ** date and time if that method is available (if iVersion is 2 or 
01127 ** greater and the function pointer is not NULL) and will fall back
01128 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
01129 **
01130 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
01131 ** are not used by the SQLite core.  These optional interfaces are provided
01132 ** by some VFSes to facilitate testing of the VFS code. By overriding 
01133 ** system calls with functions under its control, a test program can
01134 ** simulate faults and error conditions that would otherwise be difficult
01135 ** or impossible to induce.  The set of system calls that can be overridden
01136 ** varies from one VFS to another, and from one version of the same VFS to the
01137 ** next.  Applications that use these interfaces must be prepared for any
01138 ** or all of these interfaces to be NULL or for their behavior to change
01139 ** from one release to the next.  Applications must not attempt to access
01140 ** any of these methods if the iVersion of the VFS is less than 3.
01141 */
01142 typedef struct sqlite3_vfs sqlite3_vfs;
01143 typedef void (*sqlite3_syscall_ptr)(void);
01144 struct sqlite3_vfs {
01145   int iVersion;            /* Structure version number (currently 3) */
01146   int szOsFile;            /* Size of subclassed sqlite3_file */
01147   int mxPathname;          /* Maximum file pathname length */
01148   sqlite3_vfs *pNext;      /* Next registered VFS */
01149   const char *zName;       /* Name of this virtual file system */
01150   void *pAppData;          /* Pointer to application-specific data */
01151   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
01152                int flags, int *pOutFlags);
01153   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
01154   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
01155   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
01156   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
01157   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
01158   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
01159   void (*xDlClose)(sqlite3_vfs*, void*);
01160   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
01161   int (*xSleep)(sqlite3_vfs*, int microseconds);
01162   int (*xCurrentTime)(sqlite3_vfs*, double*);
01163   int (*xGetLastError)(sqlite3_vfs*, int, char *);
01164   /*
01165   ** The methods above are in version 1 of the sqlite_vfs object
01166   ** definition.  Those that follow are added in version 2 or later
01167   */
01168   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
01169   /*
01170   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
01171   ** Those below are for version 3 and greater.
01172   */
01173   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
01174   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
01175   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
01176   /*
01177   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
01178   ** New fields may be appended in figure versions.  The iVersion
01179   ** value will increment whenever this happens. 
01180   */
01181 };
01182 
01183 /*
01184 ** CAPI3REF: Flags for the xAccess VFS method
01185 **
01186 ** These integer constants can be used as the third parameter to
01187 ** the xAccess method of an [sqlite3_vfs] object.  They determine
01188 ** what kind of permissions the xAccess method is looking for.
01189 ** With SQLITE_ACCESS_EXISTS, the xAccess method
01190 ** simply checks whether the file exists.
01191 ** With SQLITE_ACCESS_READWRITE, the xAccess method
01192 ** checks whether the named directory is both readable and writable
01193 ** (in other words, if files can be added, removed, and renamed within
01194 ** the directory).
01195 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
01196 ** [temp_store_directory pragma], though this could change in a future
01197 ** release of SQLite.
01198 ** With SQLITE_ACCESS_READ, the xAccess method
01199 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
01200 ** currently unused, though it might be used in a future release of
01201 ** SQLite.
01202 */
01203 #define SQLITE_ACCESS_EXISTS    0
01204 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
01205 #define SQLITE_ACCESS_READ      2   /* Unused */
01206 
01207 /*
01208 ** CAPI3REF: Flags for the xShmLock VFS method
01209 **
01210 ** These integer constants define the various locking operations
01211 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
01212 ** following are the only legal combinations of flags to the
01213 ** xShmLock method:
01214 **
01215 ** <ul>
01216 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
01217 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
01218 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
01219 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
01220 ** </ul>
01221 **
01222 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
01223 ** was given no the corresponding lock.  
01224 **
01225 ** The xShmLock method can transition between unlocked and SHARED or
01226 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
01227 ** and EXCLUSIVE.
01228 */
01229 #define SQLITE_SHM_UNLOCK       1
01230 #define SQLITE_SHM_LOCK         2
01231 #define SQLITE_SHM_SHARED       4
01232 #define SQLITE_SHM_EXCLUSIVE    8
01233 
01234 /*
01235 ** CAPI3REF: Maximum xShmLock index
01236 **
01237 ** The xShmLock method on [sqlite3_io_methods] may use values
01238 ** between 0 and this upper bound as its "offset" argument.
01239 ** The SQLite core will never attempt to acquire or release a
01240 ** lock outside of this range
01241 */
01242 #define SQLITE_SHM_NLOCK        8
01243 
01244 
01245 /*
01246 ** CAPI3REF: Initialize The SQLite Library
01247 **
01248 ** ^The sqlite3_initialize() routine initializes the
01249 ** SQLite library.  ^The sqlite3_shutdown() routine
01250 ** deallocates any resources that were allocated by sqlite3_initialize().
01251 ** These routines are designed to aid in process initialization and
01252 ** shutdown on embedded systems.  Workstation applications using
01253 ** SQLite normally do not need to invoke either of these routines.
01254 **
01255 ** A call to sqlite3_initialize() is an "effective" call if it is
01256 ** the first time sqlite3_initialize() is invoked during the lifetime of
01257 ** the process, or if it is the first time sqlite3_initialize() is invoked
01258 ** following a call to sqlite3_shutdown().  ^(Only an effective call
01259 ** of sqlite3_initialize() does any initialization.  All other calls
01260 ** are harmless no-ops.)^
01261 **
01262 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
01263 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
01264 ** an effective call to sqlite3_shutdown() does any deinitialization.
01265 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
01266 **
01267 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
01268 ** is not.  The sqlite3_shutdown() interface must only be called from a
01269 ** single thread.  All open [database connections] must be closed and all
01270 ** other SQLite resources must be deallocated prior to invoking
01271 ** sqlite3_shutdown().
01272 **
01273 ** Among other things, ^sqlite3_initialize() will invoke
01274 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
01275 ** will invoke sqlite3_os_end().
01276 **
01277 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
01278 ** ^If for some reason, sqlite3_initialize() is unable to initialize
01279 ** the library (perhaps it is unable to allocate a needed resource such
01280 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
01281 **
01282 ** ^The sqlite3_initialize() routine is called internally by many other
01283 ** SQLite interfaces so that an application usually does not need to
01284 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
01285 ** calls sqlite3_initialize() so the SQLite library will be automatically
01286 ** initialized when [sqlite3_open()] is called if it has not be initialized
01287 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
01288 ** compile-time option, then the automatic calls to sqlite3_initialize()
01289 ** are omitted and the application must call sqlite3_initialize() directly
01290 ** prior to using any other SQLite interface.  For maximum portability,
01291 ** it is recommended that applications always invoke sqlite3_initialize()
01292 ** directly prior to using any other SQLite interface.  Future releases
01293 ** of SQLite may require this.  In other words, the behavior exhibited
01294 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
01295 ** default behavior in some future release of SQLite.
01296 **
01297 ** The sqlite3_os_init() routine does operating-system specific
01298 ** initialization of the SQLite library.  The sqlite3_os_end()
01299 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
01300 ** performed by these routines include allocation or deallocation
01301 ** of static resources, initialization of global variables,
01302 ** setting up a default [sqlite3_vfs] module, or setting up
01303 ** a default configuration using [sqlite3_config()].
01304 **
01305 ** The application should never invoke either sqlite3_os_init()
01306 ** or sqlite3_os_end() directly.  The application should only invoke
01307 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
01308 ** interface is called automatically by sqlite3_initialize() and
01309 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
01310 ** implementations for sqlite3_os_init() and sqlite3_os_end()
01311 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
01312 ** When [custom builds | built for other platforms]
01313 ** (using the [SQLITE_OS_OTHER=1] compile-time
01314 ** option) the application must supply a suitable implementation for
01315 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
01316 ** implementation of sqlite3_os_init() or sqlite3_os_end()
01317 ** must return [SQLITE_OK] on success and some other [error code] upon
01318 ** failure.
01319 */
01320 SQLITE_API int sqlite3_initialize(void);
01321 SQLITE_API int sqlite3_shutdown(void);
01322 SQLITE_API int sqlite3_os_init(void);
01323 SQLITE_API int sqlite3_os_end(void);
01324 
01325 /*
01326 ** CAPI3REF: Configuring The SQLite Library
01327 **
01328 ** The sqlite3_config() interface is used to make global configuration
01329 ** changes to SQLite in order to tune SQLite to the specific needs of
01330 ** the application.  The default configuration is recommended for most
01331 ** applications and so this routine is usually not necessary.  It is
01332 ** provided to support rare applications with unusual needs.
01333 **
01334 ** The sqlite3_config() interface is not threadsafe.  The application
01335 ** must insure that no other SQLite interfaces are invoked by other
01336 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
01337 ** may only be invoked prior to library initialization using
01338 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
01339 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
01340 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
01341 ** Note, however, that ^sqlite3_config() can be called as part of the
01342 ** implementation of an application-defined [sqlite3_os_init()].
01343 **
01344 ** The first argument to sqlite3_config() is an integer
01345 ** [configuration option] that determines
01346 ** what property of SQLite is to be configured.  Subsequent arguments
01347 ** vary depending on the [configuration option]
01348 ** in the first argument.
01349 **
01350 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
01351 ** ^If the option is unknown or SQLite is unable to set the option
01352 ** then this routine returns a non-zero [error code].
01353 */
01354 SQLITE_API int sqlite3_config(int, ...);
01355 
01356 /*
01357 ** CAPI3REF: Configure database connections
01358 **
01359 ** The sqlite3_db_config() interface is used to make configuration
01360 ** changes to a [database connection].  The interface is similar to
01361 ** [sqlite3_config()] except that the changes apply to a single
01362 ** [database connection] (specified in the first argument).
01363 **
01364 ** The second argument to sqlite3_db_config(D,V,...)  is the
01365 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
01366 ** that indicates what aspect of the [database connection] is being configured.
01367 ** Subsequent arguments vary depending on the configuration verb.
01368 **
01369 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
01370 ** the call is considered successful.
01371 */
01372 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
01373 
01374 /*
01375 ** CAPI3REF: Memory Allocation Routines
01376 **
01377 ** An instance of this object defines the interface between SQLite
01378 ** and low-level memory allocation routines.
01379 **
01380 ** This object is used in only one place in the SQLite interface.
01381 ** A pointer to an instance of this object is the argument to
01382 ** [sqlite3_config()] when the configuration option is
01383 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
01384 ** By creating an instance of this object
01385 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
01386 ** during configuration, an application can specify an alternative
01387 ** memory allocation subsystem for SQLite to use for all of its
01388 ** dynamic memory needs.
01389 **
01390 ** Note that SQLite comes with several [built-in memory allocators]
01391 ** that are perfectly adequate for the overwhelming majority of applications
01392 ** and that this object is only useful to a tiny minority of applications
01393 ** with specialized memory allocation requirements.  This object is
01394 ** also used during testing of SQLite in order to specify an alternative
01395 ** memory allocator that simulates memory out-of-memory conditions in
01396 ** order to verify that SQLite recovers gracefully from such
01397 ** conditions.
01398 **
01399 ** The xMalloc, xRealloc, and xFree methods must work like the
01400 ** malloc(), realloc() and free() functions from the standard C library.
01401 ** ^SQLite guarantees that the second argument to
01402 ** xRealloc is always a value returned by a prior call to xRoundup.
01403 **
01404 ** xSize should return the allocated size of a memory allocation
01405 ** previously obtained from xMalloc or xRealloc.  The allocated size
01406 ** is always at least as big as the requested size but may be larger.
01407 **
01408 ** The xRoundup method returns what would be the allocated size of
01409 ** a memory allocation given a particular requested size.  Most memory
01410 ** allocators round up memory allocations at least to the next multiple
01411 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
01412 ** Every memory allocation request coming in through [sqlite3_malloc()]
01413 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
01414 ** that causes the corresponding memory allocation to fail.
01415 **
01416 ** The xInit method initializes the memory allocator.  For example,
01417 ** it might allocate any require mutexes or initialize internal data
01418 ** structures.  The xShutdown method is invoked (indirectly) by
01419 ** [sqlite3_shutdown()] and should deallocate any resources acquired
01420 ** by xInit.  The pAppData pointer is used as the only parameter to
01421 ** xInit and xShutdown.
01422 **
01423 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
01424 ** the xInit method, so the xInit method need not be threadsafe.  The
01425 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
01426 ** not need to be threadsafe either.  For all other methods, SQLite
01427 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
01428 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
01429 ** it is by default) and so the methods are automatically serialized.
01430 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
01431 ** methods must be threadsafe or else make their own arrangements for
01432 ** serialization.
01433 **
01434 ** SQLite will never invoke xInit() more than once without an intervening
01435 ** call to xShutdown().
01436 */
01437 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
01438 struct sqlite3_mem_methods {
01439   void *(*xMalloc)(int);         /* Memory allocation function */
01440   void (*xFree)(void*);          /* Free a prior allocation */
01441   void *(*xRealloc)(void*,int);  /* Resize an allocation */
01442   int (*xSize)(void*);           /* Return the size of an allocation */
01443   int (*xRoundup)(int);          /* Round up request size to allocation size */
01444   int (*xInit)(void*);           /* Initialize the memory allocator */
01445   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
01446   void *pAppData;                /* Argument to xInit() and xShutdown() */
01447 };
01448 
01449 /*
01450 ** CAPI3REF: Configuration Options
01451 ** KEYWORDS: {configuration option}
01452 **
01453 ** These constants are the available integer configuration options that
01454 ** can be passed as the first argument to the [sqlite3_config()] interface.
01455 **
01456 ** New configuration options may be added in future releases of SQLite.
01457 ** Existing configuration options might be discontinued.  Applications
01458 ** should check the return code from [sqlite3_config()] to make sure that
01459 ** the call worked.  The [sqlite3_config()] interface will return a
01460 ** non-zero [error code] if a discontinued or unsupported configuration option
01461 ** is invoked.
01462 **
01463 ** <dl>
01464 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
01465 ** <dd>There are no arguments to this option.  ^This option sets the
01466 ** [threading mode] to Single-thread.  In other words, it disables
01467 ** all mutexing and puts SQLite into a mode where it can only be used
01468 ** by a single thread.   ^If SQLite is compiled with
01469 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
01470 ** it is not possible to change the [threading mode] from its default
01471 ** value of Single-thread and so [sqlite3_config()] will return 
01472 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
01473 ** configuration option.</dd>
01474 **
01475 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
01476 ** <dd>There are no arguments to this option.  ^This option sets the
01477 ** [threading mode] to Multi-thread.  In other words, it disables
01478 ** mutexing on [database connection] and [prepared statement] objects.
01479 ** The application is responsible for serializing access to
01480 ** [database connections] and [prepared statements].  But other mutexes
01481 ** are enabled so that SQLite will be safe to use in a multi-threaded
01482 ** environment as long as no two threads attempt to use the same
01483 ** [database connection] at the same time.  ^If SQLite is compiled with
01484 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
01485 ** it is not possible to set the Multi-thread [threading mode] and
01486 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
01487 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
01488 **
01489 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
01490 ** <dd>There are no arguments to this option.  ^This option sets the
01491 ** [threading mode] to Serialized. In other words, this option enables
01492 ** all mutexes including the recursive
01493 ** mutexes on [database connection] and [prepared statement] objects.
01494 ** In this mode (which is the default when SQLite is compiled with
01495 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
01496 ** to [database connections] and [prepared statements] so that the
01497 ** application is free to use the same [database connection] or the
01498 ** same [prepared statement] in different threads at the same time.
01499 ** ^If SQLite is compiled with
01500 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
01501 ** it is not possible to set the Serialized [threading mode] and
01502 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
01503 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
01504 **
01505 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
01506 ** <dd> ^(This option takes a single argument which is a pointer to an
01507 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
01508 ** alternative low-level memory allocation routines to be used in place of
01509 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
01510 ** its own private copy of the content of the [sqlite3_mem_methods] structure
01511 ** before the [sqlite3_config()] call returns.</dd>
01512 **
01513 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
01514 ** <dd> ^(This option takes a single argument which is a pointer to an
01515 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
01516 ** structure is filled with the currently defined memory allocation routines.)^
01517 ** This option can be used to overload the default memory allocation
01518 ** routines with a wrapper that simulations memory allocation failure or
01519 ** tracks memory usage, for example. </dd>
01520 **
01521 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
01522 ** <dd> ^This option takes single argument of type int, interpreted as a 
01523 ** boolean, which enables or disables the collection of memory allocation 
01524 ** statistics. ^(When memory allocation statistics are disabled, the 
01525 ** following SQLite interfaces become non-operational:
01526 **   <ul>
01527 **   <li> [sqlite3_memory_used()]
01528 **   <li> [sqlite3_memory_highwater()]
01529 **   <li> [sqlite3_soft_heap_limit64()]
01530 **   <li> [sqlite3_status()]
01531 **   </ul>)^
01532 ** ^Memory allocation statistics are enabled by default unless SQLite is
01533 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
01534 ** allocation statistics are disabled by default.
01535 ** </dd>
01536 **
01537 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
01538 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
01539 ** scratch memory.  There are three arguments:  A pointer an 8-byte
01540 ** aligned memory buffer from which the scratch allocations will be
01541 ** drawn, the size of each scratch allocation (sz),
01542 ** and the maximum number of scratch allocations (N).  The sz
01543 ** argument must be a multiple of 16.
01544 ** The first argument must be a pointer to an 8-byte aligned buffer
01545 ** of at least sz*N bytes of memory.
01546 ** ^SQLite will use no more than two scratch buffers per thread.  So
01547 ** N should be set to twice the expected maximum number of threads.
01548 ** ^SQLite will never require a scratch buffer that is more than 6
01549 ** times the database page size. ^If SQLite needs needs additional
01550 ** scratch memory beyond what is provided by this configuration option, then 
01551 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
01552 **
01553 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
01554 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
01555 ** the database page cache with the default page cache implementation.  
01556 ** This configuration should not be used if an application-define page
01557 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
01558 ** There are three arguments to this option: A pointer to 8-byte aligned
01559 ** memory, the size of each page buffer (sz), and the number of pages (N).
01560 ** The sz argument should be the size of the largest database page
01561 ** (a power of two between 512 and 32768) plus a little extra for each
01562 ** page header.  ^The page header size is 20 to 40 bytes depending on
01563 ** the host architecture.  ^It is harmless, apart from the wasted memory,
01564 ** to make sz a little too large.  The first
01565 ** argument should point to an allocation of at least sz*N bytes of memory.
01566 ** ^SQLite will use the memory provided by the first argument to satisfy its
01567 ** memory needs for the first N pages that it adds to cache.  ^If additional
01568 ** page cache memory is needed beyond what is provided by this option, then
01569 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
01570 ** The pointer in the first argument must
01571 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
01572 ** will be undefined.</dd>
01573 **
01574 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
01575 ** <dd> ^This option specifies a static memory buffer that SQLite will use
01576 ** for all of its dynamic memory allocation needs beyond those provided
01577 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
01578 ** There are three arguments: An 8-byte aligned pointer to the memory,
01579 ** the number of bytes in the memory buffer, and the minimum allocation size.
01580 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
01581 ** to using its default memory allocator (the system malloc() implementation),
01582 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
01583 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
01584 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
01585 ** allocator is engaged to handle all of SQLites memory allocation needs.
01586 ** The first pointer (the memory pointer) must be aligned to an 8-byte
01587 ** boundary or subsequent behavior of SQLite will be undefined.
01588 ** The minimum allocation size is capped at 2**12. Reasonable values
01589 ** for the minimum allocation size are 2**5 through 2**8.</dd>
01590 **
01591 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
01592 ** <dd> ^(This option takes a single argument which is a pointer to an
01593 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
01594 ** alternative low-level mutex routines to be used in place
01595 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
01596 ** content of the [sqlite3_mutex_methods] structure before the call to
01597 ** [sqlite3_config()] returns. ^If SQLite is compiled with
01598 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
01599 ** the entire mutexing subsystem is omitted from the build and hence calls to
01600 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
01601 ** return [SQLITE_ERROR].</dd>
01602 **
01603 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
01604 ** <dd> ^(This option takes a single argument which is a pointer to an
01605 ** instance of the [sqlite3_mutex_methods] structure.  The
01606 ** [sqlite3_mutex_methods]
01607 ** structure is filled with the currently defined mutex routines.)^
01608 ** This option can be used to overload the default mutex allocation
01609 ** routines with a wrapper used to track mutex usage for performance
01610 ** profiling or testing, for example.   ^If SQLite is compiled with
01611 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
01612 ** the entire mutexing subsystem is omitted from the build and hence calls to
01613 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
01614 ** return [SQLITE_ERROR].</dd>
01615 **
01616 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
01617 ** <dd> ^(This option takes two arguments that determine the default
01618 ** memory allocation for the lookaside memory allocator on each
01619 ** [database connection].  The first argument is the
01620 ** size of each lookaside buffer slot and the second is the number of
01621 ** slots allocated to each database connection.)^  ^(This option sets the
01622 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
01623 ** verb to [sqlite3_db_config()] can be used to change the lookaside
01624 ** configuration on individual connections.)^ </dd>
01625 **
01626 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
01627 ** <dd> ^(This option takes a single argument which is a pointer to
01628 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
01629 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
01630 ** object and uses it for page cache memory allocations.</dd>
01631 **
01632 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
01633 ** <dd> ^(This option takes a single argument which is a pointer to an
01634 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
01635 ** page cache implementation into that object.)^ </dd>
01636 **
01637 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
01638 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
01639 ** global [error log].
01640 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
01641 ** function with a call signature of void(*)(void*,int,const char*), 
01642 ** and a pointer to void. ^If the function pointer is not NULL, it is
01643 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
01644 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
01645 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
01646 ** passed through as the first parameter to the application-defined logger
01647 ** function whenever that function is invoked.  ^The second parameter to
01648 ** the logger function is a copy of the first parameter to the corresponding
01649 ** [sqlite3_log()] call and is intended to be a [result code] or an
01650 ** [extended result code].  ^The third parameter passed to the logger is
01651 ** log message after formatting via [sqlite3_snprintf()].
01652 ** The SQLite logging interface is not reentrant; the logger function
01653 ** supplied by the application must not invoke any SQLite interface.
01654 ** In a multi-threaded application, the application-defined logger
01655 ** function must be threadsafe. </dd>
01656 **
01657 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
01658 ** <dd>^(This option takes a single argument of type int. If non-zero, then
01659 ** URI handling is globally enabled. If the parameter is zero, then URI handling
01660 ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
01661 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
01662 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
01663 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
01664 ** connection is opened. ^If it is globally disabled, filenames are
01665 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
01666 ** database connection is opened. ^(By default, URI handling is globally
01667 ** disabled. The default value may be changed by compiling with the
01668 ** [SQLITE_USE_URI] symbol defined.)^
01669 **
01670 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
01671 ** <dd>^This option takes a single integer argument which is interpreted as
01672 ** a boolean in order to enable or disable the use of covering indices for
01673 ** full table scans in the query optimizer.  ^The default setting is determined
01674 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
01675 ** if that compile-time option is omitted.
01676 ** The ability to disable the use of covering indices for full table scans
01677 ** is because some incorrectly coded legacy applications might malfunction
01678 ** when the optimization is enabled.  Providing the ability to
01679 ** disable the optimization allows the older, buggy application code to work
01680 ** without change even with newer versions of SQLite.
01681 **
01682 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
01683 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
01684 ** <dd> These options are obsolete and should not be used by new code.
01685 ** They are retained for backwards compatibility but are now no-ops.
01686 ** </dd>
01687 **
01688 ** [[SQLITE_CONFIG_SQLLOG]]
01689 ** <dt>SQLITE_CONFIG_SQLLOG
01690 ** <dd>This option is only available if sqlite is compiled with the
01691 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
01692 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
01693 ** The second should be of type (void*). The callback is invoked by the library
01694 ** in three separate circumstances, identified by the value passed as the
01695 ** fourth parameter. If the fourth parameter is 0, then the database connection
01696 ** passed as the second argument has just been opened. The third argument
01697 ** points to a buffer containing the name of the main database file. If the
01698 ** fourth parameter is 1, then the SQL statement that the third parameter
01699 ** points to has just been executed. Or, if the fourth parameter is 2, then
01700 ** the connection being passed as the second parameter is being closed. The
01701 ** third parameter is passed NULL In this case.  An example of using this
01702 ** configuration option can be seen in the "test_sqllog.c" source file in
01703 ** the canonical SQLite source tree.</dd>
01704 **
01705 ** [[SQLITE_CONFIG_MMAP_SIZE]]
01706 ** <dt>SQLITE_CONFIG_MMAP_SIZE
01707 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
01708 ** that are the default mmap size limit (the default setting for
01709 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
01710 ** ^The default setting can be overridden by each database connection using
01711 ** either the [PRAGMA mmap_size] command, or by using the
01712 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
01713 ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
01714 ** exceed the compile-time maximum mmap size set by the
01715 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
01716 ** ^If either argument to this option is negative, then that argument is
01717 ** changed to its compile-time default.
01718 **
01719 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
01720 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
01721 ** <dd>^This option is only available if SQLite is compiled for Windows
01722 ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
01723 ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
01724 ** that specifies the maximum size of the created heap.
01725 ** </dl>
01726 */
01727 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
01728 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
01729 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
01730 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
01731 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
01732 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
01733 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
01734 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
01735 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
01736 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
01737 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
01738 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
01739 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
01740 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
01741 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
01742 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
01743 #define SQLITE_CONFIG_URI          17  /* int */
01744 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
01745 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
01746 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
01747 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
01748 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
01749 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
01750 
01751 /*
01752 ** CAPI3REF: Database Connection Configuration Options
01753 **
01754 ** These constants are the available integer configuration options that
01755 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
01756 **
01757 ** New configuration options may be added in future releases of SQLite.
01758 ** Existing configuration options might be discontinued.  Applications
01759 ** should check the return code from [sqlite3_db_config()] to make sure that
01760 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
01761 ** non-zero [error code] if a discontinued or unsupported configuration option
01762 ** is invoked.
01763 **
01764 ** <dl>
01765 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
01766 ** <dd> ^This option takes three additional arguments that determine the 
01767 ** [lookaside memory allocator] configuration for the [database connection].
01768 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
01769 ** pointer to a memory buffer to use for lookaside memory.
01770 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
01771 ** may be NULL in which case SQLite will allocate the
01772 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
01773 ** size of each lookaside buffer slot.  ^The third argument is the number of
01774 ** slots.  The size of the buffer in the first argument must be greater than
01775 ** or equal to the product of the second and third arguments.  The buffer
01776 ** must be aligned to an 8-byte boundary.  ^If the second argument to
01777 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
01778 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
01779 ** configuration for a database connection can only be changed when that
01780 ** connection is not currently using lookaside memory, or in other words
01781 ** when the "current value" returned by
01782 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
01783 ** Any attempt to change the lookaside memory configuration when lookaside
01784 ** memory is in use leaves the configuration unchanged and returns 
01785 ** [SQLITE_BUSY].)^</dd>
01786 **
01787 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
01788 ** <dd> ^This option is used to enable or disable the enforcement of
01789 ** [foreign key constraints].  There should be two additional arguments.
01790 ** The first argument is an integer which is 0 to disable FK enforcement,
01791 ** positive to enable FK enforcement or negative to leave FK enforcement
01792 ** unchanged.  The second parameter is a pointer to an integer into which
01793 ** is written 0 or 1 to indicate whether FK enforcement is off or on
01794 ** following this call.  The second parameter may be a NULL pointer, in
01795 ** which case the FK enforcement setting is not reported back. </dd>
01796 **
01797 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
01798 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
01799 ** There should be two additional arguments.
01800 ** The first argument is an integer which is 0 to disable triggers,
01801 ** positive to enable triggers or negative to leave the setting unchanged.
01802 ** The second parameter is a pointer to an integer into which
01803 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
01804 ** following this call.  The second parameter may be a NULL pointer, in
01805 ** which case the trigger setting is not reported back. </dd>
01806 **
01807 ** </dl>
01808 */
01809 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
01810 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
01811 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
01812 
01813 
01814 /*
01815 ** CAPI3REF: Enable Or Disable Extended Result Codes
01816 **
01817 ** ^The sqlite3_extended_result_codes() routine enables or disables the
01818 ** [extended result codes] feature of SQLite. ^The extended result
01819 ** codes are disabled by default for historical compatibility.
01820 */
01821 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
01822 
01823 /*
01824 ** CAPI3REF: Last Insert Rowid
01825 **
01826 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
01827 ** has a unique 64-bit signed
01828 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
01829 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
01830 ** names are not also used by explicitly declared columns. ^If
01831 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
01832 ** is another alias for the rowid.
01833 **
01834 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the 
01835 ** most recent successful [INSERT] into a rowid table or [virtual table]
01836 ** on database connection D.
01837 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
01838 ** ^If no successful [INSERT]s into rowid tables
01839 ** have ever occurred on the database connection D, 
01840 ** then sqlite3_last_insert_rowid(D) returns zero.
01841 **
01842 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
01843 ** method, then this routine will return the [rowid] of the inserted
01844 ** row as long as the trigger or virtual table method is running.
01845 ** But once the trigger or virtual table method ends, the value returned 
01846 ** by this routine reverts to what it was before the trigger or virtual
01847 ** table method began.)^
01848 **
01849 ** ^An [INSERT] that fails due to a constraint violation is not a
01850 ** successful [INSERT] and does not change the value returned by this
01851 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
01852 ** and INSERT OR ABORT make no changes to the return value of this
01853 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
01854 ** encounters a constraint violation, it does not fail.  The
01855 ** INSERT continues to completion after deleting rows that caused
01856 ** the constraint problem so INSERT OR REPLACE will always change
01857 ** the return value of this interface.)^
01858 **
01859 ** ^For the purposes of this routine, an [INSERT] is considered to
01860 ** be successful even if it is subsequently rolled back.
01861 **
01862 ** This function is accessible to SQL statements via the
01863 ** [last_insert_rowid() SQL function].
01864 **
01865 ** If a separate thread performs a new [INSERT] on the same
01866 ** database connection while the [sqlite3_last_insert_rowid()]
01867 ** function is running and thus changes the last insert [rowid],
01868 ** then the value returned by [sqlite3_last_insert_rowid()] is
01869 ** unpredictable and might not equal either the old or the new
01870 ** last insert [rowid].
01871 */
01872 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
01873 
01874 /*
01875 ** CAPI3REF: Count The Number Of Rows Modified
01876 **
01877 ** ^This function returns the number of database rows that were changed
01878 ** or inserted or deleted by the most recently completed SQL statement
01879 ** on the [database connection] specified by the first parameter.
01880 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
01881 ** or [DELETE] statement are counted.  Auxiliary changes caused by
01882 ** triggers or [foreign key actions] are not counted.)^ Use the
01883 ** [sqlite3_total_changes()] function to find the total number of changes
01884 ** including changes caused by triggers and foreign key actions.
01885 **
01886 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
01887 ** are not counted.  Only real table changes are counted.
01888 **
01889 ** ^(A "row change" is a change to a single row of a single table
01890 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
01891 ** are changed as side effects of [REPLACE] constraint resolution,
01892 ** rollback, ABORT processing, [DROP TABLE], or by any other
01893 ** mechanisms do not count as direct row changes.)^
01894 **
01895 ** A "trigger context" is a scope of execution that begins and
01896 ** ends with the script of a [CREATE TRIGGER | trigger]. 
01897 ** Most SQL statements are
01898 ** evaluated outside of any trigger.  This is the "top level"
01899 ** trigger context.  If a trigger fires from the top level, a
01900 ** new trigger context is entered for the duration of that one
01901 ** trigger.  Subtriggers create subcontexts for their duration.
01902 **
01903 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
01904 ** not create a new trigger context.
01905 **
01906 ** ^This function returns the number of direct row changes in the
01907 ** most recent INSERT, UPDATE, or DELETE statement within the same
01908 ** trigger context.
01909 **
01910 ** ^Thus, when called from the top level, this function returns the
01911 ** number of changes in the most recent INSERT, UPDATE, or DELETE
01912 ** that also occurred at the top level.  ^(Within the body of a trigger,
01913 ** the sqlite3_changes() interface can be called to find the number of
01914 ** changes in the most recently completed INSERT, UPDATE, or DELETE
01915 ** statement within the body of the same trigger.
01916 ** However, the number returned does not include changes
01917 ** caused by subtriggers since those have their own context.)^
01918 **
01919 ** See also the [sqlite3_total_changes()] interface, the
01920 ** [count_changes pragma], and the [changes() SQL function].
01921 **
01922 ** If a separate thread makes changes on the same database connection
01923 ** while [sqlite3_changes()] is running then the value returned
01924 ** is unpredictable and not meaningful.
01925 */
01926 SQLITE_API int sqlite3_changes(sqlite3*);
01927 
01928 /*
01929 ** CAPI3REF: Total Number Of Rows Modified
01930 **
01931 ** ^This function returns the number of row changes caused by [INSERT],
01932 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
01933 ** ^(The count returned by sqlite3_total_changes() includes all changes
01934 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
01935 ** [foreign key actions]. However,
01936 ** the count does not include changes used to implement [REPLACE] constraints,
01937 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
01938 ** count does not include rows of views that fire an [INSTEAD OF trigger],
01939 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
01940 ** are counted.)^
01941 ** ^The sqlite3_total_changes() function counts the changes as soon as
01942 ** the statement that makes them is completed (when the statement handle
01943 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
01944 **
01945 ** See also the [sqlite3_changes()] interface, the
01946 ** [count_changes pragma], and the [total_changes() SQL function].
01947 **
01948 ** If a separate thread makes changes on the same database connection
01949 ** while [sqlite3_total_changes()] is running then the value
01950 ** returned is unpredictable and not meaningful.
01951 */
01952 SQLITE_API int sqlite3_total_changes(sqlite3*);
01953 
01954 /*
01955 ** CAPI3REF: Interrupt A Long-Running Query
01956 **
01957 ** ^This function causes any pending database operation to abort and
01958 ** return at its earliest opportunity. This routine is typically
01959 ** called in response to a user action such as pressing "Cancel"
01960 ** or Ctrl-C where the user wants a long query operation to halt
01961 ** immediately.
01962 **
01963 ** ^It is safe to call this routine from a thread different from the
01964 ** thread that is currently running the database operation.  But it
01965 ** is not safe to call this routine with a [database connection] that
01966 ** is closed or might close before sqlite3_interrupt() returns.
01967 **
01968 ** ^If an SQL operation is very nearly finished at the time when
01969 ** sqlite3_interrupt() is called, then it might not have an opportunity
01970 ** to be interrupted and might continue to completion.
01971 **
01972 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
01973 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
01974 ** that is inside an explicit transaction, then the entire transaction
01975 ** will be rolled back automatically.
01976 **
01977 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
01978 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
01979 ** that are started after the sqlite3_interrupt() call and before the 
01980 ** running statements reaches zero are interrupted as if they had been
01981 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
01982 ** that are started after the running statement count reaches zero are
01983 ** not effected by the sqlite3_interrupt().
01984 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
01985 ** SQL statements is a no-op and has no effect on SQL statements
01986 ** that are started after the sqlite3_interrupt() call returns.
01987 **
01988 ** If the database connection closes while [sqlite3_interrupt()]
01989 ** is running then bad things will likely happen.
01990 */
01991 SQLITE_API void sqlite3_interrupt(sqlite3*);
01992 
01993 /*
01994 ** CAPI3REF: Determine If An SQL Statement Is Complete
01995 **
01996 ** These routines are useful during command-line input to determine if the
01997 ** currently entered text seems to form a complete SQL statement or
01998 ** if additional input is needed before sending the text into
01999 ** SQLite for parsing.  ^These routines return 1 if the input string
02000 ** appears to be a complete SQL statement.  ^A statement is judged to be
02001 ** complete if it ends with a semicolon token and is not a prefix of a
02002 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
02003 ** string literals or quoted identifier names or comments are not
02004 ** independent tokens (they are part of the token in which they are
02005 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
02006 ** and comments that follow the final semicolon are ignored.
02007 **
02008 ** ^These routines return 0 if the statement is incomplete.  ^If a
02009 ** memory allocation fails, then SQLITE_NOMEM is returned.
02010 **
02011 ** ^These routines do not parse the SQL statements thus
02012 ** will not detect syntactically incorrect SQL.
02013 **
02014 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
02015 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
02016 ** automatically by sqlite3_complete16().  If that initialization fails,
02017 ** then the return value from sqlite3_complete16() will be non-zero
02018 ** regardless of whether or not the input SQL is complete.)^
02019 **
02020 ** The input to [sqlite3_complete()] must be a zero-terminated
02021 ** UTF-8 string.
02022 **
02023 ** The input to [sqlite3_complete16()] must be a zero-terminated
02024 ** UTF-16 string in native byte order.
02025 */
02026 SQLITE_API int sqlite3_complete(const char *sql);
02027 SQLITE_API int sqlite3_complete16(const void *sql);
02028 
02029 /*
02030 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
02031 **
02032 ** ^This routine sets a callback function that might be invoked whenever
02033 ** an attempt is made to open a database table that another thread
02034 ** or process has locked.
02035 **
02036 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
02037 ** is returned immediately upon encountering the lock.  ^If the busy callback
02038 ** is not NULL, then the callback might be invoked with two arguments.
02039 **
02040 ** ^The first argument to the busy handler is a copy of the void* pointer which
02041 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
02042 ** the busy handler callback is the number of times that the busy handler has
02043 ** been invoked for this locking event.  ^If the
02044 ** busy callback returns 0, then no additional attempts are made to
02045 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
02046 ** ^If the callback returns non-zero, then another attempt
02047 ** is made to open the database for reading and the cycle repeats.
02048 **
02049 ** The presence of a busy handler does not guarantee that it will be invoked
02050 ** when there is lock contention. ^If SQLite determines that invoking the busy
02051 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
02052 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
02053 ** Consider a scenario where one process is holding a read lock that
02054 ** it is trying to promote to a reserved lock and
02055 ** a second process is holding a reserved lock that it is trying
02056 ** to promote to an exclusive lock.  The first process cannot proceed
02057 ** because it is blocked by the second and the second process cannot
02058 ** proceed because it is blocked by the first.  If both processes
02059 ** invoke the busy handlers, neither will make any progress.  Therefore,
02060 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
02061 ** will induce the first process to release its read lock and allow
02062 ** the second process to proceed.
02063 **
02064 ** ^The default busy callback is NULL.
02065 **
02066 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
02067 ** when SQLite is in the middle of a large transaction where all the
02068 ** changes will not fit into the in-memory cache.  SQLite will
02069 ** already hold a RESERVED lock on the database file, but it needs
02070 ** to promote this lock to EXCLUSIVE so that it can spill cache
02071 ** pages into the database file without harm to concurrent
02072 ** readers.  ^If it is unable to promote the lock, then the in-memory
02073 ** cache will be left in an inconsistent state and so the error
02074 ** code is promoted from the relatively benign [SQLITE_BUSY] to
02075 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
02076 ** forces an automatic rollback of the changes.  See the
02077 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
02078 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
02079 ** this is important.
02080 **
02081 ** ^(There can only be a single busy handler defined for each
02082 ** [database connection].  Setting a new busy handler clears any
02083 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
02084 ** will also set or clear the busy handler.
02085 **
02086 ** The busy callback should not take any actions which modify the
02087 ** database connection that invoked the busy handler.  Any such actions
02088 ** result in undefined behavior.
02089 ** 
02090 ** A busy handler must not close the database connection
02091 ** or [prepared statement] that invoked the busy handler.
02092 */
02093 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
02094 
02095 /*
02096 ** CAPI3REF: Set A Busy Timeout
02097 **
02098 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
02099 ** for a specified amount of time when a table is locked.  ^The handler
02100 ** will sleep multiple times until at least "ms" milliseconds of sleeping
02101 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
02102 ** the handler returns 0 which causes [sqlite3_step()] to return
02103 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
02104 **
02105 ** ^Calling this routine with an argument less than or equal to zero
02106 ** turns off all busy handlers.
02107 **
02108 ** ^(There can only be a single busy handler for a particular
02109 ** [database connection] any any given moment.  If another busy handler
02110 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
02111 ** this routine, that other busy handler is cleared.)^
02112 */
02113 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
02114 
02115 /*
02116 ** CAPI3REF: Convenience Routines For Running Queries
02117 **
02118 ** This is a legacy interface that is preserved for backwards compatibility.
02119 ** Use of this interface is not recommended.
02120 **
02121 ** Definition: A <b>result table</b> is memory data structure created by the
02122 ** [sqlite3_get_table()] interface.  A result table records the
02123 ** complete query results from one or more queries.
02124 **
02125 ** The table conceptually has a number of rows and columns.  But
02126 ** these numbers are not part of the result table itself.  These
02127 ** numbers are obtained separately.  Let N be the number of rows
02128 ** and M be the number of columns.
02129 **
02130 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
02131 ** There are (N+1)*M elements in the array.  The first M pointers point
02132 ** to zero-terminated strings that  contain the names of the columns.
02133 ** The remaining entries all point to query results.  NULL values result
02134 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
02135 ** string representation as returned by [sqlite3_column_text()].
02136 **
02137 ** A result table might consist of one or more memory allocations.
02138 ** It is not safe to pass a result table directly to [sqlite3_free()].
02139 ** A result table should be deallocated using [sqlite3_free_table()].
02140 **
02141 ** ^(As an example of the result table format, suppose a query result
02142 ** is as follows:
02143 **
02144 ** <blockquote><pre>
02145 **        Name        | Age
02146 **        -----------------------
02147 **        Alice       | 43
02148 **        Bob         | 28
02149 **        Cindy       | 21
02150 ** </pre></blockquote>
02151 **
02152 ** There are two column (M==2) and three rows (N==3).  Thus the
02153 ** result table has 8 entries.  Suppose the result table is stored
02154 ** in an array names azResult.  Then azResult holds this content:
02155 **
02156 ** <blockquote><pre>
02157 **        azResult&#91;0] = "Name";
02158 **        azResult&#91;1] = "Age";
02159 **        azResult&#91;2] = "Alice";
02160 **        azResult&#91;3] = "43";
02161 **        azResult&#91;4] = "Bob";
02162 **        azResult&#91;5] = "28";
02163 **        azResult&#91;6] = "Cindy";
02164 **        azResult&#91;7] = "21";
02165 ** </pre></blockquote>)^
02166 **
02167 ** ^The sqlite3_get_table() function evaluates one or more
02168 ** semicolon-separated SQL statements in the zero-terminated UTF-8
02169 ** string of its 2nd parameter and returns a result table to the
02170 ** pointer given in its 3rd parameter.
02171 **
02172 ** After the application has finished with the result from sqlite3_get_table(),
02173 ** it must pass the result table pointer to sqlite3_free_table() in order to
02174 ** release the memory that was malloced.  Because of the way the
02175 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
02176 ** function must not try to call [sqlite3_free()] directly.  Only
02177 ** [sqlite3_free_table()] is able to release the memory properly and safely.
02178 **
02179 ** The sqlite3_get_table() interface is implemented as a wrapper around
02180 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
02181 ** to any internal data structures of SQLite.  It uses only the public
02182 ** interface defined here.  As a consequence, errors that occur in the
02183 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
02184 ** reflected in subsequent calls to [sqlite3_errcode()] or
02185 ** [sqlite3_errmsg()].
02186 */
02187 SQLITE_API int sqlite3_get_table(
02188   sqlite3 *db,          /* An open database */
02189   const char *zSql,     /* SQL to be evaluated */
02190   char ***pazResult,    /* Results of the query */
02191   int *pnRow,           /* Number of result rows written here */
02192   int *pnColumn,        /* Number of result columns written here */
02193   char **pzErrmsg       /* Error msg written here */
02194 );
02195 SQLITE_API void sqlite3_free_table(char **result);
02196 
02197 /*
02198 ** CAPI3REF: Formatted String Printing Functions
02199 **
02200 ** These routines are work-alikes of the "printf()" family of functions
02201 ** from the standard C library.
02202 **
02203 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
02204 ** results into memory obtained from [sqlite3_malloc()].
02205 ** The strings returned by these two routines should be
02206 ** released by [sqlite3_free()].  ^Both routines return a
02207 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
02208 ** memory to hold the resulting string.
02209 **
02210 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
02211 ** the standard C library.  The result is written into the
02212 ** buffer supplied as the second parameter whose size is given by
02213 ** the first parameter. Note that the order of the
02214 ** first two parameters is reversed from snprintf().)^  This is an
02215 ** historical accident that cannot be fixed without breaking
02216 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
02217 ** returns a pointer to its buffer instead of the number of
02218 ** characters actually written into the buffer.)^  We admit that
02219 ** the number of characters written would be a more useful return
02220 ** value but we cannot change the implementation of sqlite3_snprintf()
02221 ** now without breaking compatibility.
02222 **
02223 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
02224 ** guarantees that the buffer is always zero-terminated.  ^The first
02225 ** parameter "n" is the total size of the buffer, including space for
02226 ** the zero terminator.  So the longest string that can be completely
02227 ** written will be n-1 characters.
02228 **
02229 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
02230 **
02231 ** These routines all implement some additional formatting
02232 ** options that are useful for constructing SQL statements.
02233 ** All of the usual printf() formatting options apply.  In addition, there
02234 ** is are "%q", "%Q", and "%z" options.
02235 **
02236 ** ^(The %q option works like %s in that it substitutes a nul-terminated
02237 ** string from the argument list.  But %q also doubles every '\'' character.
02238 ** %q is designed for use inside a string literal.)^  By doubling each '\''
02239 ** character it escapes that character and allows it to be inserted into
02240 ** the string.
02241 **
02242 ** For example, assume the string variable zText contains text as follows:
02243 **
02244 ** <blockquote><pre>
02245 **  char *zText = "It's a happy day!";
02246 ** </pre></blockquote>
02247 **
02248 ** One can use this text in an SQL statement as follows:
02249 **
02250 ** <blockquote><pre>
02251 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
02252 **  sqlite3_exec(db, zSQL, 0, 0, 0);
02253 **  sqlite3_free(zSQL);
02254 ** </pre></blockquote>
02255 **
02256 ** Because the %q format string is used, the '\'' character in zText
02257 ** is escaped and the SQL generated is as follows:
02258 **
02259 ** <blockquote><pre>
02260 **  INSERT INTO table1 VALUES('It''s a happy day!')
02261 ** </pre></blockquote>
02262 **
02263 ** This is correct.  Had we used %s instead of %q, the generated SQL
02264 ** would have looked like this:
02265 **
02266 ** <blockquote><pre>
02267 **  INSERT INTO table1 VALUES('It's a happy day!');
02268 ** </pre></blockquote>
02269 **
02270 ** This second example is an SQL syntax error.  As a general rule you should
02271 ** always use %q instead of %s when inserting text into a string literal.
02272 **
02273 ** ^(The %Q option works like %q except it also adds single quotes around
02274 ** the outside of the total string.  Additionally, if the parameter in the
02275 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
02276 ** single quotes).)^  So, for example, one could say:
02277 **
02278 ** <blockquote><pre>
02279 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
02280 **  sqlite3_exec(db, zSQL, 0, 0, 0);
02281 **  sqlite3_free(zSQL);
02282 ** </pre></blockquote>
02283 **
02284 ** The code above will render a correct SQL statement in the zSQL
02285 ** variable even if the zText variable is a NULL pointer.
02286 **
02287 ** ^(The "%z" formatting option works like "%s" but with the
02288 ** addition that after the string has been read and copied into
02289 ** the result, [sqlite3_free()] is called on the input string.)^
02290 */
02291 SQLITE_API char *sqlite3_mprintf(const char*,...);
02292 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
02293 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
02294 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
02295 
02296 /*
02297 ** CAPI3REF: Memory Allocation Subsystem
02298 **
02299 ** The SQLite core uses these three routines for all of its own
02300 ** internal memory allocation needs. "Core" in the previous sentence
02301 ** does not include operating-system specific VFS implementation.  The
02302 ** Windows VFS uses native malloc() and free() for some operations.
02303 **
02304 ** ^The sqlite3_malloc() routine returns a pointer to a block
02305 ** of memory at least N bytes in length, where N is the parameter.
02306 ** ^If sqlite3_malloc() is unable to obtain sufficient free
02307 ** memory, it returns a NULL pointer.  ^If the parameter N to
02308 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
02309 ** a NULL pointer.
02310 **
02311 ** ^Calling sqlite3_free() with a pointer previously returned
02312 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
02313 ** that it might be reused.  ^The sqlite3_free() routine is
02314 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
02315 ** to sqlite3_free() is harmless.  After being freed, memory
02316 ** should neither be read nor written.  Even reading previously freed
02317 ** memory might result in a segmentation fault or other severe error.
02318 ** Memory corruption, a segmentation fault, or other severe error
02319 ** might result if sqlite3_free() is called with a non-NULL pointer that
02320 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
02321 **
02322 ** ^(The sqlite3_realloc() interface attempts to resize a
02323 ** prior memory allocation to be at least N bytes, where N is the
02324 ** second parameter.  The memory allocation to be resized is the first
02325 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
02326 ** is a NULL pointer then its behavior is identical to calling
02327 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
02328 ** ^If the second parameter to sqlite3_realloc() is zero or
02329 ** negative then the behavior is exactly the same as calling
02330 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
02331 ** ^sqlite3_realloc() returns a pointer to a memory allocation
02332 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
02333 ** ^If M is the size of the prior allocation, then min(N,M) bytes
02334 ** of the prior allocation are copied into the beginning of buffer returned
02335 ** by sqlite3_realloc() and the prior allocation is freed.
02336 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
02337 ** is not freed.
02338 **
02339 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
02340 ** is always aligned to at least an 8 byte boundary, or to a
02341 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
02342 ** option is used.
02343 **
02344 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
02345 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
02346 ** implementation of these routines to be omitted.  That capability
02347 ** is no longer provided.  Only built-in memory allocators can be used.
02348 **
02349 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
02350 ** the system malloc() and free() directly when converting
02351 ** filenames between the UTF-8 encoding used by SQLite
02352 ** and whatever filename encoding is used by the particular Windows
02353 ** installation.  Memory allocation errors were detected, but
02354 ** they were reported back as [SQLITE_CANTOPEN] or
02355 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
02356 **
02357 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
02358 ** must be either NULL or else pointers obtained from a prior
02359 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
02360 ** not yet been released.
02361 **
02362 ** The application must not read or write any part of
02363 ** a block of memory after it has been released using
02364 ** [sqlite3_free()] or [sqlite3_realloc()].
02365 */
02366 SQLITE_API void *sqlite3_malloc(int);
02367 SQLITE_API void *sqlite3_realloc(void*, int);
02368 SQLITE_API void sqlite3_free(void*);
02369 
02370 /*
02371 ** CAPI3REF: Memory Allocator Statistics
02372 **
02373 ** SQLite provides these two interfaces for reporting on the status
02374 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
02375 ** routines, which form the built-in memory allocation subsystem.
02376 **
02377 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
02378 ** of memory currently outstanding (malloced but not freed).
02379 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
02380 ** value of [sqlite3_memory_used()] since the high-water mark
02381 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
02382 ** [sqlite3_memory_highwater()] include any overhead
02383 ** added by SQLite in its implementation of [sqlite3_malloc()],
02384 ** but not overhead added by the any underlying system library
02385 ** routines that [sqlite3_malloc()] may call.
02386 **
02387 ** ^The memory high-water mark is reset to the current value of
02388 ** [sqlite3_memory_used()] if and only if the parameter to
02389 ** [sqlite3_memory_highwater()] is true.  ^The value returned
02390 ** by [sqlite3_memory_highwater(1)] is the high-water mark
02391 ** prior to the reset.
02392 */
02393 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
02394 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
02395 
02396 /*
02397 ** CAPI3REF: Pseudo-Random Number Generator
02398 **
02399 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
02400 ** select random [ROWID | ROWIDs] when inserting new records into a table that
02401 ** already uses the largest possible [ROWID].  The PRNG is also used for
02402 ** the build-in random() and randomblob() SQL functions.  This interface allows
02403 ** applications to access the same PRNG for other purposes.
02404 **
02405 ** ^A call to this routine stores N bytes of randomness into buffer P.
02406 **
02407 ** ^The first time this routine is invoked (either internally or by
02408 ** the application) the PRNG is seeded using randomness obtained
02409 ** from the xRandomness method of the default [sqlite3_vfs] object.
02410 ** ^On all subsequent invocations, the pseudo-randomness is generated
02411 ** internally and without recourse to the [sqlite3_vfs] xRandomness
02412 ** method.
02413 */
02414 SQLITE_API void sqlite3_randomness(int N, void *P);
02415 
02416 /*
02417 ** CAPI3REF: Compile-Time Authorization Callbacks
02418 **
02419 ** ^This routine registers an authorizer callback with a particular
02420 ** [database connection], supplied in the first argument.
02421 ** ^The authorizer callback is invoked as SQL statements are being compiled
02422 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
02423 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
02424 ** points during the compilation process, as logic is being created
02425 ** to perform various actions, the authorizer callback is invoked to
02426 ** see if those actions are allowed.  ^The authorizer callback should
02427 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
02428 ** specific action but allow the SQL statement to continue to be
02429 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
02430 ** rejected with an error.  ^If the authorizer callback returns
02431 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
02432 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
02433 ** the authorizer will fail with an error message.
02434 **
02435 ** When the callback returns [SQLITE_OK], that means the operation
02436 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
02437 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
02438 ** authorizer will fail with an error message explaining that
02439 ** access is denied. 
02440 **
02441 ** ^The first parameter to the authorizer callback is a copy of the third
02442 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
02443 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
02444 ** the particular action to be authorized. ^The third through sixth parameters
02445 ** to the callback are zero-terminated strings that contain additional
02446 ** details about the action to be authorized.
02447 **
02448 ** ^If the action code is [SQLITE_READ]
02449 ** and the callback returns [SQLITE_IGNORE] then the
02450 ** [prepared statement] statement is constructed to substitute
02451 ** a NULL value in place of the table column that would have
02452 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
02453 ** return can be used to deny an untrusted user access to individual
02454 ** columns of a table.
02455 ** ^If the action code is [SQLITE_DELETE] and the callback returns
02456 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
02457 ** [truncate optimization] is disabled and all rows are deleted individually.
02458 **
02459 ** An authorizer is used when [sqlite3_prepare | preparing]
02460 ** SQL statements from an untrusted source, to ensure that the SQL statements
02461 ** do not try to access data they are not allowed to see, or that they do not
02462 ** try to execute malicious statements that damage the database.  For
02463 ** example, an application may allow a user to enter arbitrary
02464 ** SQL queries for evaluation by a database.  But the application does
02465 ** not want the user to be able to make arbitrary changes to the
02466 ** database.  An authorizer could then be put in place while the
02467 ** user-entered SQL is being [sqlite3_prepare | prepared] that
02468 ** disallows everything except [SELECT] statements.
02469 **
02470 ** Applications that need to process SQL from untrusted sources
02471 ** might also consider lowering resource limits using [sqlite3_limit()]
02472 ** and limiting database size using the [max_page_count] [PRAGMA]
02473 ** in addition to using an authorizer.
02474 **
02475 ** ^(Only a single authorizer can be in place on a database connection
02476 ** at a time.  Each call to sqlite3_set_authorizer overrides the
02477 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
02478 ** The authorizer is disabled by default.
02479 **
02480 ** The authorizer callback must not do anything that will modify
02481 ** the database connection that invoked the authorizer callback.
02482 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
02483 ** database connections for the meaning of "modify" in this paragraph.
02484 **
02485 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
02486 ** statement might be re-prepared during [sqlite3_step()] due to a 
02487 ** schema change.  Hence, the application should ensure that the
02488 ** correct authorizer callback remains in place during the [sqlite3_step()].
02489 **
02490 ** ^Note that the authorizer callback is invoked only during
02491 ** [sqlite3_prepare()] or its variants.  Authorization is not
02492 ** performed during statement evaluation in [sqlite3_step()], unless
02493 ** as stated in the previous paragraph, sqlite3_step() invokes
02494 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
02495 */
02496 SQLITE_API int sqlite3_set_authorizer(
02497   sqlite3*,
02498   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
02499   void *pUserData
02500 );
02501 
02502 /*
02503 ** CAPI3REF: Authorizer Return Codes
02504 **
02505 ** The [sqlite3_set_authorizer | authorizer callback function] must
02506 ** return either [SQLITE_OK] or one of these two constants in order
02507 ** to signal SQLite whether or not the action is permitted.  See the
02508 ** [sqlite3_set_authorizer | authorizer documentation] for additional
02509 ** information.
02510 **
02511 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
02512 ** from the [sqlite3_vtab_on_conflict()] interface.
02513 */
02514 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
02515 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
02516 
02517 /*
02518 ** CAPI3REF: Authorizer Action Codes
02519 **
02520 ** The [sqlite3_set_authorizer()] interface registers a callback function
02521 ** that is invoked to authorize certain SQL statement actions.  The
02522 ** second parameter to the callback is an integer code that specifies
02523 ** what action is being authorized.  These are the integer action codes that
02524 ** the authorizer callback may be passed.
02525 **
02526 ** These action code values signify what kind of operation is to be
02527 ** authorized.  The 3rd and 4th parameters to the authorization
02528 ** callback function will be parameters or NULL depending on which of these
02529 ** codes is used as the second parameter.  ^(The 5th parameter to the
02530 ** authorizer callback is the name of the database ("main", "temp",
02531 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
02532 ** is the name of the inner-most trigger or view that is responsible for
02533 ** the access attempt or NULL if this access attempt is directly from
02534 ** top-level SQL code.
02535 */
02536 /******************************************* 3rd ************ 4th ***********/
02537 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
02538 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
02539 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
02540 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
02541 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
02542 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
02543 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
02544 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
02545 #define SQLITE_DELETE                9   /* Table Name      NULL            */
02546 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
02547 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
02548 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
02549 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
02550 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
02551 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
02552 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
02553 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
02554 #define SQLITE_INSERT               18   /* Table Name      NULL            */
02555 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
02556 #define SQLITE_READ                 20   /* Table Name      Column Name     */
02557 #define SQLITE_SELECT               21   /* NULL            NULL            */
02558 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
02559 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
02560 #define SQLITE_ATTACH               24   /* Filename        NULL            */
02561 #define SQLITE_DETACH               25   /* Database Name   NULL            */
02562 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
02563 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
02564 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
02565 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
02566 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
02567 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
02568 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
02569 #define SQLITE_COPY                  0   /* No longer used */
02570 
02571 /*
02572 ** CAPI3REF: Tracing And Profiling Functions
02573 **
02574 ** These routines register callback functions that can be used for
02575 ** tracing and profiling the execution of SQL statements.
02576 **
02577 ** ^The callback function registered by sqlite3_trace() is invoked at
02578 ** various times when an SQL statement is being run by [sqlite3_step()].
02579 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
02580 ** SQL statement text as the statement first begins executing.
02581 ** ^(Additional sqlite3_trace() callbacks might occur
02582 ** as each triggered subprogram is entered.  The callbacks for triggers
02583 ** contain a UTF-8 SQL comment that identifies the trigger.)^
02584 **
02585 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
02586 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
02587 **
02588 ** ^The callback function registered by sqlite3_profile() is invoked
02589 ** as each SQL statement finishes.  ^The profile callback contains
02590 ** the original statement text and an estimate of wall-clock time
02591 ** of how long that statement took to run.  ^The profile callback
02592 ** time is in units of nanoseconds, however the current implementation
02593 ** is only capable of millisecond resolution so the six least significant
02594 ** digits in the time are meaningless.  Future versions of SQLite
02595 ** might provide greater resolution on the profiler callback.  The
02596 ** sqlite3_profile() function is considered experimental and is
02597 ** subject to change in future versions of SQLite.
02598 */
02599 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
02600 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
02601    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
02602 
02603 /*
02604 ** CAPI3REF: Query Progress Callbacks
02605 **
02606 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
02607 ** function X to be invoked periodically during long running calls to
02608 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
02609 ** database connection D.  An example use for this
02610 ** interface is to keep a GUI updated during a large query.
02611 **
02612 ** ^The parameter P is passed through as the only parameter to the 
02613 ** callback function X.  ^The parameter N is the approximate number of 
02614 ** [virtual machine instructions] that are evaluated between successive
02615 ** invocations of the callback X.  ^If N is less than one then the progress
02616 ** handler is disabled.
02617 **
02618 ** ^Only a single progress handler may be defined at one time per
02619 ** [database connection]; setting a new progress handler cancels the
02620 ** old one.  ^Setting parameter X to NULL disables the progress handler.
02621 ** ^The progress handler is also disabled by setting N to a value less
02622 ** than 1.
02623 **
02624 ** ^If the progress callback returns non-zero, the operation is
02625 ** interrupted.  This feature can be used to implement a
02626 ** "Cancel" button on a GUI progress dialog box.
02627 **
02628 ** The progress handler callback must not do anything that will modify
02629 ** the database connection that invoked the progress handler.
02630 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
02631 ** database connections for the meaning of "modify" in this paragraph.
02632 **
02633 */
02634 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
02635 
02636 /*
02637 ** CAPI3REF: Opening A New Database Connection
02638 **
02639 ** ^These routines open an SQLite database file as specified by the 
02640 ** filename argument. ^The filename argument is interpreted as UTF-8 for
02641 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
02642 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
02643 ** returned in *ppDb, even if an error occurs.  The only exception is that
02644 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
02645 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
02646 ** object.)^ ^(If the database is opened (and/or created) successfully, then
02647 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
02648 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
02649 ** an English language description of the error following a failure of any
02650 ** of the sqlite3_open() routines.
02651 **
02652 ** ^The default encoding for the database will be UTF-8 if
02653 ** sqlite3_open() or sqlite3_open_v2() is called and
02654 ** UTF-16 in the native byte order if sqlite3_open16() is used.
02655 **
02656 ** Whether or not an error occurs when it is opened, resources
02657 ** associated with the [database connection] handle should be released by
02658 ** passing it to [sqlite3_close()] when it is no longer required.
02659 **
02660 ** The sqlite3_open_v2() interface works like sqlite3_open()
02661 ** except that it accepts two additional parameters for additional control
02662 ** over the new database connection.  ^(The flags parameter to
02663 ** sqlite3_open_v2() can take one of
02664 ** the following three values, optionally combined with the 
02665 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
02666 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
02667 **
02668 ** <dl>
02669 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
02670 ** <dd>The database is opened in read-only mode.  If the database does not
02671 ** already exist, an error is returned.</dd>)^
02672 **
02673 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
02674 ** <dd>The database is opened for reading and writing if possible, or reading
02675 ** only if the file is write protected by the operating system.  In either
02676 ** case the database must already exist, otherwise an error is returned.</dd>)^
02677 **
02678 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
02679 ** <dd>The database is opened for reading and writing, and is created if
02680 ** it does not already exist. This is the behavior that is always used for
02681 ** sqlite3_open() and sqlite3_open16().</dd>)^
02682 ** </dl>
02683 **
02684 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
02685 ** combinations shown above optionally combined with other
02686 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
02687 ** then the behavior is undefined.
02688 **
02689 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
02690 ** opens in the multi-thread [threading mode] as long as the single-thread
02691 ** mode has not been set at compile-time or start-time.  ^If the
02692 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
02693 ** in the serialized [threading mode] unless single-thread was
02694 ** previously selected at compile-time or start-time.
02695 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
02696 ** eligible to use [shared cache mode], regardless of whether or not shared
02697 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
02698 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
02699 ** participate in [shared cache mode] even if it is enabled.
02700 **
02701 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
02702 ** [sqlite3_vfs] object that defines the operating system interface that
02703 ** the new database connection should use.  ^If the fourth parameter is
02704 ** a NULL pointer then the default [sqlite3_vfs] object is used.
02705 **
02706 ** ^If the filename is ":memory:", then a private, temporary in-memory database
02707 ** is created for the connection.  ^This in-memory database will vanish when
02708 ** the database connection is closed.  Future versions of SQLite might
02709 ** make use of additional special filenames that begin with the ":" character.
02710 ** It is recommended that when a database filename actually does begin with
02711 ** a ":" character you should prefix the filename with a pathname such as
02712 ** "./" to avoid ambiguity.
02713 **
02714 ** ^If the filename is an empty string, then a private, temporary
02715 ** on-disk database will be created.  ^This private database will be
02716 ** automatically deleted as soon as the database connection is closed.
02717 **
02718 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
02719 **
02720 ** ^If [URI filename] interpretation is enabled, and the filename argument
02721 ** begins with "file:", then the filename is interpreted as a URI. ^URI
02722 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
02723 ** set in the fourth argument to sqlite3_open_v2(), or if it has
02724 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
02725 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
02726 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
02727 ** by default, but future releases of SQLite might enable URI filename
02728 ** interpretation by default.  See "[URI filenames]" for additional
02729 ** information.
02730 **
02731 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
02732 ** authority, then it must be either an empty string or the string 
02733 ** "localhost". ^If the authority is not an empty string or "localhost", an 
02734 ** error is returned to the caller. ^The fragment component of a URI, if 
02735 ** present, is ignored.
02736 **
02737 ** ^SQLite uses the path component of the URI as the name of the disk file
02738 ** which contains the database. ^If the path begins with a '/' character, 
02739 ** then it is interpreted as an absolute path. ^If the path does not begin 
02740 ** with a '/' (meaning that the authority section is omitted from the URI)
02741 ** then the path is interpreted as a relative path. 
02742 ** ^On windows, the first component of an absolute path 
02743 ** is a drive specification (e.g. "C:").
02744 **
02745 ** [[core URI query parameters]]
02746 ** The query component of a URI may contain parameters that are interpreted
02747 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
02748 ** SQLite interprets the following three query parameters:
02749 **
02750 ** <ul>
02751 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
02752 **     a VFS object that provides the operating system interface that should
02753 **     be used to access the database file on disk. ^If this option is set to
02754 **     an empty string the default VFS object is used. ^Specifying an unknown
02755 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
02756 **     present, then the VFS specified by the option takes precedence over
02757 **     the value passed as the fourth parameter to sqlite3_open_v2().
02758 **
02759 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
02760 **     "rwc", or "memory". Attempting to set it to any other value is
02761 **     an error)^. 
02762 **     ^If "ro" is specified, then the database is opened for read-only 
02763 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
02764 **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
02765 **     "rw", then the database is opened for read-write (but not create) 
02766 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
02767 **     been set. ^Value "rwc" is equivalent to setting both 
02768 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
02769 **     set to "memory" then a pure [in-memory database] that never reads
02770 **     or writes from disk is used. ^It is an error to specify a value for
02771 **     the mode parameter that is less restrictive than that specified by
02772 **     the flags passed in the third parameter to sqlite3_open_v2().
02773 **
02774 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
02775 **     "private". ^Setting it to "shared" is equivalent to setting the
02776 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
02777 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
02778 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
02779 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
02780 **     a URI filename, its value overrides any behavior requested by setting
02781 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
02782 ** </ul>
02783 **
02784 ** ^Specifying an unknown parameter in the query component of a URI is not an
02785 ** error.  Future versions of SQLite might understand additional query
02786 ** parameters.  See "[query parameters with special meaning to SQLite]" for
02787 ** additional information.
02788 **
02789 ** [[URI filename examples]] <h3>URI filename examples</h3>
02790 **
02791 ** <table border="1" align=center cellpadding=5>
02792 ** <tr><th> URI filenames <th> Results
02793 ** <tr><td> file:data.db <td> 
02794 **          Open the file "data.db" in the current directory.
02795 ** <tr><td> file:/home/fred/data.db<br>
02796 **          file:///home/fred/data.db <br> 
02797 **          file://localhost/home/fred/data.db <br> <td> 
02798 **          Open the database file "/home/fred/data.db".
02799 ** <tr><td> file://darkstar/home/fred/data.db <td> 
02800 **          An error. "darkstar" is not a recognized authority.
02801 ** <tr><td style="white-space:nowrap"> 
02802 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
02803 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
02804 **          C:. Note that the %20 escaping in this example is not strictly 
02805 **          necessary - space characters can be used literally
02806 **          in URI filenames.
02807 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
02808 **          Open file "data.db" in the current directory for read-only access.
02809 **          Regardless of whether or not shared-cache mode is enabled by
02810 **          default, use a private cache.
02811 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
02812 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
02813 ** <tr><td> file:data.db?mode=readonly <td> 
02814 **          An error. "readonly" is not a valid option for the "mode" parameter.
02815 ** </table>
02816 **
02817 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
02818 ** query components of a URI. A hexadecimal escape sequence consists of a
02819 ** percent sign - "%" - followed by exactly two hexadecimal digits 
02820 ** specifying an octet value. ^Before the path or query components of a
02821 ** URI filename are interpreted, they are encoded using UTF-8 and all 
02822 ** hexadecimal escape sequences replaced by a single byte containing the
02823 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
02824 ** the results are undefined.
02825 **
02826 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
02827 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
02828 ** codepage is currently defined.  Filenames containing international
02829 ** characters must be converted to UTF-8 prior to passing them into
02830 ** sqlite3_open() or sqlite3_open_v2().
02831 **
02832 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
02833 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
02834 ** features that require the use of temporary files may fail.
02835 **
02836 ** See also: [sqlite3_temp_directory]
02837 */
02838 SQLITE_API int sqlite3_open(
02839   const char *filename,   /* Database filename (UTF-8) */
02840   sqlite3 **ppDb          /* OUT: SQLite db handle */
02841 );
02842 SQLITE_API int sqlite3_open16(
02843   const void *filename,   /* Database filename (UTF-16) */
02844   sqlite3 **ppDb          /* OUT: SQLite db handle */
02845 );
02846 SQLITE_API int sqlite3_open_v2(
02847   const char *filename,   /* Database filename (UTF-8) */
02848   sqlite3 **ppDb,         /* OUT: SQLite db handle */
02849   int flags,              /* Flags */
02850   const char *zVfs        /* Name of VFS module to use */
02851 );
02852 
02853 /*
02854 ** CAPI3REF: Obtain Values For URI Parameters
02855 **
02856 ** These are utility routines, useful to VFS implementations, that check
02857 ** to see if a database file was a URI that contained a specific query 
02858 ** parameter, and if so obtains the value of that query parameter.
02859 **
02860 ** If F is the database filename pointer passed into the xOpen() method of 
02861 ** a VFS implementation when the flags parameter to xOpen() has one or 
02862 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
02863 ** P is the name of the query parameter, then
02864 ** sqlite3_uri_parameter(F,P) returns the value of the P
02865 ** parameter if it exists or a NULL pointer if P does not appear as a 
02866 ** query parameter on F.  If P is a query parameter of F
02867 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
02868 ** a pointer to an empty string.
02869 **
02870 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
02871 ** parameter and returns true (1) or false (0) according to the value
02872 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
02873 ** value of query parameter P is one of "yes", "true", or "on" in any
02874 ** case or if the value begins with a non-zero number.  The 
02875 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
02876 ** query parameter P is one of "no", "false", or "off" in any case or
02877 ** if the value begins with a numeric zero.  If P is not a query
02878 ** parameter on F or if the value of P is does not match any of the
02879 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
02880 **
02881 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
02882 ** 64-bit signed integer and returns that integer, or D if P does not
02883 ** exist.  If the value of P is something other than an integer, then
02884 ** zero is returned.
02885 ** 
02886 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
02887 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
02888 ** is not a database file pathname pointer that SQLite passed into the xOpen
02889 ** VFS method, then the behavior of this routine is undefined and probably
02890 ** undesirable.
02891 */
02892 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
02893 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
02894 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
02895 
02896 
02897 /*
02898 ** CAPI3REF: Error Codes And Messages
02899 **
02900 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
02901 ** [extended result code] for the most recent failed sqlite3_* API call
02902 ** associated with a [database connection]. If a prior API call failed
02903 ** but the most recent API call succeeded, the return value from
02904 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
02905 ** interface is the same except that it always returns the 
02906 ** [extended result code] even when extended result codes are
02907 ** disabled.
02908 **
02909 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
02910 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
02911 ** ^(Memory to hold the error message string is managed internally.
02912 ** The application does not need to worry about freeing the result.
02913 ** However, the error string might be overwritten or deallocated by
02914 ** subsequent calls to other SQLite interface functions.)^
02915 **
02916 ** ^The sqlite3_errstr() interface returns the English-language text
02917 ** that describes the [result code], as UTF-8.
02918 ** ^(Memory to hold the error message string is managed internally
02919 ** and must not be freed by the application)^.
02920 **
02921 ** When the serialized [threading mode] is in use, it might be the
02922 ** case that a second error occurs on a separate thread in between
02923 ** the time of the first error and the call to these interfaces.
02924 ** When that happens, the second error will be reported since these
02925 ** interfaces always report the most recent result.  To avoid
02926 ** this, each thread can obtain exclusive use of the [database connection] D
02927 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
02928 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
02929 ** all calls to the interfaces listed here are completed.
02930 **
02931 ** If an interface fails with SQLITE_MISUSE, that means the interface
02932 ** was invoked incorrectly by the application.  In that case, the
02933 ** error code and message may or may not be set.
02934 */
02935 SQLITE_API int sqlite3_errcode(sqlite3 *db);
02936 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
02937 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
02938 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
02939 SQLITE_API const char *sqlite3_errstr(int);
02940 
02941 /*
02942 ** CAPI3REF: SQL Statement Object
02943 ** KEYWORDS: {prepared statement} {prepared statements}
02944 **
02945 ** An instance of this object represents a single SQL statement.
02946 ** This object is variously known as a "prepared statement" or a
02947 ** "compiled SQL statement" or simply as a "statement".
02948 **
02949 ** The life of a statement object goes something like this:
02950 **
02951 ** <ol>
02952 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
02953 **      function.
02954 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
02955 **      interfaces.
02956 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
02957 ** <li> Reset the statement using [sqlite3_reset()] then go back
02958 **      to step 2.  Do this zero or more times.
02959 ** <li> Destroy the object using [sqlite3_finalize()].
02960 ** </ol>
02961 **
02962 ** Refer to documentation on individual methods above for additional
02963 ** information.
02964 */
02965 typedef struct sqlite3_stmt sqlite3_stmt;
02966 
02967 /*
02968 ** CAPI3REF: Run-time Limits
02969 **
02970 ** ^(This interface allows the size of various constructs to be limited
02971 ** on a connection by connection basis.  The first parameter is the
02972 ** [database connection] whose limit is to be set or queried.  The
02973 ** second parameter is one of the [limit categories] that define a
02974 ** class of constructs to be size limited.  The third parameter is the
02975 ** new limit for that construct.)^
02976 **
02977 ** ^If the new limit is a negative number, the limit is unchanged.
02978 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
02979 ** [limits | hard upper bound]
02980 ** set at compile-time by a C preprocessor macro called
02981 ** [limits | SQLITE_MAX_<i>NAME</i>].
02982 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
02983 ** ^Attempts to increase a limit above its hard upper bound are
02984 ** silently truncated to the hard upper bound.
02985 **
02986 ** ^Regardless of whether or not the limit was changed, the 
02987 ** [sqlite3_limit()] interface returns the prior value of the limit.
02988 ** ^Hence, to find the current value of a limit without changing it,
02989 ** simply invoke this interface with the third parameter set to -1.
02990 **
02991 ** Run-time limits are intended for use in applications that manage
02992 ** both their own internal database and also databases that are controlled
02993 ** by untrusted external sources.  An example application might be a
02994 ** web browser that has its own databases for storing history and
02995 ** separate databases controlled by JavaScript applications downloaded
02996 ** off the Internet.  The internal databases can be given the
02997 ** large, default limits.  Databases managed by external sources can
02998 ** be given much smaller limits designed to prevent a denial of service
02999 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
03000 ** interface to further control untrusted SQL.  The size of the database
03001 ** created by an untrusted script can be contained using the
03002 ** [max_page_count] [PRAGMA].
03003 **
03004 ** New run-time limit categories may be added in future releases.
03005 */
03006 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
03007 
03008 /*
03009 ** CAPI3REF: Run-Time Limit Categories
03010 ** KEYWORDS: {limit category} {*limit categories}
03011 **
03012 ** These constants define various performance limits
03013 ** that can be lowered at run-time using [sqlite3_limit()].
03014 ** The synopsis of the meanings of the various limits is shown below.
03015 ** Additional information is available at [limits | Limits in SQLite].
03016 **
03017 ** <dl>
03018 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
03019 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
03020 **
03021 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
03022 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
03023 **
03024 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
03025 ** <dd>The maximum number of columns in a table definition or in the
03026 ** result set of a [SELECT] or the maximum number of columns in an index
03027 ** or in an ORDER BY or GROUP BY clause.</dd>)^
03028 **
03029 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
03030 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
03031 **
03032 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
03033 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
03034 **
03035 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
03036 ** <dd>The maximum number of instructions in a virtual machine program
03037 ** used to implement an SQL statement.  This limit is not currently
03038 ** enforced, though that might be added in some future release of
03039 ** SQLite.</dd>)^
03040 **
03041 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
03042 ** <dd>The maximum number of arguments on a function.</dd>)^
03043 **
03044 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
03045 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
03046 **
03047 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
03048 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
03049 ** <dd>The maximum length of the pattern argument to the [LIKE] or
03050 ** [GLOB] operators.</dd>)^
03051 **
03052 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
03053 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
03054 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
03055 **
03056 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
03057 ** <dd>The maximum depth of recursion for triggers.</dd>)^
03058 ** </dl>
03059 */
03060 #define SQLITE_LIMIT_LENGTH                    0
03061 #define SQLITE_LIMIT_SQL_LENGTH                1
03062 #define SQLITE_LIMIT_COLUMN                    2
03063 #define SQLITE_LIMIT_EXPR_DEPTH                3
03064 #define SQLITE_LIMIT_COMPOUND_SELECT           4
03065 #define SQLITE_LIMIT_VDBE_OP                   5
03066 #define SQLITE_LIMIT_FUNCTION_ARG              6
03067 #define SQLITE_LIMIT_ATTACHED                  7
03068 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
03069 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
03070 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
03071 
03072 /*
03073 ** CAPI3REF: Compiling An SQL Statement
03074 ** KEYWORDS: {SQL statement compiler}
03075 **
03076 ** To execute an SQL query, it must first be compiled into a byte-code
03077 ** program using one of these routines.
03078 **
03079 ** The first argument, "db", is a [database connection] obtained from a
03080 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
03081 ** [sqlite3_open16()].  The database connection must not have been closed.
03082 **
03083 ** The second argument, "zSql", is the statement to be compiled, encoded
03084 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
03085 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
03086 ** use UTF-16.
03087 **
03088 ** ^If the nByte argument is less than zero, then zSql is read up to the
03089 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
03090 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
03091 ** zSql string ends at either the first '\000' or '\u0000' character or
03092 ** the nByte-th byte, whichever comes first. If the caller knows
03093 ** that the supplied string is nul-terminated, then there is a small
03094 ** performance advantage to be gained by passing an nByte parameter that
03095 ** is equal to the number of bytes in the input string <i>including</i>
03096 ** the nul-terminator bytes as this saves SQLite from having to
03097 ** make a copy of the input string.
03098 **
03099 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
03100 ** past the end of the first SQL statement in zSql.  These routines only
03101 ** compile the first statement in zSql, so *pzTail is left pointing to
03102 ** what remains uncompiled.
03103 **
03104 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
03105 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
03106 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
03107 ** string or a comment) then *ppStmt is set to NULL.
03108 ** The calling procedure is responsible for deleting the compiled
03109 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
03110 ** ppStmt may not be NULL.
03111 **
03112 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
03113 ** otherwise an [error code] is returned.
03114 **
03115 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
03116 ** recommended for all new programs. The two older interfaces are retained
03117 ** for backwards compatibility, but their use is discouraged.
03118 ** ^In the "v2" interfaces, the prepared statement
03119 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
03120 ** original SQL text. This causes the [sqlite3_step()] interface to
03121 ** behave differently in three ways:
03122 **
03123 ** <ol>
03124 ** <li>
03125 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
03126 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
03127 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
03128 ** retries will occur before sqlite3_step() gives up and returns an error.
03129 ** </li>
03130 **
03131 ** <li>
03132 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
03133 ** [error codes] or [extended error codes].  ^The legacy behavior was that
03134 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
03135 ** and the application would have to make a second call to [sqlite3_reset()]
03136 ** in order to find the underlying cause of the problem. With the "v2" prepare
03137 ** interfaces, the underlying reason for the error is returned immediately.
03138 ** </li>
03139 **
03140 ** <li>
03141 ** ^If the specific value bound to [parameter | host parameter] in the 
03142 ** WHERE clause might influence the choice of query plan for a statement,
03143 ** then the statement will be automatically recompiled, as if there had been 
03144 ** a schema change, on the first  [sqlite3_step()] call following any change
03145 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
03146 ** ^The specific value of WHERE-clause [parameter] might influence the 
03147 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
03148 ** or [GLOB] operator or if the parameter is compared to an indexed column
03149 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
03150 ** </li>
03151 ** </ol>
03152 */
03153 SQLITE_API int sqlite3_prepare(
03154   sqlite3 *db,            /* Database handle */
03155   const char *zSql,       /* SQL statement, UTF-8 encoded */
03156   int nByte,              /* Maximum length of zSql in bytes. */
03157   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
03158   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
03159 );
03160 SQLITE_API int sqlite3_prepare_v2(
03161   sqlite3 *db,            /* Database handle */
03162   const char *zSql,       /* SQL statement, UTF-8 encoded */
03163   int nByte,              /* Maximum length of zSql in bytes. */
03164   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
03165   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
03166 );
03167 SQLITE_API int sqlite3_prepare16(
03168   sqlite3 *db,            /* Database handle */
03169   const void *zSql,       /* SQL statement, UTF-16 encoded */
03170   int nByte,              /* Maximum length of zSql in bytes. */
03171   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
03172   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
03173 );
03174 SQLITE_API int sqlite3_prepare16_v2(
03175   sqlite3 *db,            /* Database handle */
03176   const void *zSql,       /* SQL statement, UTF-16 encoded */
03177   int nByte,              /* Maximum length of zSql in bytes. */
03178   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
03179   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
03180 );
03181 
03182 /*
03183 ** CAPI3REF: Retrieving Statement SQL
03184 **
03185 ** ^This interface can be used to retrieve a saved copy of the original
03186 ** SQL text used to create a [prepared statement] if that statement was
03187 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
03188 */
03189 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
03190 
03191 /*
03192 ** CAPI3REF: Determine If An SQL Statement Writes The Database
03193 **
03194 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
03195 ** and only if the [prepared statement] X makes no direct changes to
03196 ** the content of the database file.
03197 **
03198 ** Note that [application-defined SQL functions] or
03199 ** [virtual tables] might change the database indirectly as a side effect.  
03200 ** ^(For example, if an application defines a function "eval()" that 
03201 ** calls [sqlite3_exec()], then the following SQL statement would
03202 ** change the database file through side-effects:
03203 **
03204 ** <blockquote><pre>
03205 **    SELECT eval('DELETE FROM t1') FROM t2;
03206 ** </pre></blockquote>
03207 **
03208 ** But because the [SELECT] statement does not change the database file
03209 ** directly, sqlite3_stmt_readonly() would still return true.)^
03210 **
03211 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
03212 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
03213 ** since the statements themselves do not actually modify the database but
03214 ** rather they control the timing of when other statements modify the 
03215 ** database.  ^The [ATTACH] and [DETACH] statements also cause
03216 ** sqlite3_stmt_readonly() to return true since, while those statements
03217 ** change the configuration of a database connection, they do not make 
03218 ** changes to the content of the database files on disk.
03219 */
03220 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
03221 
03222 /*
03223 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
03224 **
03225 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
03226 ** [prepared statement] S has been stepped at least once using 
03227 ** [sqlite3_step(S)] but has not run to completion and/or has not 
03228 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
03229 ** interface returns false if S is a NULL pointer.  If S is not a 
03230 ** NULL pointer and is not a pointer to a valid [prepared statement]
03231 ** object, then the behavior is undefined and probably undesirable.
03232 **
03233 ** This interface can be used in combination [sqlite3_next_stmt()]
03234 ** to locate all prepared statements associated with a database 
03235 ** connection that are in need of being reset.  This can be used,
03236 ** for example, in diagnostic routines to search for prepared 
03237 ** statements that are holding a transaction open.
03238 */
03239 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
03240 
03241 /*
03242 ** CAPI3REF: Dynamically Typed Value Object
03243 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
03244 **
03245 ** SQLite uses the sqlite3_value object to represent all values
03246 ** that can be stored in a database table. SQLite uses dynamic typing
03247 ** for the values it stores.  ^Values stored in sqlite3_value objects
03248 ** can be integers, floating point values, strings, BLOBs, or NULL.
03249 **
03250 ** An sqlite3_value object may be either "protected" or "unprotected".
03251 ** Some interfaces require a protected sqlite3_value.  Other interfaces
03252 ** will accept either a protected or an unprotected sqlite3_value.
03253 ** Every interface that accepts sqlite3_value arguments specifies
03254 ** whether or not it requires a protected sqlite3_value.
03255 **
03256 ** The terms "protected" and "unprotected" refer to whether or not
03257 ** a mutex is held.  An internal mutex is held for a protected
03258 ** sqlite3_value object but no mutex is held for an unprotected
03259 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
03260 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
03261 ** or if SQLite is run in one of reduced mutex modes 
03262 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
03263 ** then there is no distinction between protected and unprotected
03264 ** sqlite3_value objects and they can be used interchangeably.  However,
03265 ** for maximum code portability it is recommended that applications
03266 ** still make the distinction between protected and unprotected
03267 ** sqlite3_value objects even when not strictly required.
03268 **
03269 ** ^The sqlite3_value objects that are passed as parameters into the
03270 ** implementation of [application-defined SQL functions] are protected.
03271 ** ^The sqlite3_value object returned by
03272 ** [sqlite3_column_value()] is unprotected.
03273 ** Unprotected sqlite3_value objects may only be used with
03274 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
03275 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
03276 ** interfaces require protected sqlite3_value objects.
03277 */
03278 typedef struct Mem sqlite3_value;
03279 
03280 /*
03281 ** CAPI3REF: SQL Function Context Object
03282 **
03283 ** The context in which an SQL function executes is stored in an
03284 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
03285 ** is always first parameter to [application-defined SQL functions].
03286 ** The application-defined SQL function implementation will pass this
03287 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
03288 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
03289 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
03290 ** and/or [sqlite3_set_auxdata()].
03291 */
03292 typedef struct sqlite3_context sqlite3_context;
03293 
03294 /*
03295 ** CAPI3REF: Binding Values To Prepared Statements
03296 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
03297 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
03298 **
03299 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
03300 ** literals may be replaced by a [parameter] that matches one of following
03301 ** templates:
03302 **
03303 ** <ul>
03304 ** <li>  ?
03305 ** <li>  ?NNN
03306 ** <li>  :VVV
03307 ** <li>  @VVV
03308 ** <li>  $VVV
03309 ** </ul>
03310 **
03311 ** In the templates above, NNN represents an integer literal,
03312 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
03313 ** parameters (also called "host parameter names" or "SQL parameters")
03314 ** can be set using the sqlite3_bind_*() routines defined here.
03315 **
03316 ** ^The first argument to the sqlite3_bind_*() routines is always
03317 ** a pointer to the [sqlite3_stmt] object returned from
03318 ** [sqlite3_prepare_v2()] or its variants.
03319 **
03320 ** ^The second argument is the index of the SQL parameter to be set.
03321 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
03322 ** SQL parameter is used more than once, second and subsequent
03323 ** occurrences have the same index as the first occurrence.
03324 ** ^The index for named parameters can be looked up using the
03325 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
03326 ** for "?NNN" parameters is the value of NNN.
03327 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
03328 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
03329 **
03330 ** ^The third argument is the value to bind to the parameter.
03331 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
03332 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
03333 ** is ignored and the end result is the same as sqlite3_bind_null().
03334 **
03335 ** ^(In those routines that have a fourth argument, its value is the
03336 ** number of bytes in the parameter.  To be clear: the value is the
03337 ** number of <u>bytes</u> in the value, not the number of characters.)^
03338 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
03339 ** is negative, then the length of the string is
03340 ** the number of bytes up to the first zero terminator.
03341 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
03342 ** the behavior is undefined.
03343 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
03344 ** or sqlite3_bind_text16() then that parameter must be the byte offset
03345 ** where the NUL terminator would occur assuming the string were NUL
03346 ** terminated.  If any NUL characters occur at byte offsets less than 
03347 ** the value of the fourth parameter then the resulting string value will
03348 ** contain embedded NULs.  The result of expressions involving strings
03349 ** with embedded NULs is undefined.
03350 **
03351 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
03352 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
03353 ** string after SQLite has finished with it.  ^The destructor is called
03354 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
03355 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
03356 ** ^If the fifth argument is
03357 ** the special value [SQLITE_STATIC], then SQLite assumes that the
03358 ** information is in static, unmanaged space and does not need to be freed.
03359 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
03360 ** SQLite makes its own private copy of the data immediately, before
03361 ** the sqlite3_bind_*() routine returns.
03362 **
03363 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
03364 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
03365 ** (just an integer to hold its size) while it is being processed.
03366 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
03367 ** content is later written using
03368 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
03369 ** ^A negative value for the zeroblob results in a zero-length BLOB.
03370 **
03371 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
03372 ** for the [prepared statement] or with a prepared statement for which
03373 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
03374 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
03375 ** routine is passed a [prepared statement] that has been finalized, the
03376 ** result is undefined and probably harmful.
03377 **
03378 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
03379 ** ^Unbound parameters are interpreted as NULL.
03380 **
03381 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
03382 ** [error code] if anything goes wrong.
03383 ** ^[SQLITE_RANGE] is returned if the parameter
03384 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
03385 **
03386 ** See also: [sqlite3_bind_parameter_count()],
03387 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
03388 */
03389 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
03390 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
03391 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
03392 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
03393 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
03394 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
03395 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
03396 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
03397 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
03398 
03399 /*
03400 ** CAPI3REF: Number Of SQL Parameters
03401 **
03402 ** ^This routine can be used to find the number of [SQL parameters]
03403 ** in a [prepared statement].  SQL parameters are tokens of the
03404 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
03405 ** placeholders for values that are [sqlite3_bind_blob | bound]
03406 ** to the parameters at a later time.
03407 **
03408 ** ^(This routine actually returns the index of the largest (rightmost)
03409 ** parameter. For all forms except ?NNN, this will correspond to the
03410 ** number of unique parameters.  If parameters of the ?NNN form are used,
03411 ** there may be gaps in the list.)^
03412 **
03413 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
03414 ** [sqlite3_bind_parameter_name()], and
03415 ** [sqlite3_bind_parameter_index()].
03416 */
03417 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
03418 
03419 /*
03420 ** CAPI3REF: Name Of A Host Parameter
03421 **
03422 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
03423 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
03424 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
03425 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
03426 ** respectively.
03427 ** In other words, the initial ":" or "$" or "@" or "?"
03428 ** is included as part of the name.)^
03429 ** ^Parameters of the form "?" without a following integer have no name
03430 ** and are referred to as "nameless" or "anonymous parameters".
03431 **
03432 ** ^The first host parameter has an index of 1, not 0.
03433 **
03434 ** ^If the value N is out of range or if the N-th parameter is
03435 ** nameless, then NULL is returned.  ^The returned string is
03436 ** always in UTF-8 encoding even if the named parameter was
03437 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
03438 ** [sqlite3_prepare16_v2()].
03439 **
03440 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
03441 ** [sqlite3_bind_parameter_count()], and
03442 ** [sqlite3_bind_parameter_index()].
03443 */
03444 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
03445 
03446 /*
03447 ** CAPI3REF: Index Of A Parameter With A Given Name
03448 **
03449 ** ^Return the index of an SQL parameter given its name.  ^The
03450 ** index value returned is suitable for use as the second
03451 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
03452 ** is returned if no matching parameter is found.  ^The parameter
03453 ** name must be given in UTF-8 even if the original statement
03454 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
03455 **
03456 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
03457 ** [sqlite3_bind_parameter_count()], and
03458 ** [sqlite3_bind_parameter_index()].
03459 */
03460 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
03461 
03462 /*
03463 ** CAPI3REF: Reset All Bindings On A Prepared Statement
03464 **
03465 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
03466 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
03467 ** ^Use this routine to reset all host parameters to NULL.
03468 */
03469 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
03470 
03471 /*
03472 ** CAPI3REF: Number Of Columns In A Result Set
03473 **
03474 ** ^Return the number of columns in the result set returned by the
03475 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
03476 ** statement that does not return data (for example an [UPDATE]).
03477 **
03478 ** See also: [sqlite3_data_count()]
03479 */
03480 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
03481 
03482 /*
03483 ** CAPI3REF: Column Names In A Result Set
03484 **
03485 ** ^These routines return the name assigned to a particular column
03486 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
03487 ** interface returns a pointer to a zero-terminated UTF-8 string
03488 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
03489 ** UTF-16 string.  ^The first parameter is the [prepared statement]
03490 ** that implements the [SELECT] statement. ^The second parameter is the
03491 ** column number.  ^The leftmost column is number 0.
03492 **
03493 ** ^The returned string pointer is valid until either the [prepared statement]
03494 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
03495 ** reprepared by the first call to [sqlite3_step()] for a particular run
03496 ** or until the next call to
03497 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
03498 **
03499 ** ^If sqlite3_malloc() fails during the processing of either routine
03500 ** (for example during a conversion from UTF-8 to UTF-16) then a
03501 ** NULL pointer is returned.
03502 **
03503 ** ^The name of a result column is the value of the "AS" clause for
03504 ** that column, if there is an AS clause.  If there is no AS clause
03505 ** then the name of the column is unspecified and may change from
03506 ** one release of SQLite to the next.
03507 */
03508 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
03509 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
03510 
03511 /*
03512 ** CAPI3REF: Source Of Data In A Query Result
03513 **
03514 ** ^These routines provide a means to determine the database, table, and
03515 ** table column that is the origin of a particular result column in
03516 ** [SELECT] statement.
03517 ** ^The name of the database or table or column can be returned as
03518 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
03519 ** the database name, the _table_ routines return the table name, and
03520 ** the origin_ routines return the column name.
03521 ** ^The returned string is valid until the [prepared statement] is destroyed
03522 ** using [sqlite3_finalize()] or until the statement is automatically
03523 ** reprepared by the first call to [sqlite3_step()] for a particular run
03524 ** or until the same information is requested
03525 ** again in a different encoding.
03526 **
03527 ** ^The names returned are the original un-aliased names of the
03528 ** database, table, and column.
03529 **
03530 ** ^The first argument to these interfaces is a [prepared statement].
03531 ** ^These functions return information about the Nth result column returned by
03532 ** the statement, where N is the second function argument.
03533 ** ^The left-most column is column 0 for these routines.
03534 **
03535 ** ^If the Nth column returned by the statement is an expression or
03536 ** subquery and is not a column value, then all of these functions return
03537 ** NULL.  ^These routine might also return NULL if a memory allocation error
03538 ** occurs.  ^Otherwise, they return the name of the attached database, table,
03539 ** or column that query result column was extracted from.
03540 **
03541 ** ^As with all other SQLite APIs, those whose names end with "16" return
03542 ** UTF-16 encoded strings and the other functions return UTF-8.
03543 **
03544 ** ^These APIs are only available if the library was compiled with the
03545 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
03546 **
03547 ** If two or more threads call one or more of these routines against the same
03548 ** prepared statement and column at the same time then the results are
03549 ** undefined.
03550 **
03551 ** If two or more threads call one or more
03552 ** [sqlite3_column_database_name | column metadata interfaces]
03553 ** for the same [prepared statement] and result column
03554 ** at the same time then the results are undefined.
03555 */
03556 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
03557 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
03558 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
03559 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
03560 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
03561 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
03562 
03563 /*
03564 ** CAPI3REF: Declared Datatype Of A Query Result
03565 **
03566 ** ^(The first parameter is a [prepared statement].
03567 ** If this statement is a [SELECT] statement and the Nth column of the
03568 ** returned result set of that [SELECT] is a table column (not an
03569 ** expression or subquery) then the declared type of the table
03570 ** column is returned.)^  ^If the Nth column of the result set is an
03571 ** expression or subquery, then a NULL pointer is returned.
03572 ** ^The returned string is always UTF-8 encoded.
03573 **
03574 ** ^(For example, given the database schema:
03575 **
03576 ** CREATE TABLE t1(c1 VARIANT);
03577 **
03578 ** and the following statement to be compiled:
03579 **
03580 ** SELECT c1 + 1, c1 FROM t1;
03581 **
03582 ** this routine would return the string "VARIANT" for the second result
03583 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
03584 **
03585 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
03586 ** is declared to contain a particular type does not mean that the
03587 ** data stored in that column is of the declared type.  SQLite is
03588 ** strongly typed, but the typing is dynamic not static.  ^Type
03589 ** is associated with individual values, not with the containers
03590 ** used to hold those values.
03591 */
03592 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
03593 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
03594 
03595 /*
03596 ** CAPI3REF: Evaluate An SQL Statement
03597 **
03598 ** After a [prepared statement] has been prepared using either
03599 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
03600 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
03601 ** must be called one or more times to evaluate the statement.
03602 **
03603 ** The details of the behavior of the sqlite3_step() interface depend
03604 ** on whether the statement was prepared using the newer "v2" interface
03605 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
03606 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
03607 ** new "v2" interface is recommended for new applications but the legacy
03608 ** interface will continue to be supported.
03609 **
03610 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
03611 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
03612 ** ^With the "v2" interface, any of the other [result codes] or
03613 ** [extended result codes] might be returned as well.
03614 **
03615 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
03616 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
03617 ** or occurs outside of an explicit transaction, then you can retry the
03618 ** statement.  If the statement is not a [COMMIT] and occurs within an
03619 ** explicit transaction then you should rollback the transaction before
03620 ** continuing.
03621 **
03622 ** ^[SQLITE_DONE] means that the statement has finished executing
03623 ** successfully.  sqlite3_step() should not be called again on this virtual
03624 ** machine without first calling [sqlite3_reset()] to reset the virtual
03625 ** machine back to its initial state.
03626 **
03627 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
03628 ** is returned each time a new row of data is ready for processing by the
03629 ** caller. The values may be accessed using the [column access functions].
03630 ** sqlite3_step() is called again to retrieve the next row of data.
03631 **
03632 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
03633 ** violation) has occurred.  sqlite3_step() should not be called again on
03634 ** the VM. More information may be found by calling [sqlite3_errmsg()].
03635 ** ^With the legacy interface, a more specific error code (for example,
03636 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
03637 ** can be obtained by calling [sqlite3_reset()] on the
03638 ** [prepared statement].  ^In the "v2" interface,
03639 ** the more specific error code is returned directly by sqlite3_step().
03640 **
03641 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
03642 ** Perhaps it was called on a [prepared statement] that has
03643 ** already been [sqlite3_finalize | finalized] or on one that had
03644 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
03645 ** be the case that the same database connection is being used by two or
03646 ** more threads at the same moment in time.
03647 **
03648 ** For all versions of SQLite up to and including 3.6.23.1, a call to
03649 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
03650 ** other than [SQLITE_ROW] before any subsequent invocation of
03651 ** sqlite3_step().  Failure to reset the prepared statement using 
03652 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
03653 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
03654 ** calling [sqlite3_reset()] automatically in this circumstance rather
03655 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
03656 ** break because any application that ever receives an SQLITE_MISUSE error
03657 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
03658 ** can be used to restore the legacy behavior.
03659 **
03660 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
03661 ** API always returns a generic error code, [SQLITE_ERROR], following any
03662 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
03663 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
03664 ** specific [error codes] that better describes the error.
03665 ** We admit that this is a goofy design.  The problem has been fixed
03666 ** with the "v2" interface.  If you prepare all of your SQL statements
03667 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
03668 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
03669 ** then the more specific [error codes] are returned directly
03670 ** by sqlite3_step().  The use of the "v2" interface is recommended.
03671 */
03672 SQLITE_API int sqlite3_step(sqlite3_stmt*);
03673 
03674 /*
03675 ** CAPI3REF: Number of columns in a result set
03676 **
03677 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
03678 ** current row of the result set of [prepared statement] P.
03679 ** ^If prepared statement P does not have results ready to return
03680 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
03681 ** interfaces) then sqlite3_data_count(P) returns 0.
03682 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
03683 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
03684 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
03685 ** will return non-zero if previous call to [sqlite3_step](P) returned
03686 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
03687 ** where it always returns zero since each step of that multi-step
03688 ** pragma returns 0 columns of data.
03689 **
03690 ** See also: [sqlite3_column_count()]
03691 */
03692 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
03693 
03694 /*
03695 ** CAPI3REF: Fundamental Datatypes
03696 ** KEYWORDS: SQLITE_TEXT
03697 **
03698 ** ^(Every value in SQLite has one of five fundamental datatypes:
03699 **
03700 ** <ul>
03701 ** <li> 64-bit signed integer
03702 ** <li> 64-bit IEEE floating point number
03703 ** <li> string
03704 ** <li> BLOB
03705 ** <li> NULL
03706 ** </ul>)^
03707 **
03708 ** These constants are codes for each of those types.
03709 **
03710 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
03711 ** for a completely different meaning.  Software that links against both
03712 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
03713 ** SQLITE_TEXT.
03714 */
03715 #define SQLITE_INTEGER  1
03716 #define SQLITE_FLOAT    2
03717 #define SQLITE_BLOB     4
03718 #define SQLITE_NULL     5
03719 #ifdef SQLITE_TEXT
03720 # undef SQLITE_TEXT
03721 #else
03722 # define SQLITE_TEXT     3
03723 #endif
03724 #define SQLITE3_TEXT     3
03725 
03726 /*
03727 ** CAPI3REF: Result Values From A Query
03728 ** KEYWORDS: {column access functions}
03729 **
03730 ** These routines form the "result set" interface.
03731 **
03732 ** ^These routines return information about a single column of the current
03733 ** result row of a query.  ^In every case the first argument is a pointer
03734 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
03735 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
03736 ** and the second argument is the index of the column for which information
03737 ** should be returned. ^The leftmost column of the result set has the index 0.
03738 ** ^The number of columns in the result can be determined using
03739 ** [sqlite3_column_count()].
03740 **
03741 ** If the SQL statement does not currently point to a valid row, or if the
03742 ** column index is out of range, the result is undefined.
03743 ** These routines may only be called when the most recent call to
03744 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
03745 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
03746 ** If any of these routines are called after [sqlite3_reset()] or
03747 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
03748 ** something other than [SQLITE_ROW], the results are undefined.
03749 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
03750 ** are called from a different thread while any of these routines
03751 ** are pending, then the results are undefined.
03752 **
03753 ** ^The sqlite3_column_type() routine returns the
03754 ** [SQLITE_INTEGER | datatype code] for the initial data type
03755 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
03756 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
03757 ** returned by sqlite3_column_type() is only meaningful if no type
03758 ** conversions have occurred as described below.  After a type conversion,
03759 ** the value returned by sqlite3_column_type() is undefined.  Future
03760 ** versions of SQLite may change the behavior of sqlite3_column_type()
03761 ** following a type conversion.
03762 **
03763 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
03764 ** routine returns the number of bytes in that BLOB or string.
03765 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
03766 ** the string to UTF-8 and then returns the number of bytes.
03767 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
03768 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
03769 ** the number of bytes in that string.
03770 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
03771 **
03772 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
03773 ** routine returns the number of bytes in that BLOB or string.
03774 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
03775 ** the string to UTF-16 and then returns the number of bytes.
03776 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
03777 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
03778 ** the number of bytes in that string.
03779 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
03780 **
03781 ** ^The values returned by [sqlite3_column_bytes()] and 
03782 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
03783 ** of the string.  ^For clarity: the values returned by
03784 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
03785 ** bytes in the string, not the number of characters.
03786 **
03787 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
03788 ** even empty strings, are always zero-terminated.  ^The return
03789 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
03790 **
03791 ** ^The object returned by [sqlite3_column_value()] is an
03792 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
03793 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
03794 ** If the [unprotected sqlite3_value] object returned by
03795 ** [sqlite3_column_value()] is used in any other way, including calls
03796 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
03797 ** or [sqlite3_value_bytes()], then the behavior is undefined.
03798 **
03799 ** These routines attempt to convert the value where appropriate.  ^For
03800 ** example, if the internal representation is FLOAT and a text result
03801 ** is requested, [sqlite3_snprintf()] is used internally to perform the
03802 ** conversion automatically.  ^(The following table details the conversions
03803 ** that are applied:
03804 **
03805 ** <blockquote>
03806 ** <table border="1">
03807 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
03808 **
03809 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
03810 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
03811 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
03812 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
03813 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
03814 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
03815 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
03816 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
03817 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
03818 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
03819 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
03820 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
03821 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
03822 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
03823 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
03824 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
03825 ** </table>
03826 ** </blockquote>)^
03827 **
03828 ** The table above makes reference to standard C library functions atoi()
03829 ** and atof().  SQLite does not really use these functions.  It has its
03830 ** own equivalent internal routines.  The atoi() and atof() names are
03831 ** used in the table for brevity and because they are familiar to most
03832 ** C programmers.
03833 **
03834 ** Note that when type conversions occur, pointers returned by prior
03835 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
03836 ** sqlite3_column_text16() may be invalidated.
03837 ** Type conversions and pointer invalidations might occur
03838 ** in the following cases:
03839 **
03840 ** <ul>
03841 ** <li> The initial content is a BLOB and sqlite3_column_text() or
03842 **      sqlite3_column_text16() is called.  A zero-terminator might
03843 **      need to be added to the string.</li>
03844 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
03845 **      sqlite3_column_text16() is called.  The content must be converted
03846 **      to UTF-16.</li>
03847 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
03848 **      sqlite3_column_text() is called.  The content must be converted
03849 **      to UTF-8.</li>
03850 ** </ul>
03851 **
03852 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
03853 ** not invalidate a prior pointer, though of course the content of the buffer
03854 ** that the prior pointer references will have been modified.  Other kinds
03855 ** of conversion are done in place when it is possible, but sometimes they
03856 ** are not possible and in those cases prior pointers are invalidated.
03857 **
03858 ** The safest and easiest to remember policy is to invoke these routines
03859 ** in one of the following ways:
03860 **
03861 ** <ul>
03862 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
03863 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
03864 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
03865 ** </ul>
03866 **
03867 ** In other words, you should call sqlite3_column_text(),
03868 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
03869 ** into the desired format, then invoke sqlite3_column_bytes() or
03870 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
03871 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
03872 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
03873 ** with calls to sqlite3_column_bytes().
03874 **
03875 ** ^The pointers returned are valid until a type conversion occurs as
03876 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
03877 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
03878 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
03879 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
03880 ** [sqlite3_free()].
03881 **
03882 ** ^(If a memory allocation error occurs during the evaluation of any
03883 ** of these routines, a default value is returned.  The default value
03884 ** is either the integer 0, the floating point number 0.0, or a NULL
03885 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
03886 ** [SQLITE_NOMEM].)^
03887 */
03888 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
03889 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
03890 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
03891 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
03892 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
03893 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
03894 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
03895 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
03896 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
03897 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
03898 
03899 /*
03900 ** CAPI3REF: Destroy A Prepared Statement Object
03901 **
03902 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
03903 ** ^If the most recent evaluation of the statement encountered no errors
03904 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
03905 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
03906 ** sqlite3_finalize(S) returns the appropriate [error code] or
03907 ** [extended error code].
03908 **
03909 ** ^The sqlite3_finalize(S) routine can be called at any point during
03910 ** the life cycle of [prepared statement] S:
03911 ** before statement S is ever evaluated, after
03912 ** one or more calls to [sqlite3_reset()], or after any call
03913 ** to [sqlite3_step()] regardless of whether or not the statement has
03914 ** completed execution.
03915 **
03916 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
03917 **
03918 ** The application must finalize every [prepared statement] in order to avoid
03919 ** resource leaks.  It is a grievous error for the application to try to use
03920 ** a prepared statement after it has been finalized.  Any use of a prepared
03921 ** statement after it has been finalized can result in undefined and
03922 ** undesirable behavior such as segfaults and heap corruption.
03923 */
03924 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
03925 
03926 /*
03927 ** CAPI3REF: Reset A Prepared Statement Object
03928 **
03929 ** The sqlite3_reset() function is called to reset a [prepared statement]
03930 ** object back to its initial state, ready to be re-executed.
03931 ** ^Any SQL statement variables that had values bound to them using
03932 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
03933 ** Use [sqlite3_clear_bindings()] to reset the bindings.
03934 **
03935 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
03936 ** back to the beginning of its program.
03937 **
03938 ** ^If the most recent call to [sqlite3_step(S)] for the
03939 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
03940 ** or if [sqlite3_step(S)] has never before been called on S,
03941 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
03942 **
03943 ** ^If the most recent call to [sqlite3_step(S)] for the
03944 ** [prepared statement] S indicated an error, then
03945 ** [sqlite3_reset(S)] returns an appropriate [error code].
03946 **
03947 ** ^The [sqlite3_reset(S)] interface does not change the values
03948 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
03949 */
03950 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
03951 
03952 /*
03953 ** CAPI3REF: Create Or Redefine SQL Functions
03954 ** KEYWORDS: {function creation routines}
03955 ** KEYWORDS: {application-defined SQL function}
03956 ** KEYWORDS: {application-defined SQL functions}
03957 **
03958 ** ^These functions (collectively known as "function creation routines")
03959 ** are used to add SQL functions or aggregates or to redefine the behavior
03960 ** of existing SQL functions or aggregates.  The only differences between
03961 ** these routines are the text encoding expected for
03962 ** the second parameter (the name of the function being created)
03963 ** and the presence or absence of a destructor callback for
03964 ** the application data pointer.
03965 **
03966 ** ^The first parameter is the [database connection] to which the SQL
03967 ** function is to be added.  ^If an application uses more than one database
03968 ** connection then application-defined SQL functions must be added
03969 ** to each database connection separately.
03970 **
03971 ** ^The second parameter is the name of the SQL function to be created or
03972 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
03973 ** representation, exclusive of the zero-terminator.  ^Note that the name
03974 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
03975 ** ^Any attempt to create a function with a longer name
03976 ** will result in [SQLITE_MISUSE] being returned.
03977 **
03978 ** ^The third parameter (nArg)
03979 ** is the number of arguments that the SQL function or
03980 ** aggregate takes. ^If this parameter is -1, then the SQL function or
03981 ** aggregate may take any number of arguments between 0 and the limit
03982 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
03983 ** parameter is less than -1 or greater than 127 then the behavior is
03984 ** undefined.
03985 **
03986 ** ^The fourth parameter, eTextRep, specifies what
03987 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
03988 ** its parameters.  Every SQL function implementation must be able to work
03989 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
03990 ** more efficient with one encoding than another.  ^An application may
03991 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
03992 ** times with the same function but with different values of eTextRep.
03993 ** ^When multiple implementations of the same function are available, SQLite
03994 ** will pick the one that involves the least amount of data conversion.
03995 ** If there is only a single implementation which does not care what text
03996 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
03997 **
03998 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
03999 ** function can gain access to this pointer using [sqlite3_user_data()].)^
04000 **
04001 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
04002 ** pointers to C-language functions that implement the SQL function or
04003 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
04004 ** callback only; NULL pointers must be passed as the xStep and xFinal
04005 ** parameters. ^An aggregate SQL function requires an implementation of xStep
04006 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
04007 ** SQL function or aggregate, pass NULL pointers for all three function
04008 ** callbacks.
04009 **
04010 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
04011 ** then it is destructor for the application data pointer. 
04012 ** The destructor is invoked when the function is deleted, either by being
04013 ** overloaded or when the database connection closes.)^
04014 ** ^The destructor is also invoked if the call to
04015 ** sqlite3_create_function_v2() fails.
04016 ** ^When the destructor callback of the tenth parameter is invoked, it
04017 ** is passed a single argument which is a copy of the application data 
04018 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
04019 **
04020 ** ^It is permitted to register multiple implementations of the same
04021 ** functions with the same name but with either differing numbers of
04022 ** arguments or differing preferred text encodings.  ^SQLite will use
04023 ** the implementation that most closely matches the way in which the
04024 ** SQL function is used.  ^A function implementation with a non-negative
04025 ** nArg parameter is a better match than a function implementation with
04026 ** a negative nArg.  ^A function where the preferred text encoding
04027 ** matches the database encoding is a better
04028 ** match than a function where the encoding is different.  
04029 ** ^A function where the encoding difference is between UTF16le and UTF16be
04030 ** is a closer match than a function where the encoding difference is
04031 ** between UTF8 and UTF16.
04032 **
04033 ** ^Built-in functions may be overloaded by new application-defined functions.
04034 **
04035 ** ^An application-defined function is permitted to call other
04036 ** SQLite interfaces.  However, such calls must not
04037 ** close the database connection nor finalize or reset the prepared
04038 ** statement in which the function is running.
04039 */
04040 SQLITE_API int sqlite3_create_function(
04041   sqlite3 *db,
04042   const char *zFunctionName,
04043   int nArg,
04044   int eTextRep,
04045   void *pApp,
04046   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
04047   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
04048   void (*xFinal)(sqlite3_context*)
04049 );
04050 SQLITE_API int sqlite3_create_function16(
04051   sqlite3 *db,
04052   const void *zFunctionName,
04053   int nArg,
04054   int eTextRep,
04055   void *pApp,
04056   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
04057   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
04058   void (*xFinal)(sqlite3_context*)
04059 );
04060 SQLITE_API int sqlite3_create_function_v2(
04061   sqlite3 *db,
04062   const char *zFunctionName,
04063   int nArg,
04064   int eTextRep,
04065   void *pApp,
04066   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
04067   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
04068   void (*xFinal)(sqlite3_context*),
04069   void(*xDestroy)(void*)
04070 );
04071 
04072 /*
04073 ** CAPI3REF: Text Encodings
04074 **
04075 ** These constant define integer codes that represent the various
04076 ** text encodings supported by SQLite.
04077 */
04078 #define SQLITE_UTF8           1
04079 #define SQLITE_UTF16LE        2
04080 #define SQLITE_UTF16BE        3
04081 #define SQLITE_UTF16          4    /* Use native byte order */
04082 #define SQLITE_ANY            5    /* sqlite3_create_function only */
04083 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
04084 
04085 /*
04086 ** CAPI3REF: Deprecated Functions
04087 ** DEPRECATED
04088 **
04089 ** These functions are [deprecated].  In order to maintain
04090 ** backwards compatibility with older code, these functions continue 
04091 ** to be supported.  However, new applications should avoid
04092 ** the use of these functions.  To help encourage people to avoid
04093 ** using these functions, we are not going to tell you what they do.
04094 */
04095 #ifndef SQLITE_OMIT_DEPRECATED
04096 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
04097 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
04098 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
04099 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
04100 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
04101 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
04102                       void*,sqlite3_int64);
04103 #endif
04104 
04105 /*
04106 ** CAPI3REF: Obtaining SQL Function Parameter Values
04107 **
04108 ** The C-language implementation of SQL functions and aggregates uses
04109 ** this set of interface routines to access the parameter values on
04110 ** the function or aggregate.
04111 **
04112 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
04113 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
04114 ** define callbacks that implement the SQL functions and aggregates.
04115 ** The 3rd parameter to these callbacks is an array of pointers to
04116 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
04117 ** each parameter to the SQL function.  These routines are used to
04118 ** extract values from the [sqlite3_value] objects.
04119 **
04120 ** These routines work only with [protected sqlite3_value] objects.
04121 ** Any attempt to use these routines on an [unprotected sqlite3_value]
04122 ** object results in undefined behavior.
04123 **
04124 ** ^These routines work just like the corresponding [column access functions]
04125 ** except that  these routines take a single [protected sqlite3_value] object
04126 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
04127 **
04128 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
04129 ** in the native byte-order of the host machine.  ^The
04130 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
04131 ** extract UTF-16 strings as big-endian and little-endian respectively.
04132 **
04133 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
04134 ** numeric affinity to the value.  This means that an attempt is
04135 ** made to convert the value to an integer or floating point.  If
04136 ** such a conversion is possible without loss of information (in other
04137 ** words, if the value is a string that looks like a number)
04138 ** then the conversion is performed.  Otherwise no conversion occurs.
04139 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
04140 **
04141 ** Please pay particular attention to the fact that the pointer returned
04142 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
04143 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
04144 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
04145 ** or [sqlite3_value_text16()].
04146 **
04147 ** These routines must be called from the same thread as
04148 ** the SQL function that supplied the [sqlite3_value*] parameters.
04149 */
04150 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
04151 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
04152 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
04153 SQLITE_API double sqlite3_value_double(sqlite3_value*);
04154 SQLITE_API int sqlite3_value_int(sqlite3_value*);
04155 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
04156 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
04157 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
04158 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
04159 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
04160 SQLITE_API int sqlite3_value_type(sqlite3_value*);
04161 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
04162 
04163 /*
04164 ** CAPI3REF: Obtain Aggregate Function Context
04165 **
04166 ** Implementations of aggregate SQL functions use this
04167 ** routine to allocate memory for storing their state.
04168 **
04169 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
04170 ** for a particular aggregate function, SQLite
04171 ** allocates N of memory, zeroes out that memory, and returns a pointer
04172 ** to the new memory. ^On second and subsequent calls to
04173 ** sqlite3_aggregate_context() for the same aggregate function instance,
04174 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
04175 ** called once for each invocation of the xStep callback and then one
04176 ** last time when the xFinal callback is invoked.  ^(When no rows match
04177 ** an aggregate query, the xStep() callback of the aggregate function
04178 ** implementation is never called and xFinal() is called exactly once.
04179 ** In those cases, sqlite3_aggregate_context() might be called for the
04180 ** first time from within xFinal().)^
04181 **
04182 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
04183 ** when first called if N is less than or equal to zero or if a memory
04184 ** allocate error occurs.
04185 **
04186 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
04187 ** determined by the N parameter on first successful call.  Changing the
04188 ** value of N in subsequent call to sqlite3_aggregate_context() within
04189 ** the same aggregate function instance will not resize the memory
04190 ** allocation.)^  Within the xFinal callback, it is customary to set
04191 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
04192 ** pointless memory allocations occur.
04193 **
04194 ** ^SQLite automatically frees the memory allocated by 
04195 ** sqlite3_aggregate_context() when the aggregate query concludes.
04196 **
04197 ** The first parameter must be a copy of the
04198 ** [sqlite3_context | SQL function context] that is the first parameter
04199 ** to the xStep or xFinal callback routine that implements the aggregate
04200 ** function.
04201 **
04202 ** This routine must be called from the same thread in which
04203 ** the aggregate SQL function is running.
04204 */
04205 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
04206 
04207 /*
04208 ** CAPI3REF: User Data For Functions
04209 **
04210 ** ^The sqlite3_user_data() interface returns a copy of
04211 ** the pointer that was the pUserData parameter (the 5th parameter)
04212 ** of the [sqlite3_create_function()]
04213 ** and [sqlite3_create_function16()] routines that originally
04214 ** registered the application defined function.
04215 **
04216 ** This routine must be called from the same thread in which
04217 ** the application-defined function is running.
04218 */
04219 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
04220 
04221 /*
04222 ** CAPI3REF: Database Connection For Functions
04223 **
04224 ** ^The sqlite3_context_db_handle() interface returns a copy of
04225 ** the pointer to the [database connection] (the 1st parameter)
04226 ** of the [sqlite3_create_function()]
04227 ** and [sqlite3_create_function16()] routines that originally
04228 ** registered the application defined function.
04229 */
04230 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
04231 
04232 /*
04233 ** CAPI3REF: Function Auxiliary Data
04234 **
04235 ** These functions may be used by (non-aggregate) SQL functions to
04236 ** associate metadata with argument values. If the same value is passed to
04237 ** multiple invocations of the same SQL function during query execution, under
04238 ** some circumstances the associated metadata may be preserved.  An example
04239 ** of where this might be useful is in a regular-expression matching
04240 ** function. The compiled version of the regular expression can be stored as
04241 ** metadata associated with the pattern string.  
04242 ** Then as long as the pattern string remains the same,
04243 ** the compiled regular expression can be reused on multiple
04244 ** invocations of the same function.
04245 **
04246 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
04247 ** associated by the sqlite3_set_auxdata() function with the Nth argument
04248 ** value to the application-defined function. ^If there is no metadata
04249 ** associated with the function argument, this sqlite3_get_auxdata() interface
04250 ** returns a NULL pointer.
04251 **
04252 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
04253 ** argument of the application-defined function.  ^Subsequent
04254 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
04255 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
04256 ** NULL if the metadata has been discarded.
04257 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
04258 ** SQLite will invoke the destructor function X with parameter P exactly
04259 ** once, when the metadata is discarded.
04260 ** SQLite is free to discard the metadata at any time, including: <ul>
04261 ** <li> when the corresponding function parameter changes, or
04262 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
04263 **      SQL statement, or
04264 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
04265 ** <li> during the original sqlite3_set_auxdata() call when a memory 
04266 **      allocation error occurs. </ul>)^
04267 **
04268 ** Note the last bullet in particular.  The destructor X in 
04269 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
04270 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
04271 ** should be called near the end of the function implementation and the
04272 ** function implementation should not make any use of P after
04273 ** sqlite3_set_auxdata() has been called.
04274 **
04275 ** ^(In practice, metadata is preserved between function calls for
04276 ** function parameters that are compile-time constants, including literal
04277 ** values and [parameters] and expressions composed from the same.)^
04278 **
04279 ** These routines must be called from the same thread in which
04280 ** the SQL function is running.
04281 */
04282 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
04283 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
04284 
04285 
04286 /*
04287 ** CAPI3REF: Constants Defining Special Destructor Behavior
04288 **
04289 ** These are special values for the destructor that is passed in as the
04290 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
04291 ** argument is SQLITE_STATIC, it means that the content pointer is constant
04292 ** and will never change.  It does not need to be destroyed.  ^The
04293 ** SQLITE_TRANSIENT value means that the content will likely change in
04294 ** the near future and that SQLite should make its own private copy of
04295 ** the content before returning.
04296 **
04297 ** The typedef is necessary to work around problems in certain
04298 ** C++ compilers.
04299 */
04300 typedef void (*sqlite3_destructor_type)(void*);
04301 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
04302 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
04303 
04304 /*
04305 ** CAPI3REF: Setting The Result Of An SQL Function
04306 **
04307 ** These routines are used by the xFunc or xFinal callbacks that
04308 ** implement SQL functions and aggregates.  See
04309 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
04310 ** for additional information.
04311 **
04312 ** These functions work very much like the [parameter binding] family of
04313 ** functions used to bind values to host parameters in prepared statements.
04314 ** Refer to the [SQL parameter] documentation for additional information.
04315 **
04316 ** ^The sqlite3_result_blob() interface sets the result from
04317 ** an application-defined function to be the BLOB whose content is pointed
04318 ** to by the second parameter and which is N bytes long where N is the
04319 ** third parameter.
04320 **
04321 ** ^The sqlite3_result_zeroblob() interfaces set the result of
04322 ** the application-defined function to be a BLOB containing all zero
04323 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
04324 **
04325 ** ^The sqlite3_result_double() interface sets the result from
04326 ** an application-defined function to be a floating point value specified
04327 ** by its 2nd argument.
04328 **
04329 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
04330 ** cause the implemented SQL function to throw an exception.
04331 ** ^SQLite uses the string pointed to by the
04332 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
04333 ** as the text of an error message.  ^SQLite interprets the error
04334 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
04335 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
04336 ** byte order.  ^If the third parameter to sqlite3_result_error()
04337 ** or sqlite3_result_error16() is negative then SQLite takes as the error
04338 ** message all text up through the first zero character.
04339 ** ^If the third parameter to sqlite3_result_error() or
04340 ** sqlite3_result_error16() is non-negative then SQLite takes that many
04341 ** bytes (not characters) from the 2nd parameter as the error message.
04342 ** ^The sqlite3_result_error() and sqlite3_result_error16()
04343 ** routines make a private copy of the error message text before
04344 ** they return.  Hence, the calling function can deallocate or
04345 ** modify the text after they return without harm.
04346 ** ^The sqlite3_result_error_code() function changes the error code
04347 ** returned by SQLite as a result of an error in a function.  ^By default,
04348 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
04349 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
04350 **
04351 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
04352 ** error indicating that a string or BLOB is too long to represent.
04353 **
04354 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
04355 ** error indicating that a memory allocation failed.
04356 **
04357 ** ^The sqlite3_result_int() interface sets the return value
04358 ** of the application-defined function to be the 32-bit signed integer
04359 ** value given in the 2nd argument.
04360 ** ^The sqlite3_result_int64() interface sets the return value
04361 ** of the application-defined function to be the 64-bit signed integer
04362 ** value given in the 2nd argument.
04363 **
04364 ** ^The sqlite3_result_null() interface sets the return value
04365 ** of the application-defined function to be NULL.
04366 **
04367 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
04368 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
04369 ** set the return value of the application-defined function to be
04370 ** a text string which is represented as UTF-8, UTF-16 native byte order,
04371 ** UTF-16 little endian, or UTF-16 big endian, respectively.
04372 ** ^SQLite takes the text result from the application from
04373 ** the 2nd parameter of the sqlite3_result_text* interfaces.
04374 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
04375 ** is negative, then SQLite takes result text from the 2nd parameter
04376 ** through the first zero character.
04377 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
04378 ** is non-negative, then as many bytes (not characters) of the text
04379 ** pointed to by the 2nd parameter are taken as the application-defined
04380 ** function result.  If the 3rd parameter is non-negative, then it
04381 ** must be the byte offset into the string where the NUL terminator would
04382 ** appear if the string where NUL terminated.  If any NUL characters occur
04383 ** in the string at a byte offset that is less than the value of the 3rd
04384 ** parameter, then the resulting string will contain embedded NULs and the
04385 ** result of expressions operating on strings with embedded NULs is undefined.
04386 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
04387 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
04388 ** function as the destructor on the text or BLOB result when it has
04389 ** finished using that result.
04390 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
04391 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
04392 ** assumes that the text or BLOB result is in constant space and does not
04393 ** copy the content of the parameter nor call a destructor on the content
04394 ** when it has finished using that result.
04395 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
04396 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
04397 ** then SQLite makes a copy of the result into space obtained from
04398 ** from [sqlite3_malloc()] before it returns.
04399 **
04400 ** ^The sqlite3_result_value() interface sets the result of
04401 ** the application-defined function to be a copy the
04402 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
04403 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
04404 ** so that the [sqlite3_value] specified in the parameter may change or
04405 ** be deallocated after sqlite3_result_value() returns without harm.
04406 ** ^A [protected sqlite3_value] object may always be used where an
04407 ** [unprotected sqlite3_value] object is required, so either
04408 ** kind of [sqlite3_value] object can be used with this interface.
04409 **
04410 ** If these routines are called from within the different thread
04411 ** than the one containing the application-defined function that received
04412 ** the [sqlite3_context] pointer, the results are undefined.
04413 */
04414 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
04415 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
04416 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
04417 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
04418 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
04419 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
04420 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
04421 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
04422 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
04423 SQLITE_API void sqlite3_result_null(sqlite3_context*);
04424 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
04425 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
04426 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
04427 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
04428 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
04429 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
04430 
04431 /*
04432 ** CAPI3REF: Define New Collating Sequences
04433 **
04434 ** ^These functions add, remove, or modify a [collation] associated
04435 ** with the [database connection] specified as the first argument.
04436 **
04437 ** ^The name of the collation is a UTF-8 string
04438 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
04439 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
04440 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
04441 ** considered to be the same name.
04442 **
04443 ** ^(The third argument (eTextRep) must be one of the constants:
04444 ** <ul>
04445 ** <li> [SQLITE_UTF8],
04446 ** <li> [SQLITE_UTF16LE],
04447 ** <li> [SQLITE_UTF16BE],
04448 ** <li> [SQLITE_UTF16], or
04449 ** <li> [SQLITE_UTF16_ALIGNED].
04450 ** </ul>)^
04451 ** ^The eTextRep argument determines the encoding of strings passed
04452 ** to the collating function callback, xCallback.
04453 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
04454 ** force strings to be UTF16 with native byte order.
04455 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
04456 ** on an even byte address.
04457 **
04458 ** ^The fourth argument, pArg, is an application data pointer that is passed
04459 ** through as the first argument to the collating function callback.
04460 **
04461 ** ^The fifth argument, xCallback, is a pointer to the collating function.
04462 ** ^Multiple collating functions can be registered using the same name but
04463 ** with different eTextRep parameters and SQLite will use whichever
04464 ** function requires the least amount of data transformation.
04465 ** ^If the xCallback argument is NULL then the collating function is
04466 ** deleted.  ^When all collating functions having the same name are deleted,
04467 ** that collation is no longer usable.
04468 **
04469 ** ^The collating function callback is invoked with a copy of the pArg 
04470 ** application data pointer and with two strings in the encoding specified
04471 ** by the eTextRep argument.  The collating function must return an
04472 ** integer that is negative, zero, or positive
04473 ** if the first string is less than, equal to, or greater than the second,
04474 ** respectively.  A collating function must always return the same answer
04475 ** given the same inputs.  If two or more collating functions are registered
04476 ** to the same collation name (using different eTextRep values) then all
04477 ** must give an equivalent answer when invoked with equivalent strings.
04478 ** The collating function must obey the following properties for all
04479 ** strings A, B, and C:
04480 **
04481 ** <ol>
04482 ** <li> If A==B then B==A.
04483 ** <li> If A==B and B==C then A==C.
04484 ** <li> If A&lt;B THEN B&gt;A.
04485 ** <li> If A&lt;B and B&lt;C then A&lt;C.
04486 ** </ol>
04487 **
04488 ** If a collating function fails any of the above constraints and that
04489 ** collating function is  registered and used, then the behavior of SQLite
04490 ** is undefined.
04491 **
04492 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
04493 ** with the addition that the xDestroy callback is invoked on pArg when
04494 ** the collating function is deleted.
04495 ** ^Collating functions are deleted when they are overridden by later
04496 ** calls to the collation creation functions or when the
04497 ** [database connection] is closed using [sqlite3_close()].
04498 **
04499 ** ^The xDestroy callback is <u>not</u> called if the 
04500 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
04501 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
04502 ** check the return code and dispose of the application data pointer
04503 ** themselves rather than expecting SQLite to deal with it for them.
04504 ** This is different from every other SQLite interface.  The inconsistency 
04505 ** is unfortunate but cannot be changed without breaking backwards 
04506 ** compatibility.
04507 **
04508 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
04509 */
04510 SQLITE_API int sqlite3_create_collation(
04511   sqlite3*, 
04512   const char *zName, 
04513   int eTextRep, 
04514   void *pArg,
04515   int(*xCompare)(void*,int,const void*,int,const void*)
04516 );
04517 SQLITE_API int sqlite3_create_collation_v2(
04518   sqlite3*, 
04519   const char *zName, 
04520   int eTextRep, 
04521   void *pArg,
04522   int(*xCompare)(void*,int,const void*,int,const void*),
04523   void(*xDestroy)(void*)
04524 );
04525 SQLITE_API int sqlite3_create_collation16(
04526   sqlite3*, 
04527   const void *zName,
04528   int eTextRep, 
04529   void *pArg,
04530   int(*xCompare)(void*,int,const void*,int,const void*)
04531 );
04532 
04533 /*
04534 ** CAPI3REF: Collation Needed Callbacks
04535 **
04536 ** ^To avoid having to register all collation sequences before a database
04537 ** can be used, a single callback function may be registered with the
04538 ** [database connection] to be invoked whenever an undefined collation
04539 ** sequence is required.
04540 **
04541 ** ^If the function is registered using the sqlite3_collation_needed() API,
04542 ** then it is passed the names of undefined collation sequences as strings
04543 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
04544 ** the names are passed as UTF-16 in machine native byte order.
04545 ** ^A call to either function replaces the existing collation-needed callback.
04546 **
04547 ** ^(When the callback is invoked, the first argument passed is a copy
04548 ** of the second argument to sqlite3_collation_needed() or
04549 ** sqlite3_collation_needed16().  The second argument is the database
04550 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
04551 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
04552 ** sequence function required.  The fourth parameter is the name of the
04553 ** required collation sequence.)^
04554 **
04555 ** The callback function should register the desired collation using
04556 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
04557 ** [sqlite3_create_collation_v2()].
04558 */
04559 SQLITE_API int sqlite3_collation_needed(
04560   sqlite3*, 
04561   void*, 
04562   void(*)(void*,sqlite3*,int eTextRep,const char*)
04563 );
04564 SQLITE_API int sqlite3_collation_needed16(
04565   sqlite3*, 
04566   void*,
04567   void(*)(void*,sqlite3*,int eTextRep,const void*)
04568 );
04569 
04570 #ifdef SQLITE_HAS_CODEC
04571 /*
04572 ** Specify the key for an encrypted database.  This routine should be
04573 ** called right after sqlite3_open().
04574 **
04575 ** The code to implement this API is not available in the public release
04576 ** of SQLite.
04577 */
04578 SQLITE_API int sqlite3_key(
04579   sqlite3 *db,                   /* Database to be rekeyed */
04580   const void *pKey, int nKey     /* The key */
04581 );
04582 SQLITE_API int sqlite3_key_v2(
04583   sqlite3 *db,                   /* Database to be rekeyed */
04584   const char *zDbName,           /* Name of the database */
04585   const void *pKey, int nKey     /* The key */
04586 );
04587 
04588 /*
04589 ** Change the key on an open database.  If the current database is not
04590 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
04591 ** database is decrypted.
04592 **
04593 ** The code to implement this API is not available in the public release
04594 ** of SQLite.
04595 */
04596 SQLITE_API int sqlite3_rekey(
04597   sqlite3 *db,                   /* Database to be rekeyed */
04598   const void *pKey, int nKey     /* The new key */
04599 );
04600 SQLITE_API int sqlite3_rekey_v2(
04601   sqlite3 *db,                   /* Database to be rekeyed */
04602   const char *zDbName,           /* Name of the database */
04603   const void *pKey, int nKey     /* The new key */
04604 );
04605 
04606 /*
04607 ** Specify the activation key for a SEE database.  Unless 
04608 ** activated, none of the SEE routines will work.
04609 */
04610 SQLITE_API void sqlite3_activate_see(
04611   const char *zPassPhrase        /* Activation phrase */
04612 );
04613 #endif
04614 
04615 #ifdef SQLITE_ENABLE_CEROD
04616 /*
04617 ** Specify the activation key for a CEROD database.  Unless 
04618 ** activated, none of the CEROD routines will work.
04619 */
04620 SQLITE_API void sqlite3_activate_cerod(
04621   const char *zPassPhrase        /* Activation phrase */
04622 );
04623 #endif
04624 
04625 /*
04626 ** CAPI3REF: Suspend Execution For A Short Time
04627 **
04628 ** The sqlite3_sleep() function causes the current thread to suspend execution
04629 ** for at least a number of milliseconds specified in its parameter.
04630 **
04631 ** If the operating system does not support sleep requests with
04632 ** millisecond time resolution, then the time will be rounded up to
04633 ** the nearest second. The number of milliseconds of sleep actually
04634 ** requested from the operating system is returned.
04635 **
04636 ** ^SQLite implements this interface by calling the xSleep()
04637 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
04638 ** of the default VFS is not implemented correctly, or not implemented at
04639 ** all, then the behavior of sqlite3_sleep() may deviate from the description
04640 ** in the previous paragraphs.
04641 */
04642 SQLITE_API int sqlite3_sleep(int);
04643 
04644 /*
04645 ** CAPI3REF: Name Of The Folder Holding Temporary Files
04646 **
04647 ** ^(If this global variable is made to point to a string which is
04648 ** the name of a folder (a.k.a. directory), then all temporary files
04649 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
04650 ** will be placed in that directory.)^  ^If this variable
04651 ** is a NULL pointer, then SQLite performs a search for an appropriate
04652 ** temporary file directory.
04653 **
04654 ** It is not safe to read or modify this variable in more than one
04655 ** thread at a time.  It is not safe to read or modify this variable
04656 ** if a [database connection] is being used at the same time in a separate
04657 ** thread.
04658 ** It is intended that this variable be set once
04659 ** as part of process initialization and before any SQLite interface
04660 ** routines have been called and that this variable remain unchanged
04661 ** thereafter.
04662 **
04663 ** ^The [temp_store_directory pragma] may modify this variable and cause
04664 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
04665 ** the [temp_store_directory pragma] always assumes that any string
04666 ** that this variable points to is held in memory obtained from 
04667 ** [sqlite3_malloc] and the pragma may attempt to free that memory
04668 ** using [sqlite3_free].
04669 ** Hence, if this variable is modified directly, either it should be
04670 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
04671 ** or else the use of the [temp_store_directory pragma] should be avoided.
04672 **
04673 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
04674 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
04675 ** features that require the use of temporary files may fail.  Here is an
04676 ** example of how to do this using C++ with the Windows Runtime:
04677 **
04678 ** <blockquote><pre>
04679 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
04680 ** &nbsp;     TemporaryFolder->Path->Data();
04681 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
04682 ** memset(zPathBuf, 0, sizeof(zPathBuf));
04683 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
04684 ** &nbsp;     NULL, NULL);
04685 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
04686 ** </pre></blockquote>
04687 */
04688 SQLITE_API char *sqlite3_temp_directory;
04689 
04690 /*
04691 ** CAPI3REF: Name Of The Folder Holding Database Files
04692 **
04693 ** ^(If this global variable is made to point to a string which is
04694 ** the name of a folder (a.k.a. directory), then all database files
04695 ** specified with a relative pathname and created or accessed by
04696 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
04697 ** to be relative to that directory.)^ ^If this variable is a NULL
04698 ** pointer, then SQLite assumes that all database files specified
04699 ** with a relative pathname are relative to the current directory
04700 ** for the process.  Only the windows VFS makes use of this global
04701 ** variable; it is ignored by the unix VFS.
04702 **
04703 ** Changing the value of this variable while a database connection is
04704 ** open can result in a corrupt database.
04705 **
04706 ** It is not safe to read or modify this variable in more than one
04707 ** thread at a time.  It is not safe to read or modify this variable
04708 ** if a [database connection] is being used at the same time in a separate
04709 ** thread.
04710 ** It is intended that this variable be set once
04711 ** as part of process initialization and before any SQLite interface
04712 ** routines have been called and that this variable remain unchanged
04713 ** thereafter.
04714 **
04715 ** ^The [data_store_directory pragma] may modify this variable and cause
04716 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
04717 ** the [data_store_directory pragma] always assumes that any string
04718 ** that this variable points to is held in memory obtained from 
04719 ** [sqlite3_malloc] and the pragma may attempt to free that memory
04720 ** using [sqlite3_free].
04721 ** Hence, if this variable is modified directly, either it should be
04722 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
04723 ** or else the use of the [data_store_directory pragma] should be avoided.
04724 */
04725 SQLITE_API char *sqlite3_data_directory;
04726 
04727 /*
04728 ** CAPI3REF: Test For Auto-Commit Mode
04729 ** KEYWORDS: {autocommit mode}
04730 **
04731 ** ^The sqlite3_get_autocommit() interface returns non-zero or
04732 ** zero if the given database connection is or is not in autocommit mode,
04733 ** respectively.  ^Autocommit mode is on by default.
04734 ** ^Autocommit mode is disabled by a [BEGIN] statement.
04735 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
04736 **
04737 ** If certain kinds of errors occur on a statement within a multi-statement
04738 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
04739 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
04740 ** transaction might be rolled back automatically.  The only way to
04741 ** find out whether SQLite automatically rolled back the transaction after
04742 ** an error is to use this function.
04743 **
04744 ** If another thread changes the autocommit status of the database
04745 ** connection while this routine is running, then the return value
04746 ** is undefined.
04747 */
04748 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
04749 
04750 /*
04751 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
04752 **
04753 ** ^The sqlite3_db_handle interface returns the [database connection] handle
04754 ** to which a [prepared statement] belongs.  ^The [database connection]
04755 ** returned by sqlite3_db_handle is the same [database connection]
04756 ** that was the first argument
04757 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
04758 ** create the statement in the first place.
04759 */
04760 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
04761 
04762 /*
04763 ** CAPI3REF: Return The Filename For A Database Connection
04764 **
04765 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
04766 ** associated with database N of connection D.  ^The main database file
04767 ** has the name "main".  If there is no attached database N on the database
04768 ** connection D, or if database N is a temporary or in-memory database, then
04769 ** a NULL pointer is returned.
04770 **
04771 ** ^The filename returned by this function is the output of the
04772 ** xFullPathname method of the [VFS].  ^In other words, the filename
04773 ** will be an absolute pathname, even if the filename used
04774 ** to open the database originally was a URI or relative pathname.
04775 */
04776 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
04777 
04778 /*
04779 ** CAPI3REF: Determine if a database is read-only
04780 **
04781 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
04782 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
04783 ** the name of a database on connection D.
04784 */
04785 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
04786 
04787 /*
04788 ** CAPI3REF: Find the next prepared statement
04789 **
04790 ** ^This interface returns a pointer to the next [prepared statement] after
04791 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
04792 ** then this interface returns a pointer to the first prepared statement
04793 ** associated with the database connection pDb.  ^If no prepared statement
04794 ** satisfies the conditions of this routine, it returns NULL.
04795 **
04796 ** The [database connection] pointer D in a call to
04797 ** [sqlite3_next_stmt(D,S)] must refer to an open database
04798 ** connection and in particular must not be a NULL pointer.
04799 */
04800 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
04801 
04802 /*
04803 ** CAPI3REF: Commit And Rollback Notification Callbacks
04804 **
04805 ** ^The sqlite3_commit_hook() interface registers a callback
04806 ** function to be invoked whenever a transaction is [COMMIT | committed].
04807 ** ^Any callback set by a previous call to sqlite3_commit_hook()
04808 ** for the same database connection is overridden.
04809 ** ^The sqlite3_rollback_hook() interface registers a callback
04810 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
04811 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
04812 ** for the same database connection is overridden.
04813 ** ^The pArg argument is passed through to the callback.
04814 ** ^If the callback on a commit hook function returns non-zero,
04815 ** then the commit is converted into a rollback.
04816 **
04817 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
04818 ** return the P argument from the previous call of the same function
04819 ** on the same [database connection] D, or NULL for
04820 ** the first call for each function on D.
04821 **
04822 ** The commit and rollback hook callbacks are not reentrant.
04823 ** The callback implementation must not do anything that will modify
04824 ** the database connection that invoked the callback.  Any actions
04825 ** to modify the database connection must be deferred until after the
04826 ** completion of the [sqlite3_step()] call that triggered the commit
04827 ** or rollback hook in the first place.
04828 ** Note that running any other SQL statements, including SELECT statements,
04829 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
04830 ** the database connections for the meaning of "modify" in this paragraph.
04831 **
04832 ** ^Registering a NULL function disables the callback.
04833 **
04834 ** ^When the commit hook callback routine returns zero, the [COMMIT]
04835 ** operation is allowed to continue normally.  ^If the commit hook
04836 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
04837 ** ^The rollback hook is invoked on a rollback that results from a commit
04838 ** hook returning non-zero, just as it would be with any other rollback.
04839 **
04840 ** ^For the purposes of this API, a transaction is said to have been
04841 ** rolled back if an explicit "ROLLBACK" statement is executed, or
04842 ** an error or constraint causes an implicit rollback to occur.
04843 ** ^The rollback callback is not invoked if a transaction is
04844 ** automatically rolled back because the database connection is closed.
04845 **
04846 ** See also the [sqlite3_update_hook()] interface.
04847 */
04848 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
04849 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
04850 
04851 /*
04852 ** CAPI3REF: Data Change Notification Callbacks
04853 **
04854 ** ^The sqlite3_update_hook() interface registers a callback function
04855 ** with the [database connection] identified by the first argument
04856 ** to be invoked whenever a row is updated, inserted or deleted in
04857 ** a rowid table.
04858 ** ^Any callback set by a previous call to this function
04859 ** for the same database connection is overridden.
04860 **
04861 ** ^The second argument is a pointer to the function to invoke when a
04862 ** row is updated, inserted or deleted in a rowid table.
04863 ** ^The first argument to the callback is a copy of the third argument
04864 ** to sqlite3_update_hook().
04865 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
04866 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
04867 ** to be invoked.
04868 ** ^The third and fourth arguments to the callback contain pointers to the
04869 ** database and table name containing the affected row.
04870 ** ^The final callback parameter is the [rowid] of the row.
04871 ** ^In the case of an update, this is the [rowid] after the update takes place.
04872 **
04873 ** ^(The update hook is not invoked when internal system tables are
04874 ** modified (i.e. sqlite_master and sqlite_sequence).)^
04875 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
04876 **
04877 ** ^In the current implementation, the update hook
04878 ** is not invoked when duplication rows are deleted because of an
04879 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
04880 ** invoked when rows are deleted using the [truncate optimization].
04881 ** The exceptions defined in this paragraph might change in a future
04882 ** release of SQLite.
04883 **
04884 ** The update hook implementation must not do anything that will modify
04885 ** the database connection that invoked the update hook.  Any actions
04886 ** to modify the database connection must be deferred until after the
04887 ** completion of the [sqlite3_step()] call that triggered the update hook.
04888 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
04889 ** database connections for the meaning of "modify" in this paragraph.
04890 **
04891 ** ^The sqlite3_update_hook(D,C,P) function
04892 ** returns the P argument from the previous call
04893 ** on the same [database connection] D, or NULL for
04894 ** the first call on D.
04895 **
04896 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
04897 ** interfaces.
04898 */
04899 SQLITE_API void *sqlite3_update_hook(
04900   sqlite3*, 
04901   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
04902   void*
04903 );
04904 
04905 /*
04906 ** CAPI3REF: Enable Or Disable Shared Pager Cache
04907 **
04908 ** ^(This routine enables or disables the sharing of the database cache
04909 ** and schema data structures between [database connection | connections]
04910 ** to the same database. Sharing is enabled if the argument is true
04911 ** and disabled if the argument is false.)^
04912 **
04913 ** ^Cache sharing is enabled and disabled for an entire process.
04914 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
04915 ** sharing was enabled or disabled for each thread separately.
04916 **
04917 ** ^(The cache sharing mode set by this interface effects all subsequent
04918 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
04919 ** Existing database connections continue use the sharing mode
04920 ** that was in effect at the time they were opened.)^
04921 **
04922 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
04923 ** successfully.  An [error code] is returned otherwise.)^
04924 **
04925 ** ^Shared cache is disabled by default. But this might change in
04926 ** future releases of SQLite.  Applications that care about shared
04927 ** cache setting should set it explicitly.
04928 **
04929 ** This interface is threadsafe on processors where writing a
04930 ** 32-bit integer is atomic.
04931 **
04932 ** See Also:  [SQLite Shared-Cache Mode]
04933 */
04934 SQLITE_API int sqlite3_enable_shared_cache(int);
04935 
04936 /*
04937 ** CAPI3REF: Attempt To Free Heap Memory
04938 **
04939 ** ^The sqlite3_release_memory() interface attempts to free N bytes
04940 ** of heap memory by deallocating non-essential memory allocations
04941 ** held by the database library.   Memory used to cache database
04942 ** pages to improve performance is an example of non-essential memory.
04943 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
04944 ** which might be more or less than the amount requested.
04945 ** ^The sqlite3_release_memory() routine is a no-op returning zero
04946 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
04947 **
04948 ** See also: [sqlite3_db_release_memory()]
04949 */
04950 SQLITE_API int sqlite3_release_memory(int);
04951 
04952 /*
04953 ** CAPI3REF: Free Memory Used By A Database Connection
04954 **
04955 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
04956 ** memory as possible from database connection D. Unlike the
04957 ** [sqlite3_release_memory()] interface, this interface is in effect even
04958 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
04959 ** omitted.
04960 **
04961 ** See also: [sqlite3_release_memory()]
04962 */
04963 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
04964 
04965 /*
04966 ** CAPI3REF: Impose A Limit On Heap Size
04967 **
04968 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
04969 ** soft limit on the amount of heap memory that may be allocated by SQLite.
04970 ** ^SQLite strives to keep heap memory utilization below the soft heap
04971 ** limit by reducing the number of pages held in the page cache
04972 ** as heap memory usages approaches the limit.
04973 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
04974 ** below the limit, it will exceed the limit rather than generate
04975 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
04976 ** is advisory only.
04977 **
04978 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
04979 ** the soft heap limit prior to the call, or negative in the case of an
04980 ** error.  ^If the argument N is negative
04981 ** then no change is made to the soft heap limit.  Hence, the current
04982 ** size of the soft heap limit can be determined by invoking
04983 ** sqlite3_soft_heap_limit64() with a negative argument.
04984 **
04985 ** ^If the argument N is zero then the soft heap limit is disabled.
04986 **
04987 ** ^(The soft heap limit is not enforced in the current implementation
04988 ** if one or more of following conditions are true:
04989 **
04990 ** <ul>
04991 ** <li> The soft heap limit is set to zero.
04992 ** <li> Memory accounting is disabled using a combination of the
04993 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
04994 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
04995 ** <li> An alternative page cache implementation is specified using
04996 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
04997 ** <li> The page cache allocates from its own memory pool supplied
04998 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
04999 **      from the heap.
05000 ** </ul>)^
05001 **
05002 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
05003 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
05004 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
05005 ** the soft heap limit is enforced on every memory allocation.  Without
05006 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
05007 ** when memory is allocated by the page cache.  Testing suggests that because
05008 ** the page cache is the predominate memory user in SQLite, most
05009 ** applications will achieve adequate soft heap limit enforcement without
05010 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
05011 **
05012 ** The circumstances under which SQLite will enforce the soft heap limit may
05013 ** changes in future releases of SQLite.
05014 */
05015 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
05016 
05017 /*
05018 ** CAPI3REF: Deprecated Soft Heap Limit Interface
05019 ** DEPRECATED
05020 **
05021 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
05022 ** interface.  This routine is provided for historical compatibility
05023 ** only.  All new applications should use the
05024 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
05025 */
05026 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
05027 
05028 
05029 /*
05030 ** CAPI3REF: Extract Metadata About A Column Of A Table
05031 **
05032 ** ^This routine returns metadata about a specific column of a specific
05033 ** database table accessible using the [database connection] handle
05034 ** passed as the first function argument.
05035 **
05036 ** ^The column is identified by the second, third and fourth parameters to
05037 ** this function. ^The second parameter is either the name of the database
05038 ** (i.e. "main", "temp", or an attached database) containing the specified
05039 ** table or NULL. ^If it is NULL, then all attached databases are searched
05040 ** for the table using the same algorithm used by the database engine to
05041 ** resolve unqualified table references.
05042 **
05043 ** ^The third and fourth parameters to this function are the table and column
05044 ** name of the desired column, respectively. Neither of these parameters
05045 ** may be NULL.
05046 **
05047 ** ^Metadata is returned by writing to the memory locations passed as the 5th
05048 ** and subsequent parameters to this function. ^Any of these arguments may be
05049 ** NULL, in which case the corresponding element of metadata is omitted.
05050 **
05051 ** ^(<blockquote>
05052 ** <table border="1">
05053 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
05054 **
05055 ** <tr><td> 5th <td> const char* <td> Data type
05056 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
05057 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
05058 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
05059 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
05060 ** </table>
05061 ** </blockquote>)^
05062 **
05063 ** ^The memory pointed to by the character pointers returned for the
05064 ** declaration type and collation sequence is valid only until the next
05065 ** call to any SQLite API function.
05066 **
05067 ** ^If the specified table is actually a view, an [error code] is returned.
05068 **
05069 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
05070 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
05071 ** parameters are set for the explicitly declared column. ^(If there is no
05072 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
05073 ** parameters are set as follows:
05074 **
05075 ** <pre>
05076 **     data type: "INTEGER"
05077 **     collation sequence: "BINARY"
05078 **     not null: 0
05079 **     primary key: 1
05080 **     auto increment: 0
05081 ** </pre>)^
05082 **
05083 ** ^(This function may load one or more schemas from database files. If an
05084 ** error occurs during this process, or if the requested table or column
05085 ** cannot be found, an [error code] is returned and an error message left
05086 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
05087 **
05088 ** ^This API is only available if the library was compiled with the
05089 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
05090 */
05091 SQLITE_API int sqlite3_table_column_metadata(
05092   sqlite3 *db,                /* Connection handle */
05093   const char *zDbName,        /* Database name or NULL */
05094   const char *zTableName,     /* Table name */
05095   const char *zColumnName,    /* Column name */
05096   char const **pzDataType,    /* OUTPUT: Declared data type */
05097   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
05098   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
05099   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
05100   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
05101 );
05102 
05103 /*
05104 ** CAPI3REF: Load An Extension
05105 **
05106 ** ^This interface loads an SQLite extension library from the named file.
05107 **
05108 ** ^The sqlite3_load_extension() interface attempts to load an
05109 ** [SQLite extension] library contained in the file zFile.  If
05110 ** the file cannot be loaded directly, attempts are made to load
05111 ** with various operating-system specific extensions added.
05112 ** So for example, if "samplelib" cannot be loaded, then names like
05113 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
05114 ** be tried also.
05115 **
05116 ** ^The entry point is zProc.
05117 ** ^(zProc may be 0, in which case SQLite will try to come up with an
05118 ** entry point name on its own.  It first tries "sqlite3_extension_init".
05119 ** If that does not work, it constructs a name "sqlite3_X_init" where the
05120 ** X is consists of the lower-case equivalent of all ASCII alphabetic
05121 ** characters in the filename from the last "/" to the first following
05122 ** "." and omitting any initial "lib".)^
05123 ** ^The sqlite3_load_extension() interface returns
05124 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
05125 ** ^If an error occurs and pzErrMsg is not 0, then the
05126 ** [sqlite3_load_extension()] interface shall attempt to
05127 ** fill *pzErrMsg with error message text stored in memory
05128 ** obtained from [sqlite3_malloc()]. The calling function
05129 ** should free this memory by calling [sqlite3_free()].
05130 **
05131 ** ^Extension loading must be enabled using
05132 ** [sqlite3_enable_load_extension()] prior to calling this API,
05133 ** otherwise an error will be returned.
05134 **
05135 ** See also the [load_extension() SQL function].
05136 */
05137 SQLITE_API int sqlite3_load_extension(
05138   sqlite3 *db,          /* Load the extension into this database connection */
05139   const char *zFile,    /* Name of the shared library containing extension */
05140   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
05141   char **pzErrMsg       /* Put error message here if not 0 */
05142 );
05143 
05144 /*
05145 ** CAPI3REF: Enable Or Disable Extension Loading
05146 **
05147 ** ^So as not to open security holes in older applications that are
05148 ** unprepared to deal with [extension loading], and as a means of disabling
05149 ** [extension loading] while evaluating user-entered SQL, the following API
05150 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
05151 **
05152 ** ^Extension loading is off by default.
05153 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
05154 ** to turn extension loading on and call it with onoff==0 to turn
05155 ** it back off again.
05156 */
05157 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
05158 
05159 /*
05160 ** CAPI3REF: Automatically Load Statically Linked Extensions
05161 **
05162 ** ^This interface causes the xEntryPoint() function to be invoked for
05163 ** each new [database connection] that is created.  The idea here is that
05164 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
05165 ** that is to be automatically loaded into all new database connections.
05166 **
05167 ** ^(Even though the function prototype shows that xEntryPoint() takes
05168 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
05169 ** arguments and expects and integer result as if the signature of the
05170 ** entry point where as follows:
05171 **
05172 ** <blockquote><pre>
05173 ** &nbsp;  int xEntryPoint(
05174 ** &nbsp;    sqlite3 *db,
05175 ** &nbsp;    const char **pzErrMsg,
05176 ** &nbsp;    const struct sqlite3_api_routines *pThunk
05177 ** &nbsp;  );
05178 ** </pre></blockquote>)^
05179 **
05180 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
05181 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
05182 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
05183 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
05184 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
05185 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
05186 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
05187 **
05188 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
05189 ** on the list of automatic extensions is a harmless no-op. ^No entry point
05190 ** will be called more than once for each database connection that is opened.
05191 **
05192 ** See also: [sqlite3_reset_auto_extension()]
05193 ** and [sqlite3_cancel_auto_extension()]
05194 */
05195 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
05196 
05197 /*
05198 ** CAPI3REF: Cancel Automatic Extension Loading
05199 **
05200 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
05201 ** initialization routine X that was registered using a prior call to
05202 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
05203 ** routine returns 1 if initialization routine X was successfully 
05204 ** unregistered and it returns 0 if X was not on the list of initialization
05205 ** routines.
05206 */
05207 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
05208 
05209 /*
05210 ** CAPI3REF: Reset Automatic Extension Loading
05211 **
05212 ** ^This interface disables all automatic extensions previously
05213 ** registered using [sqlite3_auto_extension()].
05214 */
05215 SQLITE_API void sqlite3_reset_auto_extension(void);
05216 
05217 /*
05218 ** The interface to the virtual-table mechanism is currently considered
05219 ** to be experimental.  The interface might change in incompatible ways.
05220 ** If this is a problem for you, do not use the interface at this time.
05221 **
05222 ** When the virtual-table mechanism stabilizes, we will declare the
05223 ** interface fixed, support it indefinitely, and remove this comment.
05224 */
05225 
05226 /*
05227 ** Structures used by the virtual table interface
05228 */
05229 typedef struct sqlite3_vtab sqlite3_vtab;
05230 typedef struct sqlite3_index_info sqlite3_index_info;
05231 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
05232 typedef struct sqlite3_module sqlite3_module;
05233 
05234 /*
05235 ** CAPI3REF: Virtual Table Object
05236 ** KEYWORDS: sqlite3_module {virtual table module}
05237 **
05238 ** This structure, sometimes called a "virtual table module", 
05239 ** defines the implementation of a [virtual tables].  
05240 ** This structure consists mostly of methods for the module.
05241 **
05242 ** ^A virtual table module is created by filling in a persistent
05243 ** instance of this structure and passing a pointer to that instance
05244 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
05245 ** ^The registration remains valid until it is replaced by a different
05246 ** module or until the [database connection] closes.  The content
05247 ** of this structure must not change while it is registered with
05248 ** any database connection.
05249 */
05250 struct sqlite3_module {
05251   int iVersion;
05252   int (*xCreate)(sqlite3*, void *pAux,
05253                int argc, const char *const*argv,
05254                sqlite3_vtab **ppVTab, char**);
05255   int (*xConnect)(sqlite3*, void *pAux,
05256                int argc, const char *const*argv,
05257                sqlite3_vtab **ppVTab, char**);
05258   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
05259   int (*xDisconnect)(sqlite3_vtab *pVTab);
05260   int (*xDestroy)(sqlite3_vtab *pVTab);
05261   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
05262   int (*xClose)(sqlite3_vtab_cursor*);
05263   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
05264                 int argc, sqlite3_value **argv);
05265   int (*xNext)(sqlite3_vtab_cursor*);
05266   int (*xEof)(sqlite3_vtab_cursor*);
05267   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
05268   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
05269   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
05270   int (*xBegin)(sqlite3_vtab *pVTab);
05271   int (*xSync)(sqlite3_vtab *pVTab);
05272   int (*xCommit)(sqlite3_vtab *pVTab);
05273   int (*xRollback)(sqlite3_vtab *pVTab);
05274   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
05275                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
05276                        void **ppArg);
05277   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
05278   /* The methods above are in version 1 of the sqlite_module object. Those 
05279   ** below are for version 2 and greater. */
05280   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
05281   int (*xRelease)(sqlite3_vtab *pVTab, int);
05282   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
05283 };
05284 
05285 /*
05286 ** CAPI3REF: Virtual Table Indexing Information
05287 ** KEYWORDS: sqlite3_index_info
05288 **
05289 ** The sqlite3_index_info structure and its substructures is used as part
05290 ** of the [virtual table] interface to
05291 ** pass information into and receive the reply from the [xBestIndex]
05292 ** method of a [virtual table module].  The fields under **Inputs** are the
05293 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
05294 ** results into the **Outputs** fields.
05295 **
05296 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
05297 **
05298 ** <blockquote>column OP expr</blockquote>
05299 **
05300 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
05301 ** stored in aConstraint[].op using one of the
05302 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
05303 ** ^(The index of the column is stored in
05304 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
05305 ** expr on the right-hand side can be evaluated (and thus the constraint
05306 ** is usable) and false if it cannot.)^
05307 **
05308 ** ^The optimizer automatically inverts terms of the form "expr OP column"
05309 ** and makes other simplifications to the WHERE clause in an attempt to
05310 ** get as many WHERE clause terms into the form shown above as possible.
05311 ** ^The aConstraint[] array only reports WHERE clause terms that are
05312 ** relevant to the particular virtual table being queried.
05313 **
05314 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
05315 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
05316 **
05317 ** The [xBestIndex] method must fill aConstraintUsage[] with information
05318 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
05319 ** the right-hand side of the corresponding aConstraint[] is evaluated
05320 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
05321 ** is true, then the constraint is assumed to be fully handled by the
05322 ** virtual table and is not checked again by SQLite.)^
05323 **
05324 ** ^The idxNum and idxPtr values are recorded and passed into the
05325 ** [xFilter] method.
05326 ** ^[sqlite3_free()] is used to free idxPtr if and only if
05327 ** needToFreeIdxPtr is true.
05328 **
05329 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
05330 ** the correct order to satisfy the ORDER BY clause so that no separate
05331 ** sorting step is required.
05332 **
05333 ** ^The estimatedCost value is an estimate of the cost of a particular
05334 ** strategy. A cost of N indicates that the cost of the strategy is similar
05335 ** to a linear scan of an SQLite table with N rows. A cost of log(N) 
05336 ** indicates that the expense of the operation is similar to that of a
05337 ** binary search on a unique indexed field of an SQLite table with N rows.
05338 **
05339 ** ^The estimatedRows value is an estimate of the number of rows that
05340 ** will be returned by the strategy.
05341 **
05342 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
05343 ** structure for SQLite version 3.8.2. If a virtual table extension is
05344 ** used with an SQLite version earlier than 3.8.2, the results of attempting 
05345 ** to read or write the estimatedRows field are undefined (but are likely 
05346 ** to included crashing the application). The estimatedRows field should
05347 ** therefore only be used if [sqlite3_libversion_number()] returns a
05348 ** value greater than or equal to 3008002.
05349 */
05350 struct sqlite3_index_info {
05351   /* Inputs */
05352   int nConstraint;           /* Number of entries in aConstraint */
05353   struct sqlite3_index_constraint {
05354      int iColumn;              /* Column on left-hand side of constraint */
05355      unsigned char op;         /* Constraint operator */
05356      unsigned char usable;     /* True if this constraint is usable */
05357      int iTermOffset;          /* Used internally - xBestIndex should ignore */
05358   } *aConstraint;            /* Table of WHERE clause constraints */
05359   int nOrderBy;              /* Number of terms in the ORDER BY clause */
05360   struct sqlite3_index_orderby {
05361      int iColumn;              /* Column number */
05362      unsigned char desc;       /* True for DESC.  False for ASC. */
05363   } *aOrderBy;               /* The ORDER BY clause */
05364   /* Outputs */
05365   struct sqlite3_index_constraint_usage {
05366     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
05367     unsigned char omit;      /* Do not code a test for this constraint */
05368   } *aConstraintUsage;
05369   int idxNum;                /* Number used to identify the index */
05370   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
05371   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
05372   int orderByConsumed;       /* True if output is already ordered */
05373   double estimatedCost;           /* Estimated cost of using this index */
05374   /* Fields below are only available in SQLite 3.8.2 and later */
05375   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
05376 };
05377 
05378 /*
05379 ** CAPI3REF: Virtual Table Constraint Operator Codes
05380 **
05381 ** These macros defined the allowed values for the
05382 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
05383 ** an operator that is part of a constraint term in the wHERE clause of
05384 ** a query that uses a [virtual table].
05385 */
05386 #define SQLITE_INDEX_CONSTRAINT_EQ    2
05387 #define SQLITE_INDEX_CONSTRAINT_GT    4
05388 #define SQLITE_INDEX_CONSTRAINT_LE    8
05389 #define SQLITE_INDEX_CONSTRAINT_LT    16
05390 #define SQLITE_INDEX_CONSTRAINT_GE    32
05391 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
05392 
05393 /*
05394 ** CAPI3REF: Register A Virtual Table Implementation
05395 **
05396 ** ^These routines are used to register a new [virtual table module] name.
05397 ** ^Module names must be registered before
05398 ** creating a new [virtual table] using the module and before using a
05399 ** preexisting [virtual table] for the module.
05400 **
05401 ** ^The module name is registered on the [database connection] specified
05402 ** by the first parameter.  ^The name of the module is given by the 
05403 ** second parameter.  ^The third parameter is a pointer to
05404 ** the implementation of the [virtual table module].   ^The fourth
05405 ** parameter is an arbitrary client data pointer that is passed through
05406 ** into the [xCreate] and [xConnect] methods of the virtual table module
05407 ** when a new virtual table is be being created or reinitialized.
05408 **
05409 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
05410 ** is a pointer to a destructor for the pClientData.  ^SQLite will
05411 ** invoke the destructor function (if it is not NULL) when SQLite
05412 ** no longer needs the pClientData pointer.  ^The destructor will also
05413 ** be invoked if the call to sqlite3_create_module_v2() fails.
05414 ** ^The sqlite3_create_module()
05415 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
05416 ** destructor.
05417 */
05418 SQLITE_API int sqlite3_create_module(
05419   sqlite3 *db,               /* SQLite connection to register module with */
05420   const char *zName,         /* Name of the module */
05421   const sqlite3_module *p,   /* Methods for the module */
05422   void *pClientData          /* Client data for xCreate/xConnect */
05423 );
05424 SQLITE_API int sqlite3_create_module_v2(
05425   sqlite3 *db,               /* SQLite connection to register module with */
05426   const char *zName,         /* Name of the module */
05427   const sqlite3_module *p,   /* Methods for the module */
05428   void *pClientData,         /* Client data for xCreate/xConnect */
05429   void(*xDestroy)(void*)     /* Module destructor function */
05430 );
05431 
05432 /*
05433 ** CAPI3REF: Virtual Table Instance Object
05434 ** KEYWORDS: sqlite3_vtab
05435 **
05436 ** Every [virtual table module] implementation uses a subclass
05437 ** of this object to describe a particular instance
05438 ** of the [virtual table].  Each subclass will
05439 ** be tailored to the specific needs of the module implementation.
05440 ** The purpose of this superclass is to define certain fields that are
05441 ** common to all module implementations.
05442 **
05443 ** ^Virtual tables methods can set an error message by assigning a
05444 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
05445 ** take care that any prior string is freed by a call to [sqlite3_free()]
05446 ** prior to assigning a new string to zErrMsg.  ^After the error message
05447 ** is delivered up to the client application, the string will be automatically
05448 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
05449 */
05450 struct sqlite3_vtab {
05451   const sqlite3_module *pModule;  /* The module for this virtual table */
05452   int nRef;                       /* NO LONGER USED */
05453   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
05454   /* Virtual table implementations will typically add additional fields */
05455 };
05456 
05457 /*
05458 ** CAPI3REF: Virtual Table Cursor Object
05459 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
05460 **
05461 ** Every [virtual table module] implementation uses a subclass of the
05462 ** following structure to describe cursors that point into the
05463 ** [virtual table] and are used
05464 ** to loop through the virtual table.  Cursors are created using the
05465 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
05466 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
05467 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
05468 ** of the module.  Each module implementation will define
05469 ** the content of a cursor structure to suit its own needs.
05470 **
05471 ** This superclass exists in order to define fields of the cursor that
05472 ** are common to all implementations.
05473 */
05474 struct sqlite3_vtab_cursor {
05475   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
05476   /* Virtual table implementations will typically add additional fields */
05477 };
05478 
05479 /*
05480 ** CAPI3REF: Declare The Schema Of A Virtual Table
05481 **
05482 ** ^The [xCreate] and [xConnect] methods of a
05483 ** [virtual table module] call this interface
05484 ** to declare the format (the names and datatypes of the columns) of
05485 ** the virtual tables they implement.
05486 */
05487 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
05488 
05489 /*
05490 ** CAPI3REF: Overload A Function For A Virtual Table
05491 **
05492 ** ^(Virtual tables can provide alternative implementations of functions
05493 ** using the [xFindFunction] method of the [virtual table module].  
05494 ** But global versions of those functions
05495 ** must exist in order to be overloaded.)^
05496 **
05497 ** ^(This API makes sure a global version of a function with a particular
05498 ** name and number of parameters exists.  If no such function exists
05499 ** before this API is called, a new function is created.)^  ^The implementation
05500 ** of the new function always causes an exception to be thrown.  So
05501 ** the new function is not good for anything by itself.  Its only
05502 ** purpose is to be a placeholder function that can be overloaded
05503 ** by a [virtual table].
05504 */
05505 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
05506 
05507 /*
05508 ** The interface to the virtual-table mechanism defined above (back up
05509 ** to a comment remarkably similar to this one) is currently considered
05510 ** to be experimental.  The interface might change in incompatible ways.
05511 ** If this is a problem for you, do not use the interface at this time.
05512 **
05513 ** When the virtual-table mechanism stabilizes, we will declare the
05514 ** interface fixed, support it indefinitely, and remove this comment.
05515 */
05516 
05517 /*
05518 ** CAPI3REF: A Handle To An Open BLOB
05519 ** KEYWORDS: {BLOB handle} {BLOB handles}
05520 **
05521 ** An instance of this object represents an open BLOB on which
05522 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
05523 ** ^Objects of this type are created by [sqlite3_blob_open()]
05524 ** and destroyed by [sqlite3_blob_close()].
05525 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
05526 ** can be used to read or write small subsections of the BLOB.
05527 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
05528 */
05529 typedef struct sqlite3_blob sqlite3_blob;
05530 
05531 /*
05532 ** CAPI3REF: Open A BLOB For Incremental I/O
05533 **
05534 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
05535 ** in row iRow, column zColumn, table zTable in database zDb;
05536 ** in other words, the same BLOB that would be selected by:
05537 **
05538 ** <pre>
05539 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
05540 ** </pre>)^
05541 **
05542 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
05543 ** and write access. ^If it is zero, the BLOB is opened for read access.
05544 ** ^It is not possible to open a column that is part of an index or primary 
05545 ** key for writing. ^If [foreign key constraints] are enabled, it is 
05546 ** not possible to open a column that is part of a [child key] for writing.
05547 **
05548 ** ^Note that the database name is not the filename that contains
05549 ** the database but rather the symbolic name of the database that
05550 ** appears after the AS keyword when the database is connected using [ATTACH].
05551 ** ^For the main database file, the database name is "main".
05552 ** ^For TEMP tables, the database name is "temp".
05553 **
05554 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
05555 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
05556 ** to be a null pointer.)^
05557 ** ^This function sets the [database connection] error code and message
05558 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
05559 ** functions. ^Note that the *ppBlob variable is always initialized in a
05560 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
05561 ** regardless of the success or failure of this routine.
05562 **
05563 ** ^(If the row that a BLOB handle points to is modified by an
05564 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
05565 ** then the BLOB handle is marked as "expired".
05566 ** This is true if any column of the row is changed, even a column
05567 ** other than the one the BLOB handle is open on.)^
05568 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
05569 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
05570 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
05571 ** rolled back by the expiration of the BLOB.  Such changes will eventually
05572 ** commit if the transaction continues to completion.)^
05573 **
05574 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
05575 ** the opened blob.  ^The size of a blob may not be changed by this
05576 ** interface.  Use the [UPDATE] SQL command to change the size of a
05577 ** blob.
05578 **
05579 ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
05580 ** table.  Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
05581 **
05582 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
05583 ** and the built-in [zeroblob] SQL function can be used, if desired,
05584 ** to create an empty, zero-filled blob in which to read or write using
05585 ** this interface.
05586 **
05587 ** To avoid a resource leak, every open [BLOB handle] should eventually
05588 ** be released by a call to [sqlite3_blob_close()].
05589 */
05590 SQLITE_API int sqlite3_blob_open(
05591   sqlite3*,
05592   const char *zDb,
05593   const char *zTable,
05594   const char *zColumn,
05595   sqlite3_int64 iRow,
05596   int flags,
05597   sqlite3_blob **ppBlob
05598 );
05599 
05600 /*
05601 ** CAPI3REF: Move a BLOB Handle to a New Row
05602 **
05603 ** ^This function is used to move an existing blob handle so that it points
05604 ** to a different row of the same database table. ^The new row is identified
05605 ** by the rowid value passed as the second argument. Only the row can be
05606 ** changed. ^The database, table and column on which the blob handle is open
05607 ** remain the same. Moving an existing blob handle to a new row can be
05608 ** faster than closing the existing handle and opening a new one.
05609 **
05610 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
05611 ** it must exist and there must be either a blob or text value stored in
05612 ** the nominated column.)^ ^If the new row is not present in the table, or if
05613 ** it does not contain a blob or text value, or if another error occurs, an
05614 ** SQLite error code is returned and the blob handle is considered aborted.
05615 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
05616 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
05617 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
05618 ** always returns zero.
05619 **
05620 ** ^This function sets the database handle error code and message.
05621 */
05622 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
05623 
05624 /*
05625 ** CAPI3REF: Close A BLOB Handle
05626 **
05627 ** ^Closes an open [BLOB handle].
05628 **
05629 ** ^Closing a BLOB shall cause the current transaction to commit
05630 ** if there are no other BLOBs, no pending prepared statements, and the
05631 ** database connection is in [autocommit mode].
05632 ** ^If any writes were made to the BLOB, they might be held in cache
05633 ** until the close operation if they will fit.
05634 **
05635 ** ^(Closing the BLOB often forces the changes
05636 ** out to disk and so if any I/O errors occur, they will likely occur
05637 ** at the time when the BLOB is closed.  Any errors that occur during
05638 ** closing are reported as a non-zero return value.)^
05639 **
05640 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
05641 ** an error code, the BLOB is still closed.)^
05642 **
05643 ** ^Calling this routine with a null pointer (such as would be returned
05644 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
05645 */
05646 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
05647 
05648 /*
05649 ** CAPI3REF: Return The Size Of An Open BLOB
05650 **
05651 ** ^Returns the size in bytes of the BLOB accessible via the 
05652 ** successfully opened [BLOB handle] in its only argument.  ^The
05653 ** incremental blob I/O routines can only read or overwriting existing
05654 ** blob content; they cannot change the size of a blob.
05655 **
05656 ** This routine only works on a [BLOB handle] which has been created
05657 ** by a prior successful call to [sqlite3_blob_open()] and which has not
05658 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
05659 ** to this routine results in undefined and probably undesirable behavior.
05660 */
05661 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
05662 
05663 /*
05664 ** CAPI3REF: Read Data From A BLOB Incrementally
05665 **
05666 ** ^(This function is used to read data from an open [BLOB handle] into a
05667 ** caller-supplied buffer. N bytes of data are copied into buffer Z
05668 ** from the open BLOB, starting at offset iOffset.)^
05669 **
05670 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
05671 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
05672 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
05673 ** ^The size of the blob (and hence the maximum value of N+iOffset)
05674 ** can be determined using the [sqlite3_blob_bytes()] interface.
05675 **
05676 ** ^An attempt to read from an expired [BLOB handle] fails with an
05677 ** error code of [SQLITE_ABORT].
05678 **
05679 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
05680 ** Otherwise, an [error code] or an [extended error code] is returned.)^
05681 **
05682 ** This routine only works on a [BLOB handle] which has been created
05683 ** by a prior successful call to [sqlite3_blob_open()] and which has not
05684 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
05685 ** to this routine results in undefined and probably undesirable behavior.
05686 **
05687 ** See also: [sqlite3_blob_write()].
05688 */
05689 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
05690 
05691 /*
05692 ** CAPI3REF: Write Data Into A BLOB Incrementally
05693 **
05694 ** ^This function is used to write data into an open [BLOB handle] from a
05695 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
05696 ** into the open BLOB, starting at offset iOffset.
05697 **
05698 ** ^If the [BLOB handle] passed as the first argument was not opened for
05699 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
05700 ** this function returns [SQLITE_READONLY].
05701 **
05702 ** ^This function may only modify the contents of the BLOB; it is
05703 ** not possible to increase the size of a BLOB using this API.
05704 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
05705 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
05706 ** less than zero [SQLITE_ERROR] is returned and no data is written.
05707 ** The size of the BLOB (and hence the maximum value of N+iOffset)
05708 ** can be determined using the [sqlite3_blob_bytes()] interface.
05709 **
05710 ** ^An attempt to write to an expired [BLOB handle] fails with an
05711 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
05712 ** before the [BLOB handle] expired are not rolled back by the
05713 ** expiration of the handle, though of course those changes might
05714 ** have been overwritten by the statement that expired the BLOB handle
05715 ** or by other independent statements.
05716 **
05717 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
05718 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
05719 **
05720 ** This routine only works on a [BLOB handle] which has been created
05721 ** by a prior successful call to [sqlite3_blob_open()] and which has not
05722 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
05723 ** to this routine results in undefined and probably undesirable behavior.
05724 **
05725 ** See also: [sqlite3_blob_read()].
05726 */
05727 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
05728 
05729 /*
05730 ** CAPI3REF: Virtual File System Objects
05731 **
05732 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
05733 ** that SQLite uses to interact
05734 ** with the underlying operating system.  Most SQLite builds come with a
05735 ** single default VFS that is appropriate for the host computer.
05736 ** New VFSes can be registered and existing VFSes can be unregistered.
05737 ** The following interfaces are provided.
05738 **
05739 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
05740 ** ^Names are case sensitive.
05741 ** ^Names are zero-terminated UTF-8 strings.
05742 ** ^If there is no match, a NULL pointer is returned.
05743 ** ^If zVfsName is NULL then the default VFS is returned.
05744 **
05745 ** ^New VFSes are registered with sqlite3_vfs_register().
05746 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
05747 ** ^The same VFS can be registered multiple times without injury.
05748 ** ^To make an existing VFS into the default VFS, register it again
05749 ** with the makeDflt flag set.  If two different VFSes with the
05750 ** same name are registered, the behavior is undefined.  If a
05751 ** VFS is registered with a name that is NULL or an empty string,
05752 ** then the behavior is undefined.
05753 **
05754 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
05755 ** ^(If the default VFS is unregistered, another VFS is chosen as
05756 ** the default.  The choice for the new VFS is arbitrary.)^
05757 */
05758 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
05759 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
05760 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
05761 
05762 /*
05763 ** CAPI3REF: Mutexes
05764 **
05765 ** The SQLite core uses these routines for thread
05766 ** synchronization. Though they are intended for internal
05767 ** use by SQLite, code that links against SQLite is
05768 ** permitted to use any of these routines.
05769 **
05770 ** The SQLite source code contains multiple implementations
05771 ** of these mutex routines.  An appropriate implementation
05772 ** is selected automatically at compile-time.  ^(The following
05773 ** implementations are available in the SQLite core:
05774 **
05775 ** <ul>
05776 ** <li>   SQLITE_MUTEX_PTHREADS
05777 ** <li>   SQLITE_MUTEX_W32
05778 ** <li>   SQLITE_MUTEX_NOOP
05779 ** </ul>)^
05780 **
05781 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
05782 ** that does no real locking and is appropriate for use in
05783 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
05784 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
05785 ** and Windows.
05786 **
05787 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
05788 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
05789 ** implementation is included with the library. In this case the
05790 ** application must supply a custom mutex implementation using the
05791 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
05792 ** before calling sqlite3_initialize() or any other public sqlite3_
05793 ** function that calls sqlite3_initialize().)^
05794 **
05795 ** ^The sqlite3_mutex_alloc() routine allocates a new
05796 ** mutex and returns a pointer to it. ^If it returns NULL
05797 ** that means that a mutex could not be allocated.  ^SQLite
05798 ** will unwind its stack and return an error.  ^(The argument
05799 ** to sqlite3_mutex_alloc() is one of these integer constants:
05800 **
05801 ** <ul>
05802 ** <li>  SQLITE_MUTEX_FAST
05803 ** <li>  SQLITE_MUTEX_RECURSIVE
05804 ** <li>  SQLITE_MUTEX_STATIC_MASTER
05805 ** <li>  SQLITE_MUTEX_STATIC_MEM
05806 ** <li>  SQLITE_MUTEX_STATIC_MEM2
05807 ** <li>  SQLITE_MUTEX_STATIC_PRNG
05808 ** <li>  SQLITE_MUTEX_STATIC_LRU
05809 ** <li>  SQLITE_MUTEX_STATIC_LRU2
05810 ** </ul>)^
05811 **
05812 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
05813 ** cause sqlite3_mutex_alloc() to create
05814 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
05815 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
05816 ** The mutex implementation does not need to make a distinction
05817 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
05818 ** not want to.  ^SQLite will only request a recursive mutex in
05819 ** cases where it really needs one.  ^If a faster non-recursive mutex
05820 ** implementation is available on the host platform, the mutex subsystem
05821 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
05822 **
05823 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
05824 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
05825 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
05826 ** used by the current version of SQLite.  Future versions of SQLite
05827 ** may add additional static mutexes.  Static mutexes are for internal
05828 ** use by SQLite only.  Applications that use SQLite mutexes should
05829 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
05830 ** SQLITE_MUTEX_RECURSIVE.
05831 **
05832 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
05833 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
05834 ** returns a different mutex on every call.  ^But for the static
05835 ** mutex types, the same mutex is returned on every call that has
05836 ** the same type number.
05837 **
05838 ** ^The sqlite3_mutex_free() routine deallocates a previously
05839 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
05840 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
05841 ** use when they are deallocated.  Attempting to deallocate a static
05842 ** mutex results in undefined behavior.  ^SQLite never deallocates
05843 ** a static mutex.
05844 **
05845 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
05846 ** to enter a mutex.  ^If another thread is already within the mutex,
05847 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
05848 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
05849 ** upon successful entry.  ^(Mutexes created using
05850 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
05851 ** In such cases the,
05852 ** mutex must be exited an equal number of times before another thread
05853 ** can enter.)^  ^(If the same thread tries to enter any other
05854 ** kind of mutex more than once, the behavior is undefined.
05855 ** SQLite will never exhibit
05856 ** such behavior in its own use of mutexes.)^
05857 **
05858 ** ^(Some systems (for example, Windows 95) do not support the operation
05859 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
05860 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
05861 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
05862 **
05863 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
05864 ** previously entered by the same thread.   ^(The behavior
05865 ** is undefined if the mutex is not currently entered by the
05866 ** calling thread or is not currently allocated.  SQLite will
05867 ** never do either.)^
05868 **
05869 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
05870 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
05871 ** behave as no-ops.
05872 **
05873 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
05874 */
05875 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
05876 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
05877 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
05878 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
05879 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
05880 
05881 /*
05882 ** CAPI3REF: Mutex Methods Object
05883 **
05884 ** An instance of this structure defines the low-level routines
05885 ** used to allocate and use mutexes.
05886 **
05887 ** Usually, the default mutex implementations provided by SQLite are
05888 ** sufficient, however the user has the option of substituting a custom
05889 ** implementation for specialized deployments or systems for which SQLite
05890 ** does not provide a suitable implementation. In this case, the user
05891 ** creates and populates an instance of this structure to pass
05892 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
05893 ** Additionally, an instance of this structure can be used as an
05894 ** output variable when querying the system for the current mutex
05895 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
05896 **
05897 ** ^The xMutexInit method defined by this structure is invoked as
05898 ** part of system initialization by the sqlite3_initialize() function.
05899 ** ^The xMutexInit routine is called by SQLite exactly once for each
05900 ** effective call to [sqlite3_initialize()].
05901 **
05902 ** ^The xMutexEnd method defined by this structure is invoked as
05903 ** part of system shutdown by the sqlite3_shutdown() function. The
05904 ** implementation of this method is expected to release all outstanding
05905 ** resources obtained by the mutex methods implementation, especially
05906 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
05907 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
05908 **
05909 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
05910 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
05911 ** xMutexNotheld) implement the following interfaces (respectively):
05912 **
05913 ** <ul>
05914 **   <li>  [sqlite3_mutex_alloc()] </li>
05915 **   <li>  [sqlite3_mutex_free()] </li>
05916 **   <li>  [sqlite3_mutex_enter()] </li>
05917 **   <li>  [sqlite3_mutex_try()] </li>
05918 **   <li>  [sqlite3_mutex_leave()] </li>
05919 **   <li>  [sqlite3_mutex_held()] </li>
05920 **   <li>  [sqlite3_mutex_notheld()] </li>
05921 ** </ul>)^
05922 **
05923 ** The only difference is that the public sqlite3_XXX functions enumerated
05924 ** above silently ignore any invocations that pass a NULL pointer instead
05925 ** of a valid mutex handle. The implementations of the methods defined
05926 ** by this structure are not required to handle this case, the results
05927 ** of passing a NULL pointer instead of a valid mutex handle are undefined
05928 ** (i.e. it is acceptable to provide an implementation that segfaults if
05929 ** it is passed a NULL pointer).
05930 **
05931 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
05932 ** invoke xMutexInit() multiple times within the same process and without
05933 ** intervening calls to xMutexEnd().  Second and subsequent calls to
05934 ** xMutexInit() must be no-ops.
05935 **
05936 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
05937 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
05938 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
05939 ** memory allocation for a fast or recursive mutex.
05940 **
05941 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
05942 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
05943 ** If xMutexInit fails in any way, it is expected to clean up after itself
05944 ** prior to returning.
05945 */
05946 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
05947 struct sqlite3_mutex_methods {
05948   int (*xMutexInit)(void);
05949   int (*xMutexEnd)(void);
05950   sqlite3_mutex *(*xMutexAlloc)(int);
05951   void (*xMutexFree)(sqlite3_mutex *);
05952   void (*xMutexEnter)(sqlite3_mutex *);
05953   int (*xMutexTry)(sqlite3_mutex *);
05954   void (*xMutexLeave)(sqlite3_mutex *);
05955   int (*xMutexHeld)(sqlite3_mutex *);
05956   int (*xMutexNotheld)(sqlite3_mutex *);
05957 };
05958 
05959 /*
05960 ** CAPI3REF: Mutex Verification Routines
05961 **
05962 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
05963 ** are intended for use inside assert() statements.  ^The SQLite core
05964 ** never uses these routines except inside an assert() and applications
05965 ** are advised to follow the lead of the core.  ^The SQLite core only
05966 ** provides implementations for these routines when it is compiled
05967 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
05968 ** are only required to provide these routines if SQLITE_DEBUG is
05969 ** defined and if NDEBUG is not defined.
05970 **
05971 ** ^These routines should return true if the mutex in their argument
05972 ** is held or not held, respectively, by the calling thread.
05973 **
05974 ** ^The implementation is not required to provide versions of these
05975 ** routines that actually work. If the implementation does not provide working
05976 ** versions of these routines, it should at least provide stubs that always
05977 ** return true so that one does not get spurious assertion failures.
05978 **
05979 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
05980 ** the routine should return 1.   This seems counter-intuitive since
05981 ** clearly the mutex cannot be held if it does not exist.  But
05982 ** the reason the mutex does not exist is because the build is not
05983 ** using mutexes.  And we do not want the assert() containing the
05984 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
05985 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
05986 ** interface should also return 1 when given a NULL pointer.
05987 */
05988 #ifndef NDEBUG
05989 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
05990 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
05991 #endif
05992 
05993 /*
05994 ** CAPI3REF: Mutex Types
05995 **
05996 ** The [sqlite3_mutex_alloc()] interface takes a single argument
05997 ** which is one of these integer constants.
05998 **
05999 ** The set of static mutexes may change from one SQLite release to the
06000 ** next.  Applications that override the built-in mutex logic must be
06001 ** prepared to accommodate additional static mutexes.
06002 */
06003 #define SQLITE_MUTEX_FAST             0
06004 #define SQLITE_MUTEX_RECURSIVE        1
06005 #define SQLITE_MUTEX_STATIC_MASTER    2
06006 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
06007 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
06008 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
06009 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
06010 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
06011 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
06012 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
06013 
06014 /*
06015 ** CAPI3REF: Retrieve the mutex for a database connection
06016 **
06017 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
06018 ** serializes access to the [database connection] given in the argument
06019 ** when the [threading mode] is Serialized.
06020 ** ^If the [threading mode] is Single-thread or Multi-thread then this
06021 ** routine returns a NULL pointer.
06022 */
06023 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
06024 
06025 /*
06026 ** CAPI3REF: Low-Level Control Of Database Files
06027 **
06028 ** ^The [sqlite3_file_control()] interface makes a direct call to the
06029 ** xFileControl method for the [sqlite3_io_methods] object associated
06030 ** with a particular database identified by the second argument. ^The
06031 ** name of the database is "main" for the main database or "temp" for the
06032 ** TEMP database, or the name that appears after the AS keyword for
06033 ** databases that are added using the [ATTACH] SQL command.
06034 ** ^A NULL pointer can be used in place of "main" to refer to the
06035 ** main database file.
06036 ** ^The third and fourth parameters to this routine
06037 ** are passed directly through to the second and third parameters of
06038 ** the xFileControl method.  ^The return value of the xFileControl
06039 ** method becomes the return value of this routine.
06040 **
06041 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
06042 ** a pointer to the underlying [sqlite3_file] object to be written into
06043 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
06044 ** case is a short-circuit path which does not actually invoke the
06045 ** underlying sqlite3_io_methods.xFileControl method.
06046 **
06047 ** ^If the second parameter (zDbName) does not match the name of any
06048 ** open database file, then SQLITE_ERROR is returned.  ^This error
06049 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
06050 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
06051 ** also return SQLITE_ERROR.  There is no way to distinguish between
06052 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
06053 ** xFileControl method.
06054 **
06055 ** See also: [SQLITE_FCNTL_LOCKSTATE]
06056 */
06057 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
06058 
06059 /*
06060 ** CAPI3REF: Testing Interface
06061 **
06062 ** ^The sqlite3_test_control() interface is used to read out internal
06063 ** state of SQLite and to inject faults into SQLite for testing
06064 ** purposes.  ^The first parameter is an operation code that determines
06065 ** the number, meaning, and operation of all subsequent parameters.
06066 **
06067 ** This interface is not for use by applications.  It exists solely
06068 ** for verifying the correct operation of the SQLite library.  Depending
06069 ** on how the SQLite library is compiled, this interface might not exist.
06070 **
06071 ** The details of the operation codes, their meanings, the parameters
06072 ** they take, and what they do are all subject to change without notice.
06073 ** Unlike most of the SQLite API, this function is not guaranteed to
06074 ** operate consistently from one release to the next.
06075 */
06076 SQLITE_API int sqlite3_test_control(int op, ...);
06077 
06078 /*
06079 ** CAPI3REF: Testing Interface Operation Codes
06080 **
06081 ** These constants are the valid operation code parameters used
06082 ** as the first argument to [sqlite3_test_control()].
06083 **
06084 ** These parameters and their meanings are subject to change
06085 ** without notice.  These values are for testing purposes only.
06086 ** Applications should not use any of these parameters or the
06087 ** [sqlite3_test_control()] interface.
06088 */
06089 #define SQLITE_TESTCTRL_FIRST                    5
06090 #define SQLITE_TESTCTRL_PRNG_SAVE                5
06091 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
06092 #define SQLITE_TESTCTRL_PRNG_RESET               7
06093 #define SQLITE_TESTCTRL_BITVEC_TEST              8
06094 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
06095 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
06096 #define SQLITE_TESTCTRL_PENDING_BYTE            11
06097 #define SQLITE_TESTCTRL_ASSERT                  12
06098 #define SQLITE_TESTCTRL_ALWAYS                  13
06099 #define SQLITE_TESTCTRL_RESERVE                 14
06100 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
06101 #define SQLITE_TESTCTRL_ISKEYWORD               16
06102 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
06103 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
06104 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
06105 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
06106 #define SQLITE_TESTCTRL_LAST                    20
06107 
06108 /*
06109 ** CAPI3REF: SQLite Runtime Status
06110 **
06111 ** ^This interface is used to retrieve runtime status information
06112 ** about the performance of SQLite, and optionally to reset various
06113 ** highwater marks.  ^The first argument is an integer code for
06114 ** the specific parameter to measure.  ^(Recognized integer codes
06115 ** are of the form [status parameters | SQLITE_STATUS_...].)^
06116 ** ^The current value of the parameter is returned into *pCurrent.
06117 ** ^The highest recorded value is returned in *pHighwater.  ^If the
06118 ** resetFlag is true, then the highest record value is reset after
06119 ** *pHighwater is written.  ^(Some parameters do not record the highest
06120 ** value.  For those parameters
06121 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
06122 ** ^(Other parameters record only the highwater mark and not the current
06123 ** value.  For these latter parameters nothing is written into *pCurrent.)^
06124 **
06125 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
06126 ** non-zero [error code] on failure.
06127 **
06128 ** This routine is threadsafe but is not atomic.  This routine can be
06129 ** called while other threads are running the same or different SQLite
06130 ** interfaces.  However the values returned in *pCurrent and
06131 ** *pHighwater reflect the status of SQLite at different points in time
06132 ** and it is possible that another thread might change the parameter
06133 ** in between the times when *pCurrent and *pHighwater are written.
06134 **
06135 ** See also: [sqlite3_db_status()]
06136 */
06137 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
06138 
06139 
06140 /*
06141 ** CAPI3REF: Status Parameters
06142 ** KEYWORDS: {status parameters}
06143 **
06144 ** These integer constants designate various run-time status parameters
06145 ** that can be returned by [sqlite3_status()].
06146 **
06147 ** <dl>
06148 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
06149 ** <dd>This parameter is the current amount of memory checked out
06150 ** using [sqlite3_malloc()], either directly or indirectly.  The
06151 ** figure includes calls made to [sqlite3_malloc()] by the application
06152 ** and internal memory usage by the SQLite library.  Scratch memory
06153 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
06154 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
06155 ** this parameter.  The amount returned is the sum of the allocation
06156 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
06157 **
06158 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
06159 ** <dd>This parameter records the largest memory allocation request
06160 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
06161 ** internal equivalents).  Only the value returned in the
06162 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
06163 ** The value written into the *pCurrent parameter is undefined.</dd>)^
06164 **
06165 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
06166 ** <dd>This parameter records the number of separate memory allocations
06167 ** currently checked out.</dd>)^
06168 **
06169 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
06170 ** <dd>This parameter returns the number of pages used out of the
06171 ** [pagecache memory allocator] that was configured using 
06172 ** [SQLITE_CONFIG_PAGECACHE].  The
06173 ** value returned is in pages, not in bytes.</dd>)^
06174 **
06175 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
06176 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
06177 ** <dd>This parameter returns the number of bytes of page cache
06178 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
06179 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
06180 ** returned value includes allocations that overflowed because they
06181 ** where too large (they were larger than the "sz" parameter to
06182 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
06183 ** no space was left in the page cache.</dd>)^
06184 **
06185 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
06186 ** <dd>This parameter records the largest memory allocation request
06187 ** handed to [pagecache memory allocator].  Only the value returned in the
06188 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
06189 ** The value written into the *pCurrent parameter is undefined.</dd>)^
06190 **
06191 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
06192 ** <dd>This parameter returns the number of allocations used out of the
06193 ** [scratch memory allocator] configured using
06194 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
06195 ** in bytes.  Since a single thread may only have one scratch allocation
06196 ** outstanding at time, this parameter also reports the number of threads
06197 ** using scratch memory at the same time.</dd>)^
06198 **
06199 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
06200 ** <dd>This parameter returns the number of bytes of scratch memory
06201 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
06202 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
06203 ** returned include overflows because the requested allocation was too
06204 ** larger (that is, because the requested allocation was larger than the
06205 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
06206 ** slots were available.
06207 ** </dd>)^
06208 **
06209 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
06210 ** <dd>This parameter records the largest memory allocation request
06211 ** handed to [scratch memory allocator].  Only the value returned in the
06212 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
06213 ** The value written into the *pCurrent parameter is undefined.</dd>)^
06214 **
06215 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
06216 ** <dd>This parameter records the deepest parser stack.  It is only
06217 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
06218 ** </dl>
06219 **
06220 ** New status parameters may be added from time to time.
06221 */
06222 #define SQLITE_STATUS_MEMORY_USED          0
06223 #define SQLITE_STATUS_PAGECACHE_USED       1
06224 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
06225 #define SQLITE_STATUS_SCRATCH_USED         3
06226 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
06227 #define SQLITE_STATUS_MALLOC_SIZE          5
06228 #define SQLITE_STATUS_PARSER_STACK         6
06229 #define SQLITE_STATUS_PAGECACHE_SIZE       7
06230 #define SQLITE_STATUS_SCRATCH_SIZE         8
06231 #define SQLITE_STATUS_MALLOC_COUNT         9
06232 
06233 /*
06234 ** CAPI3REF: Database Connection Status
06235 **
06236 ** ^This interface is used to retrieve runtime status information 
06237 ** about a single [database connection].  ^The first argument is the
06238 ** database connection object to be interrogated.  ^The second argument
06239 ** is an integer constant, taken from the set of
06240 ** [SQLITE_DBSTATUS options], that
06241 ** determines the parameter to interrogate.  The set of 
06242 ** [SQLITE_DBSTATUS options] is likely
06243 ** to grow in future releases of SQLite.
06244 **
06245 ** ^The current value of the requested parameter is written into *pCur
06246 ** and the highest instantaneous value is written into *pHiwtr.  ^If
06247 ** the resetFlg is true, then the highest instantaneous value is
06248 ** reset back down to the current value.
06249 **
06250 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
06251 ** non-zero [error code] on failure.
06252 **
06253 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
06254 */
06255 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
06256 
06257 /*
06258 ** CAPI3REF: Status Parameters for database connections
06259 ** KEYWORDS: {SQLITE_DBSTATUS options}
06260 **
06261 ** These constants are the available integer "verbs" that can be passed as
06262 ** the second argument to the [sqlite3_db_status()] interface.
06263 **
06264 ** New verbs may be added in future releases of SQLite. Existing verbs
06265 ** might be discontinued. Applications should check the return code from
06266 ** [sqlite3_db_status()] to make sure that the call worked.
06267 ** The [sqlite3_db_status()] interface will return a non-zero error code
06268 ** if a discontinued or unsupported verb is invoked.
06269 **
06270 ** <dl>
06271 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
06272 ** <dd>This parameter returns the number of lookaside memory slots currently
06273 ** checked out.</dd>)^
06274 **
06275 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
06276 ** <dd>This parameter returns the number malloc attempts that were 
06277 ** satisfied using lookaside memory. Only the high-water value is meaningful;
06278 ** the current value is always zero.)^
06279 **
06280 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
06281 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
06282 ** <dd>This parameter returns the number malloc attempts that might have
06283 ** been satisfied using lookaside memory but failed due to the amount of
06284 ** memory requested being larger than the lookaside slot size.
06285 ** Only the high-water value is meaningful;
06286 ** the current value is always zero.)^
06287 **
06288 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
06289 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
06290 ** <dd>This parameter returns the number malloc attempts that might have
06291 ** been satisfied using lookaside memory but failed due to all lookaside
06292 ** memory already being in use.
06293 ** Only the high-water value is meaningful;
06294 ** the current value is always zero.)^
06295 **
06296 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
06297 ** <dd>This parameter returns the approximate number of of bytes of heap
06298 ** memory used by all pager caches associated with the database connection.)^
06299 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
06300 **
06301 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
06302 ** <dd>This parameter returns the approximate number of of bytes of heap
06303 ** memory used to store the schema for all databases associated
06304 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
06305 ** ^The full amount of memory used by the schemas is reported, even if the
06306 ** schema memory is shared with other database connections due to
06307 ** [shared cache mode] being enabled.
06308 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
06309 **
06310 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
06311 ** <dd>This parameter returns the approximate number of of bytes of heap
06312 ** and lookaside memory used by all prepared statements associated with
06313 ** the database connection.)^
06314 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
06315 ** </dd>
06316 **
06317 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
06318 ** <dd>This parameter returns the number of pager cache hits that have
06319 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
06320 ** is always 0.
06321 ** </dd>
06322 **
06323 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
06324 ** <dd>This parameter returns the number of pager cache misses that have
06325 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
06326 ** is always 0.
06327 ** </dd>
06328 **
06329 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
06330 ** <dd>This parameter returns the number of dirty cache entries that have
06331 ** been written to disk. Specifically, the number of pages written to the
06332 ** wal file in wal mode databases, or the number of pages written to the
06333 ** database file in rollback mode databases. Any pages written as part of
06334 ** transaction rollback or database recovery operations are not included.
06335 ** If an IO or other error occurs while writing a page to disk, the effect
06336 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
06337 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
06338 ** </dd>
06339 **
06340 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
06341 ** <dd>This parameter returns zero for the current value if and only if
06342 ** all foreign key constraints (deferred or immediate) have been
06343 ** resolved.)^  ^The highwater mark is always 0.
06344 ** </dd>
06345 ** </dl>
06346 */
06347 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
06348 #define SQLITE_DBSTATUS_CACHE_USED           1
06349 #define SQLITE_DBSTATUS_SCHEMA_USED          2
06350 #define SQLITE_DBSTATUS_STMT_USED            3
06351 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
06352 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
06353 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
06354 #define SQLITE_DBSTATUS_CACHE_HIT            7
06355 #define SQLITE_DBSTATUS_CACHE_MISS           8
06356 #define SQLITE_DBSTATUS_CACHE_WRITE          9
06357 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
06358 #define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
06359 
06360 
06361 /*
06362 ** CAPI3REF: Prepared Statement Status
06363 **
06364 ** ^(Each prepared statement maintains various
06365 ** [SQLITE_STMTSTATUS counters] that measure the number
06366 ** of times it has performed specific operations.)^  These counters can
06367 ** be used to monitor the performance characteristics of the prepared
06368 ** statements.  For example, if the number of table steps greatly exceeds
06369 ** the number of table searches or result rows, that would tend to indicate
06370 ** that the prepared statement is using a full table scan rather than
06371 ** an index.  
06372 **
06373 ** ^(This interface is used to retrieve and reset counter values from
06374 ** a [prepared statement].  The first argument is the prepared statement
06375 ** object to be interrogated.  The second argument
06376 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
06377 ** to be interrogated.)^
06378 ** ^The current value of the requested counter is returned.
06379 ** ^If the resetFlg is true, then the counter is reset to zero after this
06380 ** interface call returns.
06381 **
06382 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
06383 */
06384 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
06385 
06386 /*
06387 ** CAPI3REF: Status Parameters for prepared statements
06388 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
06389 **
06390 ** These preprocessor macros define integer codes that name counter
06391 ** values associated with the [sqlite3_stmt_status()] interface.
06392 ** The meanings of the various counters are as follows:
06393 **
06394 ** <dl>
06395 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
06396 ** <dd>^This is the number of times that SQLite has stepped forward in
06397 ** a table as part of a full table scan.  Large numbers for this counter
06398 ** may indicate opportunities for performance improvement through 
06399 ** careful use of indices.</dd>
06400 **
06401 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
06402 ** <dd>^This is the number of sort operations that have occurred.
06403 ** A non-zero value in this counter may indicate an opportunity to
06404 ** improvement performance through careful use of indices.</dd>
06405 **
06406 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
06407 ** <dd>^This is the number of rows inserted into transient indices that
06408 ** were created automatically in order to help joins run faster.
06409 ** A non-zero value in this counter may indicate an opportunity to
06410 ** improvement performance by adding permanent indices that do not
06411 ** need to be reinitialized each time the statement is run.</dd>
06412 **
06413 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
06414 ** <dd>^This is the number of virtual machine operations executed
06415 ** by the prepared statement if that number is less than or equal
06416 ** to 2147483647.  The number of virtual machine operations can be 
06417 ** used as a proxy for the total work done by the prepared statement.
06418 ** If the number of virtual machine operations exceeds 2147483647
06419 ** then the value returned by this statement status code is undefined.
06420 ** </dd>
06421 ** </dl>
06422 */
06423 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
06424 #define SQLITE_STMTSTATUS_SORT              2
06425 #define SQLITE_STMTSTATUS_AUTOINDEX         3
06426 #define SQLITE_STMTSTATUS_VM_STEP           4
06427 
06428 /*
06429 ** CAPI3REF: Custom Page Cache Object
06430 **
06431 ** The sqlite3_pcache type is opaque.  It is implemented by
06432 ** the pluggable module.  The SQLite core has no knowledge of
06433 ** its size or internal structure and never deals with the
06434 ** sqlite3_pcache object except by holding and passing pointers
06435 ** to the object.
06436 **
06437 ** See [sqlite3_pcache_methods2] for additional information.
06438 */
06439 typedef struct sqlite3_pcache sqlite3_pcache;
06440 
06441 /*
06442 ** CAPI3REF: Custom Page Cache Object
06443 **
06444 ** The sqlite3_pcache_page object represents a single page in the
06445 ** page cache.  The page cache will allocate instances of this
06446 ** object.  Various methods of the page cache use pointers to instances
06447 ** of this object as parameters or as their return value.
06448 **
06449 ** See [sqlite3_pcache_methods2] for additional information.
06450 */
06451 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
06452 struct sqlite3_pcache_page {
06453   void *pBuf;        /* The content of the page */
06454   void *pExtra;      /* Extra information associated with the page */
06455 };
06456 
06457 /*
06458 ** CAPI3REF: Application Defined Page Cache.
06459 ** KEYWORDS: {page cache}
06460 **
06461 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
06462 ** register an alternative page cache implementation by passing in an 
06463 ** instance of the sqlite3_pcache_methods2 structure.)^
06464 ** In many applications, most of the heap memory allocated by 
06465 ** SQLite is used for the page cache.
06466 ** By implementing a 
06467 ** custom page cache using this API, an application can better control
06468 ** the amount of memory consumed by SQLite, the way in which 
06469 ** that memory is allocated and released, and the policies used to 
06470 ** determine exactly which parts of a database file are cached and for 
06471 ** how long.
06472 **
06473 ** The alternative page cache mechanism is an
06474 ** extreme measure that is only needed by the most demanding applications.
06475 ** The built-in page cache is recommended for most uses.
06476 **
06477 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
06478 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
06479 ** the application may discard the parameter after the call to
06480 ** [sqlite3_config()] returns.)^
06481 **
06482 ** [[the xInit() page cache method]]
06483 ** ^(The xInit() method is called once for each effective 
06484 ** call to [sqlite3_initialize()])^
06485 ** (usually only once during the lifetime of the process). ^(The xInit()
06486 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
06487 ** The intent of the xInit() method is to set up global data structures 
06488 ** required by the custom page cache implementation. 
06489 ** ^(If the xInit() method is NULL, then the 
06490 ** built-in default page cache is used instead of the application defined
06491 ** page cache.)^
06492 **
06493 ** [[the xShutdown() page cache method]]
06494 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
06495 ** It can be used to clean up 
06496 ** any outstanding resources before process shutdown, if required.
06497 ** ^The xShutdown() method may be NULL.
06498 **
06499 ** ^SQLite automatically serializes calls to the xInit method,
06500 ** so the xInit method need not be threadsafe.  ^The
06501 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
06502 ** not need to be threadsafe either.  All other methods must be threadsafe
06503 ** in multithreaded applications.
06504 **
06505 ** ^SQLite will never invoke xInit() more than once without an intervening
06506 ** call to xShutdown().
06507 **
06508 ** [[the xCreate() page cache methods]]
06509 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
06510 ** SQLite will typically create one cache instance for each open database file,
06511 ** though this is not guaranteed. ^The
06512 ** first parameter, szPage, is the size in bytes of the pages that must
06513 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
06514 ** second parameter szExtra is a number of bytes of extra storage 
06515 ** associated with each page cache entry.  ^The szExtra parameter will
06516 ** a number less than 250.  SQLite will use the
06517 ** extra szExtra bytes on each page to store metadata about the underlying
06518 ** database page on disk.  The value passed into szExtra depends
06519 ** on the SQLite version, the target platform, and how SQLite was compiled.
06520 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
06521 ** created will be used to cache database pages of a file stored on disk, or
06522 ** false if it is used for an in-memory database. The cache implementation
06523 ** does not have to do anything special based with the value of bPurgeable;
06524 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
06525 ** never invoke xUnpin() except to deliberately delete a page.
06526 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
06527 ** false will always have the "discard" flag set to true.  
06528 ** ^Hence, a cache created with bPurgeable false will
06529 ** never contain any unpinned pages.
06530 **
06531 ** [[the xCachesize() page cache method]]
06532 ** ^(The xCachesize() method may be called at any time by SQLite to set the
06533 ** suggested maximum cache-size (number of pages stored by) the cache
06534 ** instance passed as the first argument. This is the value configured using
06535 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
06536 ** parameter, the implementation is not required to do anything with this
06537 ** value; it is advisory only.
06538 **
06539 ** [[the xPagecount() page cache methods]]
06540 ** The xPagecount() method must return the number of pages currently
06541 ** stored in the cache, both pinned and unpinned.
06542 ** 
06543 ** [[the xFetch() page cache methods]]
06544 ** The xFetch() method locates a page in the cache and returns a pointer to 
06545 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
06546 ** The pBuf element of the returned sqlite3_pcache_page object will be a
06547 ** pointer to a buffer of szPage bytes used to store the content of a 
06548 ** single database page.  The pExtra element of sqlite3_pcache_page will be
06549 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
06550 ** for each entry in the page cache.
06551 **
06552 ** The page to be fetched is determined by the key. ^The minimum key value
06553 ** is 1.  After it has been retrieved using xFetch, the page is considered
06554 ** to be "pinned".
06555 **
06556 ** If the requested page is already in the page cache, then the page cache
06557 ** implementation must return a pointer to the page buffer with its content
06558 ** intact.  If the requested page is not already in the cache, then the
06559 ** cache implementation should use the value of the createFlag
06560 ** parameter to help it determined what action to take:
06561 **
06562 ** <table border=1 width=85% align=center>
06563 ** <tr><th> createFlag <th> Behavior when page is not already in cache
06564 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
06565 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
06566 **                 Otherwise return NULL.
06567 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
06568 **                 NULL if allocating a new page is effectively impossible.
06569 ** </table>
06570 **
06571 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
06572 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
06573 ** failed.)^  In between the to xFetch() calls, SQLite may
06574 ** attempt to unpin one or more cache pages by spilling the content of
06575 ** pinned pages to disk and synching the operating system disk cache.
06576 **
06577 ** [[the xUnpin() page cache method]]
06578 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
06579 ** as its second argument.  If the third parameter, discard, is non-zero,
06580 ** then the page must be evicted from the cache.
06581 ** ^If the discard parameter is
06582 ** zero, then the page may be discarded or retained at the discretion of
06583 ** page cache implementation. ^The page cache implementation
06584 ** may choose to evict unpinned pages at any time.
06585 **
06586 ** The cache must not perform any reference counting. A single 
06587 ** call to xUnpin() unpins the page regardless of the number of prior calls 
06588 ** to xFetch().
06589 **
06590 ** [[the xRekey() page cache methods]]
06591 ** The xRekey() method is used to change the key value associated with the
06592 ** page passed as the second argument. If the cache
06593 ** previously contains an entry associated with newKey, it must be
06594 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
06595 ** to be pinned.
06596 **
06597 ** When SQLite calls the xTruncate() method, the cache must discard all
06598 ** existing cache entries with page numbers (keys) greater than or equal
06599 ** to the value of the iLimit parameter passed to xTruncate(). If any
06600 ** of these pages are pinned, they are implicitly unpinned, meaning that
06601 ** they can be safely discarded.
06602 **
06603 ** [[the xDestroy() page cache method]]
06604 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
06605 ** All resources associated with the specified cache should be freed. ^After
06606 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
06607 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
06608 ** functions.
06609 **
06610 ** [[the xShrink() page cache method]]
06611 ** ^SQLite invokes the xShrink() method when it wants the page cache to
06612 ** free up as much of heap memory as possible.  The page cache implementation
06613 ** is not obligated to free any memory, but well-behaved implementations should
06614 ** do their best.
06615 */
06616 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
06617 struct sqlite3_pcache_methods2 {
06618   int iVersion;
06619   void *pArg;
06620   int (*xInit)(void*);
06621   void (*xShutdown)(void*);
06622   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
06623   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
06624   int (*xPagecount)(sqlite3_pcache*);
06625   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
06626   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
06627   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
06628       unsigned oldKey, unsigned newKey);
06629   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
06630   void (*xDestroy)(sqlite3_pcache*);
06631   void (*xShrink)(sqlite3_pcache*);
06632 };
06633 
06634 /*
06635 ** This is the obsolete pcache_methods object that has now been replaced
06636 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
06637 ** retained in the header file for backwards compatibility only.
06638 */
06639 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
06640 struct sqlite3_pcache_methods {
06641   void *pArg;
06642   int (*xInit)(void*);
06643   void (*xShutdown)(void*);
06644   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
06645   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
06646   int (*xPagecount)(sqlite3_pcache*);
06647   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
06648   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
06649   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
06650   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
06651   void (*xDestroy)(sqlite3_pcache*);
06652 };
06653 
06654 
06655 /*
06656 ** CAPI3REF: Online Backup Object
06657 **
06658 ** The sqlite3_backup object records state information about an ongoing
06659 ** online backup operation.  ^The sqlite3_backup object is created by
06660 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
06661 ** [sqlite3_backup_finish()].
06662 **
06663 ** See Also: [Using the SQLite Online Backup API]
06664 */
06665 typedef struct sqlite3_backup sqlite3_backup;
06666 
06667 /*
06668 ** CAPI3REF: Online Backup API.
06669 **
06670 ** The backup API copies the content of one database into another.
06671 ** It is useful either for creating backups of databases or
06672 ** for copying in-memory databases to or from persistent files. 
06673 **
06674 ** See Also: [Using the SQLite Online Backup API]
06675 **
06676 ** ^SQLite holds a write transaction open on the destination database file
06677 ** for the duration of the backup operation.
06678 ** ^The source database is read-locked only while it is being read;
06679 ** it is not locked continuously for the entire backup operation.
06680 ** ^Thus, the backup may be performed on a live source database without
06681 ** preventing other database connections from
06682 ** reading or writing to the source database while the backup is underway.
06683 ** 
06684 ** ^(To perform a backup operation: 
06685 **   <ol>
06686 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
06687 **         backup, 
06688 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
06689 **         the data between the two databases, and finally
06690 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
06691 **         associated with the backup operation. 
06692 **   </ol>)^
06693 ** There should be exactly one call to sqlite3_backup_finish() for each
06694 ** successful call to sqlite3_backup_init().
06695 **
06696 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
06697 **
06698 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
06699 ** [database connection] associated with the destination database 
06700 ** and the database name, respectively.
06701 ** ^The database name is "main" for the main database, "temp" for the
06702 ** temporary database, or the name specified after the AS keyword in
06703 ** an [ATTACH] statement for an attached database.
06704 ** ^The S and M arguments passed to 
06705 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
06706 ** and database name of the source database, respectively.
06707 ** ^The source and destination [database connections] (parameters S and D)
06708 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
06709 ** an error.
06710 **
06711 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
06712 ** returned and an error code and error message are stored in the
06713 ** destination [database connection] D.
06714 ** ^The error code and message for the failed call to sqlite3_backup_init()
06715 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
06716 ** [sqlite3_errmsg16()] functions.
06717 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
06718 ** [sqlite3_backup] object.
06719 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
06720 ** sqlite3_backup_finish() functions to perform the specified backup 
06721 ** operation.
06722 **
06723 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
06724 **
06725 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
06726 ** the source and destination databases specified by [sqlite3_backup] object B.
06727 ** ^If N is negative, all remaining source pages are copied. 
06728 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
06729 ** are still more pages to be copied, then the function returns [SQLITE_OK].
06730 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
06731 ** from source to destination, then it returns [SQLITE_DONE].
06732 ** ^If an error occurs while running sqlite3_backup_step(B,N),
06733 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
06734 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
06735 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
06736 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
06737 **
06738 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
06739 ** <ol>
06740 ** <li> the destination database was opened read-only, or
06741 ** <li> the destination database is using write-ahead-log journaling
06742 ** and the destination and source page sizes differ, or
06743 ** <li> the destination database is an in-memory database and the
06744 ** destination and source page sizes differ.
06745 ** </ol>)^
06746 **
06747 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
06748 ** the [sqlite3_busy_handler | busy-handler function]
06749 ** is invoked (if one is specified). ^If the 
06750 ** busy-handler returns non-zero before the lock is available, then 
06751 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
06752 ** sqlite3_backup_step() can be retried later. ^If the source
06753 ** [database connection]
06754 ** is being used to write to the source database when sqlite3_backup_step()
06755 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
06756 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
06757 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
06758 ** [SQLITE_READONLY] is returned, then 
06759 ** there is no point in retrying the call to sqlite3_backup_step(). These 
06760 ** errors are considered fatal.)^  The application must accept 
06761 ** that the backup operation has failed and pass the backup operation handle 
06762 ** to the sqlite3_backup_finish() to release associated resources.
06763 **
06764 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
06765 ** on the destination file. ^The exclusive lock is not released until either 
06766 ** sqlite3_backup_finish() is called or the backup operation is complete 
06767 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
06768 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
06769 ** lasts for the duration of the sqlite3_backup_step() call.
06770 ** ^Because the source database is not locked between calls to
06771 ** sqlite3_backup_step(), the source database may be modified mid-way
06772 ** through the backup process.  ^If the source database is modified by an
06773 ** external process or via a database connection other than the one being
06774 ** used by the backup operation, then the backup will be automatically
06775 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
06776 ** database is modified by the using the same database connection as is used
06777 ** by the backup operation, then the backup database is automatically
06778 ** updated at the same time.
06779 **
06780 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
06781 **
06782 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
06783 ** application wishes to abandon the backup operation, the application
06784 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
06785 ** ^The sqlite3_backup_finish() interfaces releases all
06786 ** resources associated with the [sqlite3_backup] object. 
06787 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
06788 ** active write-transaction on the destination database is rolled back.
06789 ** The [sqlite3_backup] object is invalid
06790 ** and may not be used following a call to sqlite3_backup_finish().
06791 **
06792 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
06793 ** sqlite3_backup_step() errors occurred, regardless or whether or not
06794 ** sqlite3_backup_step() completed.
06795 ** ^If an out-of-memory condition or IO error occurred during any prior
06796 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
06797 ** sqlite3_backup_finish() returns the corresponding [error code].
06798 **
06799 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
06800 ** is not a permanent error and does not affect the return value of
06801 ** sqlite3_backup_finish().
06802 **
06803 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
06804 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
06805 **
06806 ** ^Each call to sqlite3_backup_step() sets two values inside
06807 ** the [sqlite3_backup] object: the number of pages still to be backed
06808 ** up and the total number of pages in the source database file.
06809 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
06810 ** retrieve these two values, respectively.
06811 **
06812 ** ^The values returned by these functions are only updated by
06813 ** sqlite3_backup_step(). ^If the source database is modified during a backup
06814 ** operation, then the values are not updated to account for any extra
06815 ** pages that need to be updated or the size of the source database file
06816 ** changing.
06817 **
06818 ** <b>Concurrent Usage of Database Handles</b>
06819 **
06820 ** ^The source [database connection] may be used by the application for other
06821 ** purposes while a backup operation is underway or being initialized.
06822 ** ^If SQLite is compiled and configured to support threadsafe database
06823 ** connections, then the source database connection may be used concurrently
06824 ** from within other threads.
06825 **
06826 ** However, the application must guarantee that the destination 
06827 ** [database connection] is not passed to any other API (by any thread) after 
06828 ** sqlite3_backup_init() is called and before the corresponding call to
06829 ** sqlite3_backup_finish().  SQLite does not currently check to see
06830 ** if the application incorrectly accesses the destination [database connection]
06831 ** and so no error code is reported, but the operations may malfunction
06832 ** nevertheless.  Use of the destination database connection while a
06833 ** backup is in progress might also also cause a mutex deadlock.
06834 **
06835 ** If running in [shared cache mode], the application must
06836 ** guarantee that the shared cache used by the destination database
06837 ** is not accessed while the backup is running. In practice this means
06838 ** that the application must guarantee that the disk file being 
06839 ** backed up to is not accessed by any connection within the process,
06840 ** not just the specific connection that was passed to sqlite3_backup_init().
06841 **
06842 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
06843 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
06844 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
06845 ** APIs are not strictly speaking threadsafe. If they are invoked at the
06846 ** same time as another thread is invoking sqlite3_backup_step() it is
06847 ** possible that they return invalid values.
06848 */
06849 SQLITE_API sqlite3_backup *sqlite3_backup_init(
06850   sqlite3 *pDest,                        /* Destination database handle */
06851   const char *zDestName,                 /* Destination database name */
06852   sqlite3 *pSource,                      /* Source database handle */
06853   const char *zSourceName                /* Source database name */
06854 );
06855 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
06856 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
06857 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
06858 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
06859 
06860 /*
06861 ** CAPI3REF: Unlock Notification
06862 **
06863 ** ^When running in shared-cache mode, a database operation may fail with
06864 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
06865 ** individual tables within the shared-cache cannot be obtained. See
06866 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
06867 ** ^This API may be used to register a callback that SQLite will invoke 
06868 ** when the connection currently holding the required lock relinquishes it.
06869 ** ^This API is only available if the library was compiled with the
06870 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
06871 **
06872 ** See Also: [Using the SQLite Unlock Notification Feature].
06873 **
06874 ** ^Shared-cache locks are released when a database connection concludes
06875 ** its current transaction, either by committing it or rolling it back. 
06876 **
06877 ** ^When a connection (known as the blocked connection) fails to obtain a
06878 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
06879 ** identity of the database connection (the blocking connection) that
06880 ** has locked the required resource is stored internally. ^After an 
06881 ** application receives an SQLITE_LOCKED error, it may call the
06882 ** sqlite3_unlock_notify() method with the blocked connection handle as 
06883 ** the first argument to register for a callback that will be invoked
06884 ** when the blocking connections current transaction is concluded. ^The
06885 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
06886 ** call that concludes the blocking connections transaction.
06887 **
06888 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
06889 ** there is a chance that the blocking connection will have already
06890 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
06891 ** If this happens, then the specified callback is invoked immediately,
06892 ** from within the call to sqlite3_unlock_notify().)^
06893 **
06894 ** ^If the blocked connection is attempting to obtain a write-lock on a
06895 ** shared-cache table, and more than one other connection currently holds
06896 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
06897 ** the other connections to use as the blocking connection.
06898 **
06899 ** ^(There may be at most one unlock-notify callback registered by a 
06900 ** blocked connection. If sqlite3_unlock_notify() is called when the
06901 ** blocked connection already has a registered unlock-notify callback,
06902 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
06903 ** called with a NULL pointer as its second argument, then any existing
06904 ** unlock-notify callback is canceled. ^The blocked connections 
06905 ** unlock-notify callback may also be canceled by closing the blocked
06906 ** connection using [sqlite3_close()].
06907 **
06908 ** The unlock-notify callback is not reentrant. If an application invokes
06909 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
06910 ** crash or deadlock may be the result.
06911 **
06912 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
06913 ** returns SQLITE_OK.
06914 **
06915 ** <b>Callback Invocation Details</b>
06916 **
06917 ** When an unlock-notify callback is registered, the application provides a 
06918 ** single void* pointer that is passed to the callback when it is invoked.
06919 ** However, the signature of the callback function allows SQLite to pass
06920 ** it an array of void* context pointers. The first argument passed to
06921 ** an unlock-notify callback is a pointer to an array of void* pointers,
06922 ** and the second is the number of entries in the array.
06923 **
06924 ** When a blocking connections transaction is concluded, there may be
06925 ** more than one blocked connection that has registered for an unlock-notify
06926 ** callback. ^If two or more such blocked connections have specified the
06927 ** same callback function, then instead of invoking the callback function
06928 ** multiple times, it is invoked once with the set of void* context pointers
06929 ** specified by the blocked connections bundled together into an array.
06930 ** This gives the application an opportunity to prioritize any actions 
06931 ** related to the set of unblocked database connections.
06932 **
06933 ** <b>Deadlock Detection</b>
06934 **
06935 ** Assuming that after registering for an unlock-notify callback a 
06936 ** database waits for the callback to be issued before taking any further
06937 ** action (a reasonable assumption), then using this API may cause the
06938 ** application to deadlock. For example, if connection X is waiting for
06939 ** connection Y's transaction to be concluded, and similarly connection
06940 ** Y is waiting on connection X's transaction, then neither connection
06941 ** will proceed and the system may remain deadlocked indefinitely.
06942 **
06943 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
06944 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
06945 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
06946 ** unlock-notify callback is registered. The system is said to be in
06947 ** a deadlocked state if connection A has registered for an unlock-notify
06948 ** callback on the conclusion of connection B's transaction, and connection
06949 ** B has itself registered for an unlock-notify callback when connection
06950 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
06951 ** the system is also considered to be deadlocked if connection B has
06952 ** registered for an unlock-notify callback on the conclusion of connection
06953 ** C's transaction, where connection C is waiting on connection A. ^Any
06954 ** number of levels of indirection are allowed.
06955 **
06956 ** <b>The "DROP TABLE" Exception</b>
06957 **
06958 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
06959 ** always appropriate to call sqlite3_unlock_notify(). There is however,
06960 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
06961 ** SQLite checks if there are any currently executing SELECT statements
06962 ** that belong to the same connection. If there are, SQLITE_LOCKED is
06963 ** returned. In this case there is no "blocking connection", so invoking
06964 ** sqlite3_unlock_notify() results in the unlock-notify callback being
06965 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
06966 ** or "DROP INDEX" query, an infinite loop might be the result.
06967 **
06968 ** One way around this problem is to check the extended error code returned
06969 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
06970 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
06971 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
06972 ** SQLITE_LOCKED.)^
06973 */
06974 SQLITE_API int sqlite3_unlock_notify(
06975   sqlite3 *pBlocked,                          /* Waiting connection */
06976   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
06977   void *pNotifyArg                            /* Argument to pass to xNotify */
06978 );
06979 
06980 
06981 /*
06982 ** CAPI3REF: String Comparison
06983 **
06984 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
06985 ** and extensions to compare the contents of two buffers containing UTF-8
06986 ** strings in a case-independent fashion, using the same definition of "case
06987 ** independence" that SQLite uses internally when comparing identifiers.
06988 */
06989 SQLITE_API int sqlite3_stricmp(const char *, const char *);
06990 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
06991 
06992 /*
06993 ** CAPI3REF: String Globbing
06994 *
06995 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
06996 ** the glob pattern P, and it returns non-zero if string X does not match
06997 ** the glob pattern P.  ^The definition of glob pattern matching used in
06998 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
06999 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
07000 ** sensitive.
07001 **
07002 ** Note that this routine returns zero on a match and non-zero if the strings
07003 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
07004 */
07005 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
07006 
07007 /*
07008 ** CAPI3REF: Error Logging Interface
07009 **
07010 ** ^The [sqlite3_log()] interface writes a message into the [error log]
07011 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
07012 ** ^If logging is enabled, the zFormat string and subsequent arguments are
07013 ** used with [sqlite3_snprintf()] to generate the final output string.
07014 **
07015 ** The sqlite3_log() interface is intended for use by extensions such as
07016 ** virtual tables, collating functions, and SQL functions.  While there is
07017 ** nothing to prevent an application from calling sqlite3_log(), doing so
07018 ** is considered bad form.
07019 **
07020 ** The zFormat string must not be NULL.
07021 **
07022 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
07023 ** will not use dynamically allocated memory.  The log message is stored in
07024 ** a fixed-length buffer on the stack.  If the log message is longer than
07025 ** a few hundred characters, it will be truncated to the length of the
07026 ** buffer.
07027 */
07028 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
07029 
07030 /*
07031 ** CAPI3REF: Write-Ahead Log Commit Hook
07032 **
07033 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
07034 ** will be invoked each time a database connection commits data to a
07035 ** [write-ahead log] (i.e. whenever a transaction is committed in
07036 ** [journal_mode | journal_mode=WAL mode]). 
07037 **
07038 ** ^The callback is invoked by SQLite after the commit has taken place and 
07039 ** the associated write-lock on the database released, so the implementation 
07040 ** may read, write or [checkpoint] the database as required.
07041 **
07042 ** ^The first parameter passed to the callback function when it is invoked
07043 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
07044 ** registering the callback. ^The second is a copy of the database handle.
07045 ** ^The third parameter is the name of the database that was written to -
07046 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
07047 ** is the number of pages currently in the write-ahead log file,
07048 ** including those that were just committed.
07049 **
07050 ** The callback function should normally return [SQLITE_OK].  ^If an error
07051 ** code is returned, that error will propagate back up through the
07052 ** SQLite code base to cause the statement that provoked the callback
07053 ** to report an error, though the commit will have still occurred. If the
07054 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
07055 ** that does not correspond to any valid SQLite error code, the results
07056 ** are undefined.
07057 **
07058 ** A single database handle may have at most a single write-ahead log callback 
07059 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
07060 ** previously registered write-ahead log callback. ^Note that the
07061 ** [sqlite3_wal_autocheckpoint()] interface and the
07062 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
07063 ** those overwrite any prior [sqlite3_wal_hook()] settings.
07064 */
07065 SQLITE_API void *sqlite3_wal_hook(
07066   sqlite3*, 
07067   int(*)(void *,sqlite3*,const char*,int),
07068   void*
07069 );
07070 
07071 /*
07072 ** CAPI3REF: Configure an auto-checkpoint
07073 **
07074 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
07075 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
07076 ** to automatically [checkpoint]
07077 ** after committing a transaction if there are N or
07078 ** more frames in the [write-ahead log] file.  ^Passing zero or 
07079 ** a negative value as the nFrame parameter disables automatic
07080 ** checkpoints entirely.
07081 **
07082 ** ^The callback registered by this function replaces any existing callback
07083 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
07084 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
07085 ** configured by this function.
07086 **
07087 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
07088 ** from SQL.
07089 **
07090 ** ^Every new [database connection] defaults to having the auto-checkpoint
07091 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
07092 ** pages.  The use of this interface
07093 ** is only necessary if the default setting is found to be suboptimal
07094 ** for a particular application.
07095 */
07096 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
07097 
07098 /*
07099 ** CAPI3REF: Checkpoint a database
07100 **
07101 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
07102 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
07103 ** empty string, then a checkpoint is run on all databases of
07104 ** connection D.  ^If the database connection D is not in
07105 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
07106 **
07107 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
07108 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
07109 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
07110 ** run whenever the WAL reaches a certain size threshold.
07111 **
07112 ** See also: [sqlite3_wal_checkpoint_v2()]
07113 */
07114 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
07115 
07116 /*
07117 ** CAPI3REF: Checkpoint a database
07118 **
07119 ** Run a checkpoint operation on WAL database zDb attached to database 
07120 ** handle db. The specific operation is determined by the value of the 
07121 ** eMode parameter:
07122 **
07123 ** <dl>
07124 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
07125 **   Checkpoint as many frames as possible without waiting for any database 
07126 **   readers or writers to finish. Sync the db file if all frames in the log
07127 **   are checkpointed. This mode is the same as calling 
07128 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
07129 **
07130 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
07131 **   This mode blocks (calls the busy-handler callback) until there is no
07132 **   database writer and all readers are reading from the most recent database
07133 **   snapshot. It then checkpoints all frames in the log file and syncs the
07134 **   database file. This call blocks database writers while it is running,
07135 **   but not database readers.
07136 **
07137 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
07138 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
07139 **   checkpointing the log file it blocks (calls the busy-handler callback)
07140 **   until all readers are reading from the database file only. This ensures 
07141 **   that the next client to write to the database file restarts the log file 
07142 **   from the beginning. This call blocks database writers while it is running,
07143 **   but not database readers.
07144 ** </dl>
07145 **
07146 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
07147 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
07148 ** the total number of checkpointed frames (including any that were already
07149 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
07150 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
07151 ** If no values are available because of an error, they are both set to -1
07152 ** before returning to communicate this to the caller.
07153 **
07154 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
07155 ** any other process is running a checkpoint operation at the same time, the 
07156 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
07157 ** busy-handler configured, it will not be invoked in this case.
07158 **
07159 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
07160 ** "writer" lock on the database file. If the writer lock cannot be obtained
07161 ** immediately, and a busy-handler is configured, it is invoked and the writer
07162 ** lock retried until either the busy-handler returns 0 or the lock is
07163 ** successfully obtained. The busy-handler is also invoked while waiting for
07164 ** database readers as described above. If the busy-handler returns 0 before
07165 ** the writer lock is obtained or while waiting for database readers, the
07166 ** checkpoint operation proceeds from that point in the same way as 
07167 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
07168 ** without blocking any further. SQLITE_BUSY is returned in this case.
07169 **
07170 ** If parameter zDb is NULL or points to a zero length string, then the
07171 ** specified operation is attempted on all WAL databases. In this case the
07172 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
07173 ** an SQLITE_BUSY error is encountered when processing one or more of the 
07174 ** attached WAL databases, the operation is still attempted on any remaining 
07175 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
07176 ** error occurs while processing an attached database, processing is abandoned 
07177 ** and the error code returned to the caller immediately. If no error 
07178 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
07179 ** databases, SQLITE_OK is returned.
07180 **
07181 ** If database zDb is the name of an attached database that is not in WAL
07182 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
07183 ** zDb is not NULL (or a zero length string) and is not the name of any
07184 ** attached database, SQLITE_ERROR is returned to the caller.
07185 */
07186 SQLITE_API int sqlite3_wal_checkpoint_v2(
07187   sqlite3 *db,                    /* Database handle */
07188   const char *zDb,                /* Name of attached database (or NULL) */
07189   int eMode,                      /* SQLITE_CHECKPOINT_* value */
07190   int *pnLog,                     /* OUT: Size of WAL log in frames */
07191   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
07192 );
07193 
07194 /*
07195 ** CAPI3REF: Checkpoint operation parameters
07196 **
07197 ** These constants can be used as the 3rd parameter to
07198 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
07199 ** documentation for additional information about the meaning and use of
07200 ** each of these values.
07201 */
07202 #define SQLITE_CHECKPOINT_PASSIVE 0
07203 #define SQLITE_CHECKPOINT_FULL    1
07204 #define SQLITE_CHECKPOINT_RESTART 2
07205 
07206 /*
07207 ** CAPI3REF: Virtual Table Interface Configuration
07208 **
07209 ** This function may be called by either the [xConnect] or [xCreate] method
07210 ** of a [virtual table] implementation to configure
07211 ** various facets of the virtual table interface.
07212 **
07213 ** If this interface is invoked outside the context of an xConnect or
07214 ** xCreate virtual table method then the behavior is undefined.
07215 **
07216 ** At present, there is only one option that may be configured using
07217 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
07218 ** may be added in the future.
07219 */
07220 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
07221 
07222 /*
07223 ** CAPI3REF: Virtual Table Configuration Options
07224 **
07225 ** These macros define the various options to the
07226 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
07227 ** can use to customize and optimize their behavior.
07228 **
07229 ** <dl>
07230 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
07231 ** <dd>Calls of the form
07232 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
07233 ** where X is an integer.  If X is zero, then the [virtual table] whose
07234 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
07235 ** support constraints.  In this configuration (which is the default) if
07236 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
07237 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
07238 ** specified as part of the users SQL statement, regardless of the actual
07239 ** ON CONFLICT mode specified.
07240 **
07241 ** If X is non-zero, then the virtual table implementation guarantees
07242 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
07243 ** any modifications to internal or persistent data structures have been made.
07244 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
07245 ** is able to roll back a statement or database transaction, and abandon
07246 ** or continue processing the current SQL statement as appropriate. 
07247 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
07248 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
07249 ** had been ABORT.
07250 **
07251 ** Virtual table implementations that are required to handle OR REPLACE
07252 ** must do so within the [xUpdate] method. If a call to the 
07253 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
07254 ** CONFLICT policy is REPLACE, the virtual table implementation should 
07255 ** silently replace the appropriate rows within the xUpdate callback and
07256 ** return SQLITE_OK. Or, if this is not possible, it may return
07257 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
07258 ** constraint handling.
07259 ** </dl>
07260 */
07261 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
07262 
07263 /*
07264 ** CAPI3REF: Determine The Virtual Table Conflict Policy
07265 **
07266 ** This function may only be called from within a call to the [xUpdate] method
07267 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
07268 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
07269 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
07270 ** of the SQL statement that triggered the call to the [xUpdate] method of the
07271 ** [virtual table].
07272 */
07273 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
07274 
07275 /*
07276 ** CAPI3REF: Conflict resolution modes
07277 **
07278 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
07279 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
07280 ** is for the SQL statement being evaluated.
07281 **
07282 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
07283 ** return value from the [sqlite3_set_authorizer()] callback and that
07284 ** [SQLITE_ABORT] is also a [result code].
07285 */
07286 #define SQLITE_ROLLBACK 1
07287 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
07288 #define SQLITE_FAIL     3
07289 /* #define SQLITE_ABORT 4  // Also an error code */
07290 #define SQLITE_REPLACE  5
07291 
07292 
07293 
07294 /*
07295 ** Undo the hack that converts floating point types to integer for
07296 ** builds on processors without floating point support.
07297 */
07298 #ifdef SQLITE_OMIT_FLOATING_POINT
07299 # undef double
07300 #endif
07301 
07302 #if 0
07303 }  /* End of the 'extern "C"' block */
07304 #endif
07305 #endif /* _SQLITE3_H_ */
07306 
07307 /*
07308 ** 2010 August 30
07309 **
07310 ** The author disclaims copyright to this source code.  In place of
07311 ** a legal notice, here is a blessing:
07312 **
07313 **    May you do good and not evil.
07314 **    May you find forgiveness for yourself and forgive others.
07315 **    May you share freely, never taking more than you give.
07316 **
07317 *************************************************************************
07318 */
07319 
07320 #ifndef _SQLITE3RTREE_H_
07321 #define _SQLITE3RTREE_H_
07322 
07323 
07324 #if 0
07325 extern "C" {
07326 #endif
07327 
07328 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
07329 
07330 /*
07331 ** Register a geometry callback named zGeom that can be used as part of an
07332 ** R-Tree geometry query as follows:
07333 **
07334 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
07335 */
07336 SQLITE_API int sqlite3_rtree_geometry_callback(
07337   sqlite3 *db,
07338   const char *zGeom,
07339 #ifdef SQLITE_RTREE_INT_ONLY
07340   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
07341 #else
07342   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
07343 #endif
07344   void *pContext
07345 );
07346 
07347 
07348 /*
07349 ** A pointer to a structure of the following type is passed as the first
07350 ** argument to callbacks registered using rtree_geometry_callback().
07351 */
07352 struct sqlite3_rtree_geometry {
07353   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
07354   int nParam;                     /* Size of array aParam[] */
07355   double *aParam;                 /* Parameters passed to SQL geom function */
07356   void *pUser;                    /* Callback implementation user data */
07357   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
07358 };
07359 
07360 
07361 #if 0
07362 }  /* end of the 'extern "C"' block */
07363 #endif
07364 
07365 #endif  /* ifndef _SQLITE3RTREE_H_ */
07366 
07367 
07368 /************** End of sqlite3.h *********************************************/
07369 /************** Begin file sqliteInt.h ***************************************/
07370 /*
07371 ** 2001 September 15
07372 **
07373 ** The author disclaims copyright to this source code.  In place of
07374 ** a legal notice, here is a blessing:
07375 **
07376 **    May you do good and not evil.
07377 **    May you find forgiveness for yourself and forgive others.
07378 **    May you share freely, never taking more than you give.
07379 **
07380 *************************************************************************
07381 ** Internal interface definitions for SQLite.
07382 **
07383 */
07384 #ifndef _SQLITEINT_H_
07385 #define _SQLITEINT_H_
07386 
07387 /*
07388 ** These #defines should enable >2GB file support on POSIX if the
07389 ** underlying operating system supports it.  If the OS lacks
07390 ** large file support, or if the OS is windows, these should be no-ops.
07391 **
07392 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
07393 ** system #includes.  Hence, this block of code must be the very first
07394 ** code in all source files.
07395 **
07396 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
07397 ** on the compiler command line.  This is necessary if you are compiling
07398 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
07399 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
07400 ** without this option, LFS is enable.  But LFS does not exist in the kernel
07401 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
07402 ** portability you should omit LFS.
07403 **
07404 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
07405 */
07406 #ifndef SQLITE_DISABLE_LFS
07407 # define _LARGE_FILE       1
07408 # ifndef _FILE_OFFSET_BITS
07409 #   define _FILE_OFFSET_BITS 64
07410 # endif
07411 # define _LARGEFILE_SOURCE 1
07412 #endif
07413 
07414 /*
07415 ** Include the configuration header output by 'configure' if we're using the
07416 ** autoconf-based build
07417 */
07418 #ifdef _HAVE_SQLITE_CONFIG_H
07419 #include "config.h"
07420 #endif
07421 
07422 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
07423 /************** Begin file sqliteLimit.h *************************************/
07424 /*
07425 ** 2007 May 7
07426 **
07427 ** The author disclaims copyright to this source code.  In place of
07428 ** a legal notice, here is a blessing:
07429 **
07430 **    May you do good and not evil.
07431 **    May you find forgiveness for yourself and forgive others.
07432 **    May you share freely, never taking more than you give.
07433 **
07434 *************************************************************************
07435 ** 
07436 ** This file defines various limits of what SQLite can process.
07437 */
07438 
07439 /*
07440 ** The maximum length of a TEXT or BLOB in bytes.   This also
07441 ** limits the size of a row in a table or index.
07442 **
07443 ** The hard limit is the ability of a 32-bit signed integer
07444 ** to count the size: 2^31-1 or 2147483647.
07445 */
07446 #ifndef SQLITE_MAX_LENGTH
07447 # define SQLITE_MAX_LENGTH 1000000000
07448 #endif
07449 
07450 /*
07451 ** This is the maximum number of
07452 **
07453 **    * Columns in a table
07454 **    * Columns in an index
07455 **    * Columns in a view
07456 **    * Terms in the SET clause of an UPDATE statement
07457 **    * Terms in the result set of a SELECT statement
07458 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
07459 **    * Terms in the VALUES clause of an INSERT statement
07460 **
07461 ** The hard upper limit here is 32676.  Most database people will
07462 ** tell you that in a well-normalized database, you usually should
07463 ** not have more than a dozen or so columns in any table.  And if
07464 ** that is the case, there is no point in having more than a few
07465 ** dozen values in any of the other situations described above.
07466 */
07467 #ifndef SQLITE_MAX_COLUMN
07468 # define SQLITE_MAX_COLUMN 2000
07469 #endif
07470 
07471 /*
07472 ** The maximum length of a single SQL statement in bytes.
07473 **
07474 ** It used to be the case that setting this value to zero would
07475 ** turn the limit off.  That is no longer true.  It is not possible
07476 ** to turn this limit off.
07477 */
07478 #ifndef SQLITE_MAX_SQL_LENGTH
07479 # define SQLITE_MAX_SQL_LENGTH 1000000000
07480 #endif
07481 
07482 /*
07483 ** The maximum depth of an expression tree. This is limited to 
07484 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
07485 ** want to place more severe limits on the complexity of an 
07486 ** expression.
07487 **
07488 ** A value of 0 used to mean that the limit was not enforced.
07489 ** But that is no longer true.  The limit is now strictly enforced
07490 ** at all times.
07491 */
07492 #ifndef SQLITE_MAX_EXPR_DEPTH
07493 # define SQLITE_MAX_EXPR_DEPTH 1000
07494 #endif
07495 
07496 /*
07497 ** The maximum number of terms in a compound SELECT statement.
07498 ** The code generator for compound SELECT statements does one
07499 ** level of recursion for each term.  A stack overflow can result
07500 ** if the number of terms is too large.  In practice, most SQL
07501 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
07502 ** any limit on the number of terms in a compount SELECT.
07503 */
07504 #ifndef SQLITE_MAX_COMPOUND_SELECT
07505 # define SQLITE_MAX_COMPOUND_SELECT 500
07506 #endif
07507 
07508 /*
07509 ** The maximum number of opcodes in a VDBE program.
07510 ** Not currently enforced.
07511 */
07512 #ifndef SQLITE_MAX_VDBE_OP
07513 # define SQLITE_MAX_VDBE_OP 25000
07514 #endif
07515 
07516 /*
07517 ** The maximum number of arguments to an SQL function.
07518 */
07519 #ifndef SQLITE_MAX_FUNCTION_ARG
07520 # define SQLITE_MAX_FUNCTION_ARG 127
07521 #endif
07522 
07523 /*
07524 ** The maximum number of in-memory pages to use for the main database
07525 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
07526 */
07527 #ifndef SQLITE_DEFAULT_CACHE_SIZE
07528 # define SQLITE_DEFAULT_CACHE_SIZE  2000
07529 #endif
07530 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
07531 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
07532 #endif
07533 
07534 /*
07535 ** The default number of frames to accumulate in the log file before
07536 ** checkpointing the database in WAL mode.
07537 */
07538 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
07539 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
07540 #endif
07541 
07542 /*
07543 ** The maximum number of attached databases.  This must be between 0
07544 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
07545 ** is used internally to track attached databases.
07546 */
07547 #ifndef SQLITE_MAX_ATTACHED
07548 # define SQLITE_MAX_ATTACHED 10
07549 #endif
07550 
07551 
07552 /*
07553 ** The maximum value of a ?nnn wildcard that the parser will accept.
07554 */
07555 #ifndef SQLITE_MAX_VARIABLE_NUMBER
07556 # define SQLITE_MAX_VARIABLE_NUMBER 999
07557 #endif
07558 
07559 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
07560 ** imposed by the use of 16-bit offsets within each page.
07561 **
07562 ** Earlier versions of SQLite allowed the user to change this value at
07563 ** compile time. This is no longer permitted, on the grounds that it creates
07564 ** a library that is technically incompatible with an SQLite library 
07565 ** compiled with a different limit. If a process operating on a database 
07566 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
07567 ** compiled with the default page-size limit will not be able to rollback 
07568 ** the aborted transaction. This could lead to database corruption.
07569 */
07570 #ifdef SQLITE_MAX_PAGE_SIZE
07571 # undef SQLITE_MAX_PAGE_SIZE
07572 #endif
07573 #define SQLITE_MAX_PAGE_SIZE 65536
07574 
07575 
07576 /*
07577 ** The default size of a database page.
07578 */
07579 #ifndef SQLITE_DEFAULT_PAGE_SIZE
07580 # define SQLITE_DEFAULT_PAGE_SIZE 1024
07581 #endif
07582 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
07583 # undef SQLITE_DEFAULT_PAGE_SIZE
07584 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
07585 #endif
07586 
07587 /*
07588 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
07589 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
07590 ** device characteristics (sector-size and atomic write() support),
07591 ** SQLite may choose a larger value. This constant is the maximum value
07592 ** SQLite will choose on its own.
07593 */
07594 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
07595 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
07596 #endif
07597 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
07598 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
07599 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
07600 #endif
07601 
07602 
07603 /*
07604 ** Maximum number of pages in one database file.
07605 **
07606 ** This is really just the default value for the max_page_count pragma.
07607 ** This value can be lowered (or raised) at run-time using that the
07608 ** max_page_count macro.
07609 */
07610 #ifndef SQLITE_MAX_PAGE_COUNT
07611 # define SQLITE_MAX_PAGE_COUNT 1073741823
07612 #endif
07613 
07614 /*
07615 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
07616 ** operator.
07617 */
07618 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
07619 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
07620 #endif
07621 
07622 /*
07623 ** Maximum depth of recursion for triggers.
07624 **
07625 ** A value of 1 means that a trigger program will not be able to itself
07626 ** fire any triggers. A value of 0 means that no trigger programs at all 
07627 ** may be executed.
07628 */
07629 #ifndef SQLITE_MAX_TRIGGER_DEPTH
07630 # define SQLITE_MAX_TRIGGER_DEPTH 1000
07631 #endif
07632 
07633 /************** End of sqliteLimit.h *****************************************/
07634 /************** Continuing where we left off in sqliteInt.h ******************/
07635 
07636 /* Disable nuisance warnings on Borland compilers */
07637 #if defined(__BORLANDC__)
07638 #pragma warn -rch /* unreachable code */
07639 #pragma warn -ccc /* Condition is always true or false */
07640 #pragma warn -aus /* Assigned value is never used */
07641 #pragma warn -csu /* Comparing signed and unsigned */
07642 #pragma warn -spa /* Suspicious pointer arithmetic */
07643 #endif
07644 
07645 /* Needed for various definitions... */
07646 #ifndef _GNU_SOURCE
07647 # define _GNU_SOURCE
07648 #endif
07649 
07650 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
07651 # define _BSD_SOURCE
07652 #endif
07653 
07654 /*
07655 ** Include standard header files as necessary
07656 */
07657 #ifdef HAVE_STDINT_H
07658 #include <stdint.h>
07659 #endif
07660 #ifdef HAVE_INTTYPES_H
07661 #include <inttypes.h>
07662 #endif
07663 
07664 /*
07665 ** The following macros are used to cast pointers to integers and
07666 ** integers to pointers.  The way you do this varies from one compiler
07667 ** to the next, so we have developed the following set of #if statements
07668 ** to generate appropriate macros for a wide range of compilers.
07669 **
07670 ** The correct "ANSI" way to do this is to use the intptr_t type. 
07671 ** Unfortunately, that typedef is not available on all compilers, or
07672 ** if it is available, it requires an #include of specific headers
07673 ** that vary from one machine to the next.
07674 **
07675 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
07676 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
07677 ** So we have to define the macros in different ways depending on the
07678 ** compiler.
07679 */
07680 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
07681 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
07682 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
07683 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
07684 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
07685 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
07686 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
07687 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
07688 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
07689 #else                          /* Generates a warning - but it always works */
07690 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
07691 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
07692 #endif
07693 
07694 /*
07695 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
07696 ** 0 means mutexes are permanently disable and the library is never
07697 ** threadsafe.  1 means the library is serialized which is the highest
07698 ** level of threadsafety.  2 means the library is multithreaded - multiple
07699 ** threads can use SQLite as long as no two threads try to use the same
07700 ** database connection at the same time.
07701 **
07702 ** Older versions of SQLite used an optional THREADSAFE macro.
07703 ** We support that for legacy.
07704 */
07705 #if !defined(SQLITE_THREADSAFE)
07706 # if defined(THREADSAFE)
07707 #   define SQLITE_THREADSAFE THREADSAFE
07708 # else
07709 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
07710 # endif
07711 #endif
07712 
07713 /*
07714 ** Powersafe overwrite is on by default.  But can be turned off using
07715 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
07716 */
07717 #ifndef SQLITE_POWERSAFE_OVERWRITE
07718 # define SQLITE_POWERSAFE_OVERWRITE 1
07719 #endif
07720 
07721 /*
07722 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
07723 ** It determines whether or not the features related to 
07724 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
07725 ** be overridden at runtime using the sqlite3_config() API.
07726 */
07727 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
07728 # define SQLITE_DEFAULT_MEMSTATUS 1
07729 #endif
07730 
07731 /*
07732 ** Exactly one of the following macros must be defined in order to
07733 ** specify which memory allocation subsystem to use.
07734 **
07735 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
07736 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
07737 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
07738 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
07739 **
07740 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
07741 ** assert() macro is enabled, each call into the Win32 native heap subsystem
07742 ** will cause HeapValidate to be called.  If heap validation should fail, an
07743 ** assertion will be triggered.
07744 **
07745 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
07746 ** the default.
07747 */
07748 #if defined(SQLITE_SYSTEM_MALLOC) \
07749   + defined(SQLITE_WIN32_MALLOC) \
07750   + defined(SQLITE_ZERO_MALLOC) \
07751   + defined(SQLITE_MEMDEBUG)>1
07752 # error "Two or more of the following compile-time configuration options\
07753  are defined but at most one is allowed:\
07754  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
07755  SQLITE_ZERO_MALLOC"
07756 #endif
07757 #if defined(SQLITE_SYSTEM_MALLOC) \
07758   + defined(SQLITE_WIN32_MALLOC) \
07759   + defined(SQLITE_ZERO_MALLOC) \
07760   + defined(SQLITE_MEMDEBUG)==0
07761 # define SQLITE_SYSTEM_MALLOC 1
07762 #endif
07763 
07764 /*
07765 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
07766 ** sizes of memory allocations below this value where possible.
07767 */
07768 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
07769 # define SQLITE_MALLOC_SOFT_LIMIT 1024
07770 #endif
07771 
07772 /*
07773 ** We need to define _XOPEN_SOURCE as follows in order to enable
07774 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
07775 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
07776 ** it.
07777 */
07778 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
07779 #  define _XOPEN_SOURCE 600
07780 #endif
07781 
07782 /*
07783 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
07784 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
07785 ** make it true by defining or undefining NDEBUG.
07786 **
07787 ** Setting NDEBUG makes the code smaller and faster by disabling the
07788 ** assert() statements in the code.  So we want the default action
07789 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
07790 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
07791 ** feature.
07792 */
07793 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
07794 # define NDEBUG 1
07795 #endif
07796 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
07797 # undef NDEBUG
07798 #endif
07799 
07800 /*
07801 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
07802 */
07803 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
07804 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
07805 #endif
07806 
07807 /*
07808 ** The testcase() macro is used to aid in coverage testing.  When 
07809 ** doing coverage testing, the condition inside the argument to
07810 ** testcase() must be evaluated both true and false in order to
07811 ** get full branch coverage.  The testcase() macro is inserted
07812 ** to help ensure adequate test coverage in places where simple
07813 ** condition/decision coverage is inadequate.  For example, testcase()
07814 ** can be used to make sure boundary values are tested.  For
07815 ** bitmask tests, testcase() can be used to make sure each bit
07816 ** is significant and used at least once.  On switch statements
07817 ** where multiple cases go to the same block of code, testcase()
07818 ** can insure that all cases are evaluated.
07819 **
07820 */
07821 #ifdef SQLITE_COVERAGE_TEST
07822 SQLITE_PRIVATE   void sqlite3Coverage(int);
07823 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
07824 #else
07825 # define testcase(X)
07826 #endif
07827 
07828 /*
07829 ** The TESTONLY macro is used to enclose variable declarations or
07830 ** other bits of code that are needed to support the arguments
07831 ** within testcase() and assert() macros.
07832 */
07833 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
07834 # define TESTONLY(X)  X
07835 #else
07836 # define TESTONLY(X)
07837 #endif
07838 
07839 /*
07840 ** Sometimes we need a small amount of code such as a variable initialization
07841 ** to setup for a later assert() statement.  We do not want this code to
07842 ** appear when assert() is disabled.  The following macro is therefore
07843 ** used to contain that setup code.  The "VVA" acronym stands for
07844 ** "Verification, Validation, and Accreditation".  In other words, the
07845 ** code within VVA_ONLY() will only run during verification processes.
07846 */
07847 #ifndef NDEBUG
07848 # define VVA_ONLY(X)  X
07849 #else
07850 # define VVA_ONLY(X)
07851 #endif
07852 
07853 /*
07854 ** The ALWAYS and NEVER macros surround boolean expressions which 
07855 ** are intended to always be true or false, respectively.  Such
07856 ** expressions could be omitted from the code completely.  But they
07857 ** are included in a few cases in order to enhance the resilience
07858 ** of SQLite to unexpected behavior - to make the code "self-healing"
07859 ** or "ductile" rather than being "brittle" and crashing at the first
07860 ** hint of unplanned behavior.
07861 **
07862 ** In other words, ALWAYS and NEVER are added for defensive code.
07863 **
07864 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
07865 ** be true and false so that the unreachable code they specify will
07866 ** not be counted as untested code.
07867 */
07868 #if defined(SQLITE_COVERAGE_TEST)
07869 # define ALWAYS(X)      (1)
07870 # define NEVER(X)       (0)
07871 #elif !defined(NDEBUG)
07872 # define ALWAYS(X)      ((X)?1:(assert(0),0))
07873 # define NEVER(X)       ((X)?(assert(0),1):0)
07874 #else
07875 # define ALWAYS(X)      (X)
07876 # define NEVER(X)       (X)
07877 #endif
07878 
07879 /*
07880 ** Return true (non-zero) if the input is a integer that is too large
07881 ** to fit in 32-bits.  This macro is used inside of various testcase()
07882 ** macros to verify that we have tested SQLite for large-file support.
07883 */
07884 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
07885 
07886 /*
07887 ** The macro unlikely() is a hint that surrounds a boolean
07888 ** expression that is usually false.  Macro likely() surrounds
07889 ** a boolean expression that is usually true.  These hints could,
07890 ** in theory, be used by the compiler to generate better code, but
07891 ** currently they are just comments for human readers.
07892 */
07893 #define likely(X)    (X)
07894 #define unlikely(X)  (X)
07895 
07896 /************** Include hash.h in the middle of sqliteInt.h ******************/
07897 /************** Begin file hash.h ********************************************/
07898 /*
07899 ** 2001 September 22
07900 **
07901 ** The author disclaims copyright to this source code.  In place of
07902 ** a legal notice, here is a blessing:
07903 **
07904 **    May you do good and not evil.
07905 **    May you find forgiveness for yourself and forgive others.
07906 **    May you share freely, never taking more than you give.
07907 **
07908 *************************************************************************
07909 ** This is the header file for the generic hash-table implementation
07910 ** used in SQLite.
07911 */
07912 #ifndef _SQLITE_HASH_H_
07913 #define _SQLITE_HASH_H_
07914 
07915 /* Forward declarations of structures. */
07916 typedef struct Hash Hash;
07917 typedef struct HashElem HashElem;
07918 
07919 /* A complete hash table is an instance of the following structure.
07920 ** The internals of this structure are intended to be opaque -- client
07921 ** code should not attempt to access or modify the fields of this structure
07922 ** directly.  Change this structure only by using the routines below.
07923 ** However, some of the "procedures" and "functions" for modifying and
07924 ** accessing this structure are really macros, so we can't really make
07925 ** this structure opaque.
07926 **
07927 ** All elements of the hash table are on a single doubly-linked list.
07928 ** Hash.first points to the head of this list.
07929 **
07930 ** There are Hash.htsize buckets.  Each bucket points to a spot in
07931 ** the global doubly-linked list.  The contents of the bucket are the
07932 ** element pointed to plus the next _ht.count-1 elements in the list.
07933 **
07934 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
07935 ** by a linear search of the global list.  For small tables, the 
07936 ** Hash.ht table is never allocated because if there are few elements
07937 ** in the table, it is faster to do a linear search than to manage
07938 ** the hash table.
07939 */
07940 struct Hash {
07941   unsigned int htsize;      /* Number of buckets in the hash table */
07942   unsigned int count;       /* Number of entries in this table */
07943   HashElem *first;          /* The first element of the array */
07944   struct _ht {              /* the hash table */
07945     int count;                 /* Number of entries with this hash */
07946     HashElem *chain;           /* Pointer to first entry with this hash */
07947   } *ht;
07948 };
07949 
07950 /* Each element in the hash table is an instance of the following 
07951 ** structure.  All elements are stored on a single doubly-linked list.
07952 **
07953 ** Again, this structure is intended to be opaque, but it can't really
07954 ** be opaque because it is used by macros.
07955 */
07956 struct HashElem {
07957   HashElem *next, *prev;       /* Next and previous elements in the table */
07958   void *data;                  /* Data associated with this element */
07959   const char *pKey; int nKey;  /* Key associated with this element */
07960 };
07961 
07962 /*
07963 ** Access routines.  To delete, insert a NULL pointer.
07964 */
07965 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
07966 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
07967 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
07968 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
07969 
07970 /*
07971 ** Macros for looping over all elements of a hash table.  The idiom is
07972 ** like this:
07973 **
07974 **   Hash h;
07975 **   HashElem *p;
07976 **   ...
07977 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
07978 **     SomeStructure *pData = sqliteHashData(p);
07979 **     // do something with pData
07980 **   }
07981 */
07982 #define sqliteHashFirst(H)  ((H)->first)
07983 #define sqliteHashNext(E)   ((E)->next)
07984 #define sqliteHashData(E)   ((E)->data)
07985 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
07986 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
07987 
07988 /*
07989 ** Number of entries in a hash table
07990 */
07991 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
07992 
07993 #endif /* _SQLITE_HASH_H_ */
07994 
07995 /************** End of hash.h ************************************************/
07996 /************** Continuing where we left off in sqliteInt.h ******************/
07997 /************** Include parse.h in the middle of sqliteInt.h *****************/
07998 /************** Begin file parse.h *******************************************/
07999 #define TK_SEMI                            1
08000 #define TK_EXPLAIN                         2
08001 #define TK_QUERY                           3
08002 #define TK_PLAN                            4
08003 #define TK_BEGIN                           5
08004 #define TK_TRANSACTION                     6
08005 #define TK_DEFERRED                        7
08006 #define TK_IMMEDIATE                       8
08007 #define TK_EXCLUSIVE                       9
08008 #define TK_COMMIT                         10
08009 #define TK_END                            11
08010 #define TK_ROLLBACK                       12
08011 #define TK_SAVEPOINT                      13
08012 #define TK_RELEASE                        14
08013 #define TK_TO                             15
08014 #define TK_TABLE                          16
08015 #define TK_CREATE                         17
08016 #define TK_IF                             18
08017 #define TK_NOT                            19
08018 #define TK_EXISTS                         20
08019 #define TK_TEMP                           21
08020 #define TK_LP                             22
08021 #define TK_RP                             23
08022 #define TK_AS                             24
08023 #define TK_WITHOUT                        25
08024 #define TK_COMMA                          26
08025 #define TK_ID                             27
08026 #define TK_INDEXED                        28
08027 #define TK_ABORT                          29
08028 #define TK_ACTION                         30
08029 #define TK_AFTER                          31
08030 #define TK_ANALYZE                        32
08031 #define TK_ASC                            33
08032 #define TK_ATTACH                         34
08033 #define TK_BEFORE                         35
08034 #define TK_BY                             36
08035 #define TK_CASCADE                        37
08036 #define TK_CAST                           38
08037 #define TK_COLUMNKW                       39
08038 #define TK_CONFLICT                       40
08039 #define TK_DATABASE                       41
08040 #define TK_DESC                           42
08041 #define TK_DETACH                         43
08042 #define TK_EACH                           44
08043 #define TK_FAIL                           45
08044 #define TK_FOR                            46
08045 #define TK_IGNORE                         47
08046 #define TK_INITIALLY                      48
08047 #define TK_INSTEAD                        49
08048 #define TK_LIKE_KW                        50
08049 #define TK_MATCH                          51
08050 #define TK_NO                             52
08051 #define TK_KEY                            53
08052 #define TK_OF                             54
08053 #define TK_OFFSET                         55
08054 #define TK_PRAGMA                         56
08055 #define TK_RAISE                          57
08056 #define TK_REPLACE                        58
08057 #define TK_RESTRICT                       59
08058 #define TK_ROW                            60
08059 #define TK_TRIGGER                        61
08060 #define TK_VACUUM                         62
08061 #define TK_VIEW                           63
08062 #define TK_VIRTUAL                        64
08063 #define TK_REINDEX                        65
08064 #define TK_RENAME                         66
08065 #define TK_CTIME_KW                       67
08066 #define TK_ANY                            68
08067 #define TK_OR                             69
08068 #define TK_AND                            70
08069 #define TK_IS                             71
08070 #define TK_BETWEEN                        72
08071 #define TK_IN                             73
08072 #define TK_ISNULL                         74
08073 #define TK_NOTNULL                        75
08074 #define TK_NE                             76
08075 #define TK_EQ                             77
08076 #define TK_GT                             78
08077 #define TK_LE                             79
08078 #define TK_LT                             80
08079 #define TK_GE                             81
08080 #define TK_ESCAPE                         82
08081 #define TK_BITAND                         83
08082 #define TK_BITOR                          84
08083 #define TK_LSHIFT                         85
08084 #define TK_RSHIFT                         86
08085 #define TK_PLUS                           87
08086 #define TK_MINUS                          88
08087 #define TK_STAR                           89
08088 #define TK_SLASH                          90
08089 #define TK_REM                            91
08090 #define TK_CONCAT                         92
08091 #define TK_COLLATE                        93
08092 #define TK_BITNOT                         94
08093 #define TK_STRING                         95
08094 #define TK_JOIN_KW                        96
08095 #define TK_CONSTRAINT                     97
08096 #define TK_DEFAULT                        98
08097 #define TK_NULL                           99
08098 #define TK_PRIMARY                        100
08099 #define TK_UNIQUE                         101
08100 #define TK_CHECK                          102
08101 #define TK_REFERENCES                     103
08102 #define TK_AUTOINCR                       104
08103 #define TK_ON                             105
08104 #define TK_INSERT                         106
08105 #define TK_DELETE                         107
08106 #define TK_UPDATE                         108
08107 #define TK_SET                            109
08108 #define TK_DEFERRABLE                     110
08109 #define TK_FOREIGN                        111
08110 #define TK_DROP                           112
08111 #define TK_UNION                          113
08112 #define TK_ALL                            114
08113 #define TK_EXCEPT                         115
08114 #define TK_INTERSECT                      116
08115 #define TK_SELECT                         117
08116 #define TK_DISTINCT                       118
08117 #define TK_DOT                            119
08118 #define TK_FROM                           120
08119 #define TK_JOIN                           121
08120 #define TK_USING                          122
08121 #define TK_ORDER                          123
08122 #define TK_GROUP                          124
08123 #define TK_HAVING                         125
08124 #define TK_LIMIT                          126
08125 #define TK_WHERE                          127
08126 #define TK_INTO                           128
08127 #define TK_VALUES                         129
08128 #define TK_INTEGER                        130
08129 #define TK_FLOAT                          131
08130 #define TK_BLOB                           132
08131 #define TK_REGISTER                       133
08132 #define TK_VARIABLE                       134
08133 #define TK_CASE                           135
08134 #define TK_WHEN                           136
08135 #define TK_THEN                           137
08136 #define TK_ELSE                           138
08137 #define TK_INDEX                          139
08138 #define TK_ALTER                          140
08139 #define TK_ADD                            141
08140 #define TK_TO_TEXT                        142
08141 #define TK_TO_BLOB                        143
08142 #define TK_TO_NUMERIC                     144
08143 #define TK_TO_INT                         145
08144 #define TK_TO_REAL                        146
08145 #define TK_ISNOT                          147
08146 #define TK_END_OF_FILE                    148
08147 #define TK_ILLEGAL                        149
08148 #define TK_SPACE                          150
08149 #define TK_UNCLOSED_STRING                151
08150 #define TK_FUNCTION                       152
08151 #define TK_COLUMN                         153
08152 #define TK_AGG_FUNCTION                   154
08153 #define TK_AGG_COLUMN                     155
08154 #define TK_UMINUS                         156
08155 #define TK_UPLUS                          157
08156 
08157 /************** End of parse.h ***********************************************/
08158 /************** Continuing where we left off in sqliteInt.h ******************/
08159 #include <stdio.h>
08160 #include <stdlib.h>
08161 #include <string.h>
08162 #include <assert.h>
08163 #include <stddef.h>
08164 
08165 /*
08166 ** If compiling for a processor that lacks floating point support,
08167 ** substitute integer for floating-point
08168 */
08169 #ifdef SQLITE_OMIT_FLOATING_POINT
08170 # define double sqlite_int64
08171 # define float sqlite_int64
08172 # define LONGDOUBLE_TYPE sqlite_int64
08173 # ifndef SQLITE_BIG_DBL
08174 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
08175 # endif
08176 # define SQLITE_OMIT_DATETIME_FUNCS 1
08177 # define SQLITE_OMIT_TRACE 1
08178 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
08179 # undef SQLITE_HAVE_ISNAN
08180 #endif
08181 #ifndef SQLITE_BIG_DBL
08182 # define SQLITE_BIG_DBL (1e99)
08183 #endif
08184 
08185 /*
08186 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
08187 ** afterward. Having this macro allows us to cause the C compiler 
08188 ** to omit code used by TEMP tables without messy #ifndef statements.
08189 */
08190 #ifdef SQLITE_OMIT_TEMPDB
08191 #define OMIT_TEMPDB 1
08192 #else
08193 #define OMIT_TEMPDB 0
08194 #endif
08195 
08196 /*
08197 ** The "file format" number is an integer that is incremented whenever
08198 ** the VDBE-level file format changes.  The following macros define the
08199 ** the default file format for new databases and the maximum file format
08200 ** that the library can read.
08201 */
08202 #define SQLITE_MAX_FILE_FORMAT 4
08203 #ifndef SQLITE_DEFAULT_FILE_FORMAT
08204 # define SQLITE_DEFAULT_FILE_FORMAT 4
08205 #endif
08206 
08207 /*
08208 ** Determine whether triggers are recursive by default.  This can be
08209 ** changed at run-time using a pragma.
08210 */
08211 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
08212 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
08213 #endif
08214 
08215 /*
08216 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
08217 ** on the command-line
08218 */
08219 #ifndef SQLITE_TEMP_STORE
08220 # define SQLITE_TEMP_STORE 1
08221 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
08222 #endif
08223 
08224 /*
08225 ** GCC does not define the offsetof() macro so we'll have to do it
08226 ** ourselves.
08227 */
08228 #ifndef offsetof
08229 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
08230 #endif
08231 
08232 /*
08233 ** Macros to compute minimum and maximum of two numbers.
08234 */
08235 #define MIN(A,B) ((A)<(B)?(A):(B))
08236 #define MAX(A,B) ((A)>(B)?(A):(B))
08237 
08238 /*
08239 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
08240 ** not, there are still machines out there that use EBCDIC.)
08241 */
08242 #if 'A' == '\301'
08243 # define SQLITE_EBCDIC 1
08244 #else
08245 # define SQLITE_ASCII 1
08246 #endif
08247 
08248 /*
08249 ** Integers of known sizes.  These typedefs might change for architectures
08250 ** where the sizes very.  Preprocessor macros are available so that the
08251 ** types can be conveniently redefined at compile-type.  Like this:
08252 **
08253 **         cc '-DUINTPTR_TYPE=long long int' ...
08254 */
08255 #ifndef UINT32_TYPE
08256 # ifdef HAVE_UINT32_T
08257 #  define UINT32_TYPE uint32_t
08258 # else
08259 #  define UINT32_TYPE unsigned int
08260 # endif
08261 #endif
08262 #ifndef UINT16_TYPE
08263 # ifdef HAVE_UINT16_T
08264 #  define UINT16_TYPE uint16_t
08265 # else
08266 #  define UINT16_TYPE unsigned short int
08267 # endif
08268 #endif
08269 #ifndef INT16_TYPE
08270 # ifdef HAVE_INT16_T
08271 #  define INT16_TYPE int16_t
08272 # else
08273 #  define INT16_TYPE short int
08274 # endif
08275 #endif
08276 #ifndef UINT8_TYPE
08277 # ifdef HAVE_UINT8_T
08278 #  define UINT8_TYPE uint8_t
08279 # else
08280 #  define UINT8_TYPE unsigned char
08281 # endif
08282 #endif
08283 #ifndef INT8_TYPE
08284 # ifdef HAVE_INT8_T
08285 #  define INT8_TYPE int8_t
08286 # else
08287 #  define INT8_TYPE signed char
08288 # endif
08289 #endif
08290 #ifndef LONGDOUBLE_TYPE
08291 # define LONGDOUBLE_TYPE long double
08292 #endif
08293 typedef sqlite_int64 i64;          /* 8-byte signed integer */
08294 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
08295 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
08296 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
08297 typedef INT16_TYPE i16;            /* 2-byte signed integer */
08298 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
08299 typedef INT8_TYPE i8;              /* 1-byte signed integer */
08300 
08301 /*
08302 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
08303 ** that can be stored in a u32 without loss of data.  The value
08304 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
08305 ** have to specify the value in the less intuitive manner shown:
08306 */
08307 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
08308 
08309 /*
08310 ** The datatype used to store estimates of the number of rows in a
08311 ** table or index.  This is an unsigned integer type.  For 99.9% of
08312 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
08313 ** can be used at compile-time if desired.
08314 */
08315 #ifdef SQLITE_64BIT_STATS
08316  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
08317 #else
08318  typedef u32 tRowcnt;    /* 32-bit is the default */
08319 #endif
08320 
08321 /*
08322 ** Estimated quantities used for query planning are stored as 16-bit
08323 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
08324 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
08325 ** But the allowed values are "grainy".  Not every value is representable.
08326 ** For example, quantities 16 and 17 are both represented by a LogEst
08327 ** of 40.  However, since LogEst quantatites are suppose to be estimates,
08328 ** not exact values, this imprecision is not a problem.
08329 **
08330 ** "LogEst" is short for "Logarithimic Estimate".
08331 **
08332 ** Examples:
08333 **      1 -> 0              20 -> 43          10000 -> 132
08334 **      2 -> 10             25 -> 46          25000 -> 146
08335 **      3 -> 16            100 -> 66        1000000 -> 199
08336 **      4 -> 20           1000 -> 99        1048576 -> 200
08337 **     10 -> 33           1024 -> 100    4294967296 -> 320
08338 **
08339 ** The LogEst can be negative to indicate fractional values. 
08340 ** Examples:
08341 **
08342 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
08343 */
08344 typedef INT16_TYPE LogEst;
08345 
08346 /*
08347 ** Macros to determine whether the machine is big or little endian,
08348 ** evaluated at runtime.
08349 */
08350 #ifdef SQLITE_AMALGAMATION
08351 SQLITE_PRIVATE const int sqlite3one = 1;
08352 #else
08353 SQLITE_PRIVATE const int sqlite3one;
08354 #endif
08355 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
08356                              || defined(__x86_64) || defined(__x86_64__)
08357 # define SQLITE_BIGENDIAN    0
08358 # define SQLITE_LITTLEENDIAN 1
08359 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
08360 #else
08361 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
08362 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
08363 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
08364 #endif
08365 
08366 /*
08367 ** Constants for the largest and smallest possible 64-bit signed integers.
08368 ** These macros are designed to work correctly on both 32-bit and 64-bit
08369 ** compilers.
08370 */
08371 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
08372 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
08373 
08374 /* 
08375 ** Round up a number to the next larger multiple of 8.  This is used
08376 ** to force 8-byte alignment on 64-bit architectures.
08377 */
08378 #define ROUND8(x)     (((x)+7)&~7)
08379 
08380 /*
08381 ** Round down to the nearest multiple of 8
08382 */
08383 #define ROUNDDOWN8(x) ((x)&~7)
08384 
08385 /*
08386 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
08387 ** macro is used only within assert() to verify that the code gets
08388 ** all alignment restrictions correct.
08389 **
08390 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
08391 ** underlying malloc() implemention might return us 4-byte aligned
08392 ** pointers.  In that case, only verify 4-byte alignment.
08393 */
08394 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
08395 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
08396 #else
08397 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
08398 #endif
08399 
08400 /*
08401 ** Disable MMAP on platforms where it is known to not work
08402 */
08403 #if defined(__OpenBSD__) || defined(__QNXNTO__)
08404 # undef SQLITE_MAX_MMAP_SIZE
08405 # define SQLITE_MAX_MMAP_SIZE 0
08406 #endif
08407 
08408 /*
08409 ** Default maximum size of memory used by memory-mapped I/O in the VFS
08410 */
08411 #ifdef __APPLE__
08412 # include <TargetConditionals.h>
08413 # if TARGET_OS_IPHONE
08414 #   undef SQLITE_MAX_MMAP_SIZE
08415 #   define SQLITE_MAX_MMAP_SIZE 0
08416 # endif
08417 #endif
08418 #ifndef SQLITE_MAX_MMAP_SIZE
08419 # if defined(__linux__) \
08420   || defined(_WIN32) \
08421   || (defined(__APPLE__) && defined(__MACH__)) \
08422   || defined(__sun)
08423 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
08424 # else
08425 #   define SQLITE_MAX_MMAP_SIZE 0
08426 # endif
08427 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
08428 #endif
08429 
08430 /*
08431 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
08432 ** default MMAP_SIZE is specified at compile-time, make sure that it does
08433 ** not exceed the maximum mmap size.
08434 */
08435 #ifndef SQLITE_DEFAULT_MMAP_SIZE
08436 # define SQLITE_DEFAULT_MMAP_SIZE 0
08437 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
08438 #endif
08439 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
08440 # undef SQLITE_DEFAULT_MMAP_SIZE
08441 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
08442 #endif
08443 
08444 /*
08445 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
08446 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
08447 ** define SQLITE_ENABLE_STAT3_OR_STAT4
08448 */
08449 #ifdef SQLITE_ENABLE_STAT4
08450 # undef SQLITE_ENABLE_STAT3
08451 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
08452 #elif SQLITE_ENABLE_STAT3
08453 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
08454 #elif SQLITE_ENABLE_STAT3_OR_STAT4
08455 # undef SQLITE_ENABLE_STAT3_OR_STAT4
08456 #endif
08457 
08458 /*
08459 ** An instance of the following structure is used to store the busy-handler
08460 ** callback for a given sqlite handle. 
08461 **
08462 ** The sqlite.busyHandler member of the sqlite struct contains the busy
08463 ** callback for the database handle. Each pager opened via the sqlite
08464 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
08465 ** callback is currently invoked only from within pager.c.
08466 */
08467 typedef struct BusyHandler BusyHandler;
08468 struct BusyHandler {
08469   int (*xFunc)(void *,int);  /* The busy callback */
08470   void *pArg;                /* First arg to busy callback */
08471   int nBusy;                 /* Incremented with each busy call */
08472 };
08473 
08474 /*
08475 ** Name of the master database table.  The master database table
08476 ** is a special table that holds the names and attributes of all
08477 ** user tables and indices.
08478 */
08479 #define MASTER_NAME       "sqlite_master"
08480 #define TEMP_MASTER_NAME  "sqlite_temp_master"
08481 
08482 /*
08483 ** The root-page of the master database table.
08484 */
08485 #define MASTER_ROOT       1
08486 
08487 /*
08488 ** The name of the schema table.
08489 */
08490 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
08491 
08492 /*
08493 ** A convenience macro that returns the number of elements in
08494 ** an array.
08495 */
08496 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
08497 
08498 /*
08499 ** Determine if the argument is a power of two
08500 */
08501 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
08502 
08503 /*
08504 ** The following value as a destructor means to use sqlite3DbFree().
08505 ** The sqlite3DbFree() routine requires two parameters instead of the 
08506 ** one parameter that destructors normally want.  So we have to introduce 
08507 ** this magic value that the code knows to handle differently.  Any 
08508 ** pointer will work here as long as it is distinct from SQLITE_STATIC
08509 ** and SQLITE_TRANSIENT.
08510 */
08511 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
08512 
08513 /*
08514 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
08515 ** not support Writable Static Data (WSD) such as global and static variables.
08516 ** All variables must either be on the stack or dynamically allocated from
08517 ** the heap.  When WSD is unsupported, the variable declarations scattered
08518 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
08519 ** macro is used for this purpose.  And instead of referencing the variable
08520 ** directly, we use its constant as a key to lookup the run-time allocated
08521 ** buffer that holds real variable.  The constant is also the initializer
08522 ** for the run-time allocated buffer.
08523 **
08524 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
08525 ** macros become no-ops and have zero performance impact.
08526 */
08527 #ifdef SQLITE_OMIT_WSD
08528   #define SQLITE_WSD const
08529   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
08530   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
08531 SQLITE_API   int sqlite3_wsd_init(int N, int J);
08532 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
08533 #else
08534   #define SQLITE_WSD 
08535   #define GLOBAL(t,v) v
08536   #define sqlite3GlobalConfig sqlite3Config
08537 #endif
08538 
08539 /*
08540 ** The following macros are used to suppress compiler warnings and to
08541 ** make it clear to human readers when a function parameter is deliberately 
08542 ** left unused within the body of a function. This usually happens when
08543 ** a function is called via a function pointer. For example the 
08544 ** implementation of an SQL aggregate step callback may not use the
08545 ** parameter indicating the number of arguments passed to the aggregate,
08546 ** if it knows that this is enforced elsewhere.
08547 **
08548 ** When a function parameter is not used at all within the body of a function,
08549 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
08550 ** However, these macros may also be used to suppress warnings related to
08551 ** parameters that may or may not be used depending on compilation options.
08552 ** For example those parameters only used in assert() statements. In these
08553 ** cases the parameters are named as per the usual conventions.
08554 */
08555 #define UNUSED_PARAMETER(x) (void)(x)
08556 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
08557 
08558 /*
08559 ** Forward references to structures
08560 */
08561 typedef struct AggInfo AggInfo;
08562 typedef struct AuthContext AuthContext;
08563 typedef struct AutoincInfo AutoincInfo;
08564 typedef struct Bitvec Bitvec;
08565 typedef struct CollSeq CollSeq;
08566 typedef struct Column Column;
08567 typedef struct Db Db;
08568 typedef struct Schema Schema;
08569 typedef struct Expr Expr;
08570 typedef struct ExprList ExprList;
08571 typedef struct ExprSpan ExprSpan;
08572 typedef struct FKey FKey;
08573 typedef struct FuncDestructor FuncDestructor;
08574 typedef struct FuncDef FuncDef;
08575 typedef struct FuncDefHash FuncDefHash;
08576 typedef struct IdList IdList;
08577 typedef struct Index Index;
08578 typedef struct IndexSample IndexSample;
08579 typedef struct KeyClass KeyClass;
08580 typedef struct KeyInfo KeyInfo;
08581 typedef struct Lookaside Lookaside;
08582 typedef struct LookasideSlot LookasideSlot;
08583 typedef struct Module Module;
08584 typedef struct NameContext NameContext;
08585 typedef struct Parse Parse;
08586 typedef struct RowSet RowSet;
08587 typedef struct Savepoint Savepoint;
08588 typedef struct Select Select;
08589 typedef struct SelectDest SelectDest;
08590 typedef struct SrcList SrcList;
08591 typedef struct StrAccum StrAccum;
08592 typedef struct Table Table;
08593 typedef struct TableLock TableLock;
08594 typedef struct Token Token;
08595 typedef struct Trigger Trigger;
08596 typedef struct TriggerPrg TriggerPrg;
08597 typedef struct TriggerStep TriggerStep;
08598 typedef struct UnpackedRecord UnpackedRecord;
08599 typedef struct VTable VTable;
08600 typedef struct VtabCtx VtabCtx;
08601 typedef struct Walker Walker;
08602 typedef struct WhereInfo WhereInfo;
08603 
08604 /*
08605 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
08606 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
08607 ** pointer types (i.e. FuncDef) defined above.
08608 */
08609 /************** Include btree.h in the middle of sqliteInt.h *****************/
08610 /************** Begin file btree.h *******************************************/
08611 /*
08612 ** 2001 September 15
08613 **
08614 ** The author disclaims copyright to this source code.  In place of
08615 ** a legal notice, here is a blessing:
08616 **
08617 **    May you do good and not evil.
08618 **    May you find forgiveness for yourself and forgive others.
08619 **    May you share freely, never taking more than you give.
08620 **
08621 *************************************************************************
08622 ** This header file defines the interface that the sqlite B-Tree file
08623 ** subsystem.  See comments in the source code for a detailed description
08624 ** of what each interface routine does.
08625 */
08626 #ifndef _BTREE_H_
08627 #define _BTREE_H_
08628 
08629 /* TODO: This definition is just included so other modules compile. It
08630 ** needs to be revisited.
08631 */
08632 #define SQLITE_N_BTREE_META 10
08633 
08634 /*
08635 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
08636 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
08637 */
08638 #ifndef SQLITE_DEFAULT_AUTOVACUUM
08639   #define SQLITE_DEFAULT_AUTOVACUUM 0
08640 #endif
08641 
08642 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
08643 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
08644 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
08645 
08646 /*
08647 ** Forward declarations of structure
08648 */
08649 typedef struct Btree Btree;
08650 typedef struct BtCursor BtCursor;
08651 typedef struct BtShared BtShared;
08652 
08653 
08654 SQLITE_PRIVATE int sqlite3BtreeOpen(
08655   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
08656   const char *zFilename,   /* Name of database file to open */
08657   sqlite3 *db,             /* Associated database connection */
08658   Btree **ppBtree,         /* Return open Btree* here */
08659   int flags,               /* Flags */
08660   int vfsFlags             /* Flags passed through to VFS open */
08661 );
08662 
08663 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
08664 ** following values.
08665 **
08666 ** NOTE:  These values must match the corresponding PAGER_ values in
08667 ** pager.h.
08668 */
08669 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
08670 #define BTREE_MEMORY        2  /* This is an in-memory DB */
08671 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
08672 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
08673 
08674 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
08675 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
08676 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
08677 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
08678 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
08679 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
08680 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
08681 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
08682 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
08683 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
08684 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
08685 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
08686 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
08687 #endif
08688 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
08689 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
08690 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
08691 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
08692 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
08693 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
08694 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
08695 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
08696 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
08697 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
08698 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
08699 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
08700 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
08701 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
08702 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
08703 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
08704 
08705 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
08706 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
08707 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
08708 
08709 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
08710 
08711 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
08712 ** of the flags shown below.
08713 **
08714 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
08715 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
08716 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
08717 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
08718 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
08719 ** indices.)
08720 */
08721 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
08722 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
08723 
08724 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
08725 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
08726 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
08727 
08728 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
08729 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
08730 
08731 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
08732 
08733 /*
08734 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
08735 ** should be one of the following values. The integer values are assigned 
08736 ** to constants so that the offset of the corresponding field in an
08737 ** SQLite database header may be found using the following formula:
08738 **
08739 **   offset = 36 + (idx * 4)
08740 **
08741 ** For example, the free-page-count field is located at byte offset 36 of
08742 ** the database file header. The incr-vacuum-flag field is located at
08743 ** byte offset 64 (== 36+4*7).
08744 */
08745 #define BTREE_FREE_PAGE_COUNT     0
08746 #define BTREE_SCHEMA_VERSION      1
08747 #define BTREE_FILE_FORMAT         2
08748 #define BTREE_DEFAULT_CACHE_SIZE  3
08749 #define BTREE_LARGEST_ROOT_PAGE   4
08750 #define BTREE_TEXT_ENCODING       5
08751 #define BTREE_USER_VERSION        6
08752 #define BTREE_INCR_VACUUM         7
08753 #define BTREE_APPLICATION_ID      8
08754 
08755 /*
08756 ** Values that may be OR'd together to form the second argument of an
08757 ** sqlite3BtreeCursorHints() call.
08758 */
08759 #define BTREE_BULKLOAD 0x00000001
08760 
08761 SQLITE_PRIVATE int sqlite3BtreeCursor(
08762   Btree*,                              /* BTree containing table to open */
08763   int iTable,                          /* Index of root page */
08764   int wrFlag,                          /* 1 for writing.  0 for read-only */
08765   struct KeyInfo*,                     /* First argument to compare function */
08766   BtCursor *pCursor                    /* Space to write cursor structure */
08767 );
08768 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
08769 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
08770 
08771 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
08772 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
08773   BtCursor*,
08774   UnpackedRecord *pUnKey,
08775   i64 intKey,
08776   int bias,
08777   int *pRes
08778 );
08779 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
08780 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
08781 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
08782                                   const void *pData, int nData,
08783                                   int nZero, int bias, int seekResult);
08784 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
08785 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
08786 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
08787 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
08788 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
08789 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
08790 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
08791 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
08792 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
08793 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
08794 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
08795 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
08796 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
08797 
08798 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
08799 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
08800 
08801 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
08802 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
08803 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
08804 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
08805 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
08806 
08807 #ifndef NDEBUG
08808 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
08809 #endif
08810 
08811 #ifndef SQLITE_OMIT_BTREECOUNT
08812 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
08813 #endif
08814 
08815 #ifdef SQLITE_TEST
08816 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
08817 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
08818 #endif
08819 
08820 #ifndef SQLITE_OMIT_WAL
08821 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
08822 #endif
08823 
08824 /*
08825 ** If we are not using shared cache, then there is no need to
08826 ** use mutexes to access the BtShared structures.  So make the
08827 ** Enter and Leave procedures no-ops.
08828 */
08829 #ifndef SQLITE_OMIT_SHARED_CACHE
08830 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
08831 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
08832 #else
08833 # define sqlite3BtreeEnter(X) 
08834 # define sqlite3BtreeEnterAll(X)
08835 #endif
08836 
08837 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
08838 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
08839 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
08840 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
08841 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
08842 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
08843 #ifndef NDEBUG
08844   /* These routines are used inside assert() statements only. */
08845 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
08846 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
08847 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
08848 #endif
08849 #else
08850 
08851 # define sqlite3BtreeSharable(X) 0
08852 # define sqlite3BtreeLeave(X)
08853 # define sqlite3BtreeEnterCursor(X)
08854 # define sqlite3BtreeLeaveCursor(X)
08855 # define sqlite3BtreeLeaveAll(X)
08856 
08857 # define sqlite3BtreeHoldsMutex(X) 1
08858 # define sqlite3BtreeHoldsAllMutexes(X) 1
08859 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
08860 #endif
08861 
08862 
08863 #endif /* _BTREE_H_ */
08864 
08865 /************** End of btree.h ***********************************************/
08866 /************** Continuing where we left off in sqliteInt.h ******************/
08867 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
08868 /************** Begin file vdbe.h ********************************************/
08869 /*
08870 ** 2001 September 15
08871 **
08872 ** The author disclaims copyright to this source code.  In place of
08873 ** a legal notice, here is a blessing:
08874 **
08875 **    May you do good and not evil.
08876 **    May you find forgiveness for yourself and forgive others.
08877 **    May you share freely, never taking more than you give.
08878 **
08879 *************************************************************************
08880 ** Header file for the Virtual DataBase Engine (VDBE)
08881 **
08882 ** This header defines the interface to the virtual database engine
08883 ** or VDBE.  The VDBE implements an abstract machine that runs a
08884 ** simple program to access and modify the underlying database.
08885 */
08886 #ifndef _SQLITE_VDBE_H_
08887 #define _SQLITE_VDBE_H_
08888 /* #include <stdio.h> */
08889 
08890 /*
08891 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
08892 ** in the source file sqliteVdbe.c are allowed to see the insides
08893 ** of this structure.
08894 */
08895 typedef struct Vdbe Vdbe;
08896 
08897 /*
08898 ** The names of the following types declared in vdbeInt.h are required
08899 ** for the VdbeOp definition.
08900 */
08901 typedef struct Mem Mem;
08902 typedef struct SubProgram SubProgram;
08903 
08904 /*
08905 ** A single instruction of the virtual machine has an opcode
08906 ** and as many as three operands.  The instruction is recorded
08907 ** as an instance of the following structure:
08908 */
08909 struct VdbeOp {
08910   u8 opcode;          /* What operation to perform */
08911   signed char p4type; /* One of the P4_xxx constants for p4 */
08912   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
08913   u8 p5;              /* Fifth parameter is an unsigned character */
08914   int p1;             /* First operand */
08915   int p2;             /* Second parameter (often the jump destination) */
08916   int p3;             /* The third parameter */
08917   union {             /* fourth parameter */
08918     int i;                 /* Integer value if p4type==P4_INT32 */
08919     void *p;               /* Generic pointer */
08920     char *z;               /* Pointer to data for string (char array) types */
08921     i64 *pI64;             /* Used when p4type is P4_INT64 */
08922     double *pReal;         /* Used when p4type is P4_REAL */
08923     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
08924     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
08925     Mem *pMem;             /* Used when p4type is P4_MEM */
08926     VTable *pVtab;         /* Used when p4type is P4_VTAB */
08927     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
08928     int *ai;               /* Used when p4type is P4_INTARRAY */
08929     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
08930     int (*xAdvance)(BtCursor *, int *);
08931   } p4;
08932 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
08933   char *zComment;          /* Comment to improve readability */
08934 #endif
08935 #ifdef VDBE_PROFILE
08936   int cnt;                 /* Number of times this instruction was executed */
08937   u64 cycles;              /* Total time spent executing this instruction */
08938 #endif
08939 };
08940 typedef struct VdbeOp VdbeOp;
08941 
08942 
08943 /*
08944 ** A sub-routine used to implement a trigger program.
08945 */
08946 struct SubProgram {
08947   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
08948   int nOp;                      /* Elements in aOp[] */
08949   int nMem;                     /* Number of memory cells required */
08950   int nCsr;                     /* Number of cursors required */
08951   int nOnce;                    /* Number of OP_Once instructions */
08952   void *token;                  /* id that may be used to recursive triggers */
08953   SubProgram *pNext;            /* Next sub-program already visited */
08954 };
08955 
08956 /*
08957 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
08958 ** it takes up less space.
08959 */
08960 struct VdbeOpList {
08961   u8 opcode;          /* What operation to perform */
08962   signed char p1;     /* First operand */
08963   signed char p2;     /* Second parameter (often the jump destination) */
08964   signed char p3;     /* Third parameter */
08965 };
08966 typedef struct VdbeOpList VdbeOpList;
08967 
08968 /*
08969 ** Allowed values of VdbeOp.p4type
08970 */
08971 #define P4_NOTUSED    0   /* The P4 parameter is not used */
08972 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
08973 #define P4_STATIC   (-2)  /* Pointer to a static string */
08974 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
08975 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
08976 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
08977 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
08978 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
08979 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
08980 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
08981 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
08982 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
08983 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
08984 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
08985 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
08986 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
08987 
08988 /* Error message codes for OP_Halt */
08989 #define P5_ConstraintNotNull 1
08990 #define P5_ConstraintUnique  2
08991 #define P5_ConstraintCheck   3
08992 #define P5_ConstraintFK      4
08993 
08994 /*
08995 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
08996 ** number of columns of data returned by the statement.
08997 */
08998 #define COLNAME_NAME     0
08999 #define COLNAME_DECLTYPE 1
09000 #define COLNAME_DATABASE 2
09001 #define COLNAME_TABLE    3
09002 #define COLNAME_COLUMN   4
09003 #ifdef SQLITE_ENABLE_COLUMN_METADATA
09004 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
09005 #else
09006 # ifdef SQLITE_OMIT_DECLTYPE
09007 #   define COLNAME_N      1      /* Store only the name */
09008 # else
09009 #   define COLNAME_N      2      /* Store the name and decltype */
09010 # endif
09011 #endif
09012 
09013 /*
09014 ** The following macro converts a relative address in the p2 field
09015 ** of a VdbeOp structure into a negative number so that 
09016 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
09017 ** the macro again restores the address.
09018 */
09019 #define ADDR(X)  (-1-(X))
09020 
09021 /*
09022 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
09023 ** header file that defines a number for each opcode used by the VDBE.
09024 */
09025 /************** Include opcodes.h in the middle of vdbe.h ********************/
09026 /************** Begin file opcodes.h *****************************************/
09027 /* Automatically generated.  Do not edit */
09028 /* See the mkopcodeh.awk script for details */
09029 #define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
09030 #define OP_Savepoint       2
09031 #define OP_AutoCommit      3
09032 #define OP_Transaction     4
09033 #define OP_SorterNext      5
09034 #define OP_PrevIfOpen      6
09035 #define OP_NextIfOpen      7
09036 #define OP_Prev            8
09037 #define OP_Next            9
09038 #define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
09039 #define OP_Checkpoint     11
09040 #define OP_JournalMode    12
09041 #define OP_Vacuum         13
09042 #define OP_VFilter        14 /* synopsis: iPlan=r[P3] zPlan='P4'           */
09043 #define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
09044 #define OP_Goto           16
09045 #define OP_Gosub          17
09046 #define OP_Return         18
09047 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
09048 #define OP_Yield          20
09049 #define OP_HaltIfNull     21 /* synopsis: if r[P3] null then halt          */
09050 #define OP_Halt           22
09051 #define OP_Integer        23 /* synopsis: r[P2]=P1                         */
09052 #define OP_Int64          24 /* synopsis: r[P2]=P4                         */
09053 #define OP_String         25 /* synopsis: r[P2]='P4' (len=P1)              */
09054 #define OP_Null           26 /* synopsis: r[P2..P3]=NULL                   */
09055 #define OP_Blob           27 /* synopsis: r[P2]=P4 (len=P1)                */
09056 #define OP_Variable       28 /* synopsis: r[P2]=parameter(P1,P4)           */
09057 #define OP_Move           29 /* synopsis: r[P2@P3]=r[P1@P3]                */
09058 #define OP_Copy           30 /* synopsis: r[P2@P3]=r[P1@P3]                */
09059 #define OP_SCopy          31 /* synopsis: r[P2]=r[P1]                      */
09060 #define OP_ResultRow      32 /* synopsis: output=r[P1@P2]                  */
09061 #define OP_CollSeq        33
09062 #define OP_AddImm         34 /* synopsis: r[P1]=r[P1]+P2                   */
09063 #define OP_MustBeInt      35
09064 #define OP_RealAffinity   36
09065 #define OP_Permutation    37
09066 #define OP_Compare        38
09067 #define OP_Jump           39
09068 #define OP_Once           40
09069 #define OP_If             41
09070 #define OP_IfNot          42
09071 #define OP_Column         43 /* synopsis: r[P3]=PX                         */
09072 #define OP_Affinity       44 /* synopsis: affinity(r[P1@P2])               */
09073 #define OP_MakeRecord     45 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
09074 #define OP_Count          46 /* synopsis: r[P2]=count()                    */
09075 #define OP_ReadCookie     47
09076 #define OP_SetCookie      48
09077 #define OP_VerifyCookie   49
09078 #define OP_OpenRead       50 /* synopsis: root=P2 iDb=P3                   */
09079 #define OP_OpenWrite      51 /* synopsis: root=P2 iDb=P3                   */
09080 #define OP_OpenAutoindex  52 /* synopsis: nColumn=P2                       */
09081 #define OP_OpenEphemeral  53 /* synopsis: nColumn=P2                       */
09082 #define OP_SorterOpen     54
09083 #define OP_OpenPseudo     55 /* synopsis: content in r[P2@P3]              */
09084 #define OP_Close          56
09085 #define OP_SeekLt         57 /* synopsis: key=r[P3@P4]                     */
09086 #define OP_SeekLe         58 /* synopsis: key=r[P3@P4]                     */
09087 #define OP_SeekGe         59 /* synopsis: key=r[P3@P4]                     */
09088 #define OP_SeekGt         60 /* synopsis: key=r[P3@P4]                     */
09089 #define OP_Seek           61 /* synopsis: intkey=r[P2]                     */
09090 #define OP_NoConflict     62 /* synopsis: key=r[P3@P4]                     */
09091 #define OP_NotFound       63 /* synopsis: key=r[P3@P4]                     */
09092 #define OP_Found          64 /* synopsis: key=r[P3@P4]                     */
09093 #define OP_NotExists      65 /* synopsis: intkey=r[P3]                     */
09094 #define OP_Sequence       66 /* synopsis: r[P2]=rowid                      */
09095 #define OP_NewRowid       67 /* synopsis: r[P2]=rowid                      */
09096 #define OP_Insert         68 /* synopsis: intkey=r[P3] data=r[P2]          */
09097 #define OP_Or             69 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
09098 #define OP_And            70 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
09099 #define OP_InsertInt      71 /* synopsis: intkey=P3 data=r[P2]             */
09100 #define OP_Delete         72
09101 #define OP_ResetCount     73
09102 #define OP_IsNull         74 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
09103 #define OP_NotNull        75 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
09104 #define OP_Ne             76 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
09105 #define OP_Eq             77 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
09106 #define OP_Gt             78 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
09107 #define OP_Le             79 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
09108 #define OP_Lt             80 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
09109 #define OP_Ge             81 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
09110 #define OP_SorterCompare  82 /* synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2 */
09111 #define OP_BitAnd         83 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
09112 #define OP_BitOr          84 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
09113 #define OP_ShiftLeft      85 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
09114 #define OP_ShiftRight     86 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
09115 #define OP_Add            87 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
09116 #define OP_Subtract       88 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
09117 #define OP_Multiply       89 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
09118 #define OP_Divide         90 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
09119 #define OP_Remainder      91 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
09120 #define OP_Concat         92 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
09121 #define OP_SorterData     93 /* synopsis: r[P2]=data                       */
09122 #define OP_BitNot         94 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
09123 #define OP_String8        95 /* same as TK_STRING, synopsis: r[P2]='P4'    */
09124 #define OP_RowKey         96 /* synopsis: r[P2]=key                        */
09125 #define OP_RowData        97 /* synopsis: r[P2]=data                       */
09126 #define OP_Rowid          98 /* synopsis: r[P2]=rowid                      */
09127 #define OP_NullRow        99
09128 #define OP_Last          100
09129 #define OP_SorterSort    101
09130 #define OP_Sort          102
09131 #define OP_Rewind        103
09132 #define OP_SorterInsert  104
09133 #define OP_IdxInsert     105 /* synopsis: key=r[P2]                        */
09134 #define OP_IdxDelete     106 /* synopsis: key=r[P2@P3]                     */
09135 #define OP_IdxRowid      107 /* synopsis: r[P2]=rowid                      */
09136 #define OP_IdxLT         108 /* synopsis: key=r[P3@P4]                     */
09137 #define OP_IdxGE         109 /* synopsis: key=r[P3@P4]                     */
09138 #define OP_Destroy       110
09139 #define OP_Clear         111
09140 #define OP_CreateIndex   112 /* synopsis: r[P2]=root iDb=P1                */
09141 #define OP_CreateTable   113 /* synopsis: r[P2]=root iDb=P1                */
09142 #define OP_ParseSchema   114
09143 #define OP_LoadAnalysis  115
09144 #define OP_DropTable     116
09145 #define OP_DropIndex     117
09146 #define OP_DropTrigger   118
09147 #define OP_IntegrityCk   119
09148 #define OP_RowSetAdd     120 /* synopsis: rowset(P1)=r[P2]                 */
09149 #define OP_RowSetRead    121 /* synopsis: r[P3]=rowset(P1)                 */
09150 #define OP_RowSetTest    122 /* synopsis: if r[P3] in rowset(P1) goto P2   */
09151 #define OP_Program       123
09152 #define OP_Param         124
09153 #define OP_FkCounter     125 /* synopsis: fkctr[P1]+=P2                    */
09154 #define OP_FkIfZero      126 /* synopsis: if fkctr[P1]==0 goto P2          */
09155 #define OP_MemMax        127 /* synopsis: r[P1]=max(r[P1],r[P2])           */
09156 #define OP_IfPos         128 /* synopsis: if r[P1]>0 goto P2               */
09157 #define OP_IfNeg         129 /* synopsis: if r[P1]<0 goto P2               */
09158 #define OP_IfZero        130 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2   */
09159 #define OP_Real          131 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
09160 #define OP_AggFinal      132 /* synopsis: accum=r[P1] N=P2                 */
09161 #define OP_IncrVacuum    133
09162 #define OP_Expire        134
09163 #define OP_TableLock     135 /* synopsis: iDb=P1 root=P2 write=P3          */
09164 #define OP_VBegin        136
09165 #define OP_VCreate       137
09166 #define OP_VDestroy      138
09167 #define OP_VOpen         139
09168 #define OP_VColumn       140 /* synopsis: r[P3]=vcolumn(P2)                */
09169 #define OP_VNext         141
09170 #define OP_ToText        142 /* same as TK_TO_TEXT                         */
09171 #define OP_ToBlob        143 /* same as TK_TO_BLOB                         */
09172 #define OP_ToNumeric     144 /* same as TK_TO_NUMERIC                      */
09173 #define OP_ToInt         145 /* same as TK_TO_INT                          */
09174 #define OP_ToReal        146 /* same as TK_TO_REAL                         */
09175 #define OP_VRename       147
09176 #define OP_Pagecount     148
09177 #define OP_MaxPgcnt      149
09178 #define OP_Trace         150
09179 #define OP_Noop          151
09180 #define OP_Explain       152
09181 
09182 
09183 /* Properties such as "out2" or "jump" that are specified in
09184 ** comments following the "case" for each opcode in the vdbe.c
09185 ** are encoded into bitvectors as follows:
09186 */
09187 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
09188 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
09189 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
09190 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
09191 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
09192 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
09193 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
09194 #define OPFLG_INITIALIZER {\
09195 /*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
09196 /*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
09197 /*  16 */ 0x01, 0x01, 0x04, 0x24, 0x04, 0x10, 0x00, 0x02,\
09198 /*  24 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x20,\
09199 /*  32 */ 0x00, 0x00, 0x04, 0x05, 0x04, 0x00, 0x00, 0x01,\
09200 /*  40 */ 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x02,\
09201 /*  48 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
09202 /*  56 */ 0x00, 0x11, 0x11, 0x11, 0x11, 0x08, 0x11, 0x11,\
09203 /*  64 */ 0x11, 0x11, 0x02, 0x02, 0x00, 0x4c, 0x4c, 0x00,\
09204 /*  72 */ 0x00, 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15,\
09205 /*  80 */ 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
09206 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02,\
09207 /*  96 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x01, 0x01, 0x01,\
09208 /* 104 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
09209 /* 112 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
09210 /* 120 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
09211 /* 128 */ 0x05, 0x05, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00,\
09212 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x04,\
09213 /* 144 */ 0x04, 0x04, 0x04, 0x00, 0x02, 0x02, 0x00, 0x00,\
09214 /* 152 */ 0x00,}
09215 
09216 /************** End of opcodes.h *********************************************/
09217 /************** Continuing where we left off in vdbe.h ***********************/
09218 
09219 /*
09220 ** Prototypes for the VDBE interface.  See comments on the implementation
09221 ** for a description of what each of these routines does.
09222 */
09223 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
09224 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
09225 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
09226 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
09227 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
09228 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
09229 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
09230 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
09231 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
09232 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
09233 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
09234 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
09235 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
09236 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
09237 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
09238 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
09239 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
09240 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
09241 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
09242 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
09243 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
09244 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
09245 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
09246 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
09247 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
09248 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
09249 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
09250 #ifdef SQLITE_DEBUG
09251 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
09252 #endif
09253 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
09254 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
09255 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
09256 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
09257 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
09258 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
09259 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
09260 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
09261 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
09262 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
09263 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
09264 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
09265 #ifndef SQLITE_OMIT_TRACE
09266 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
09267 #endif
09268 
09269 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
09270 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
09271 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
09272 
09273 #ifndef SQLITE_OMIT_TRIGGER
09274 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
09275 #endif
09276 
09277 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
09278 ** each VDBE opcode.
09279 **
09280 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
09281 ** comments in VDBE programs that show key decision points in the code
09282 ** generator.
09283 */
09284 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
09285 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
09286 # define VdbeComment(X)  sqlite3VdbeComment X
09287 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
09288 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
09289 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
09290 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
09291 # else
09292 #   define VdbeModuleComment(X)
09293 # endif
09294 #else
09295 # define VdbeComment(X)
09296 # define VdbeNoopComment(X)
09297 # define VdbeModuleComment(X)
09298 #endif
09299 
09300 #endif
09301 
09302 /************** End of vdbe.h ************************************************/
09303 /************** Continuing where we left off in sqliteInt.h ******************/
09304 /************** Include pager.h in the middle of sqliteInt.h *****************/
09305 /************** Begin file pager.h *******************************************/
09306 /*
09307 ** 2001 September 15
09308 **
09309 ** The author disclaims copyright to this source code.  In place of
09310 ** a legal notice, here is a blessing:
09311 **
09312 **    May you do good and not evil.
09313 **    May you find forgiveness for yourself and forgive others.
09314 **    May you share freely, never taking more than you give.
09315 **
09316 *************************************************************************
09317 ** This header file defines the interface that the sqlite page cache
09318 ** subsystem.  The page cache subsystem reads and writes a file a page
09319 ** at a time and provides a journal for rollback.
09320 */
09321 
09322 #ifndef _PAGER_H_
09323 #define _PAGER_H_
09324 
09325 /*
09326 ** Default maximum size for persistent journal files. A negative 
09327 ** value means no limit. This value may be overridden using the 
09328 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
09329 */
09330 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
09331   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
09332 #endif
09333 
09334 /*
09335 ** The type used to represent a page number.  The first page in a file
09336 ** is called page 1.  0 is used to represent "not a page".
09337 */
09338 typedef u32 Pgno;
09339 
09340 /*
09341 ** Each open file is managed by a separate instance of the "Pager" structure.
09342 */
09343 typedef struct Pager Pager;
09344 
09345 /*
09346 ** Handle type for pages.
09347 */
09348 typedef struct PgHdr DbPage;
09349 
09350 /*
09351 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
09352 ** reserved for working around a windows/posix incompatibility). It is
09353 ** used in the journal to signify that the remainder of the journal file 
09354 ** is devoted to storing a master journal name - there are no more pages to
09355 ** roll back. See comments for function writeMasterJournal() in pager.c 
09356 ** for details.
09357 */
09358 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
09359 
09360 /*
09361 ** Allowed values for the flags parameter to sqlite3PagerOpen().
09362 **
09363 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
09364 */
09365 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
09366 #define PAGER_MEMORY        0x0002    /* In-memory database */
09367 
09368 /*
09369 ** Valid values for the second argument to sqlite3PagerLockingMode().
09370 */
09371 #define PAGER_LOCKINGMODE_QUERY      -1
09372 #define PAGER_LOCKINGMODE_NORMAL      0
09373 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
09374 
09375 /*
09376 ** Numeric constants that encode the journalmode.  
09377 */
09378 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
09379 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
09380 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
09381 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
09382 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
09383 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
09384 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
09385 
09386 /*
09387 ** Flags that make up the mask passed to sqlite3PagerAcquire().
09388 */
09389 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
09390 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
09391 
09392 /*
09393 ** Flags for sqlite3PagerSetFlags()
09394 */
09395 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
09396 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
09397 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
09398 #define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
09399 #define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
09400 #define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
09401 #define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
09402 #define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
09403 
09404 /*
09405 ** The remainder of this file contains the declarations of the functions
09406 ** that make up the Pager sub-system API. See source code comments for 
09407 ** a detailed description of each routine.
09408 */
09409 
09410 /* Open and close a Pager connection. */ 
09411 SQLITE_PRIVATE int sqlite3PagerOpen(
09412   sqlite3_vfs*,
09413   Pager **ppPager,
09414   const char*,
09415   int,
09416   int,
09417   int,
09418   void(*)(DbPage*)
09419 );
09420 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
09421 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
09422 
09423 /* Functions used to configure a Pager object. */
09424 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
09425 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
09426 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
09427 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
09428 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
09429 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
09430 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
09431 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
09432 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
09433 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
09434 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
09435 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
09436 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
09437 
09438 /* Functions used to obtain and release page references. */ 
09439 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
09440 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
09441 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
09442 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
09443 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
09444 
09445 /* Operations on page references. */
09446 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
09447 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
09448 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
09449 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
09450 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
09451 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
09452 
09453 /* Functions used to manage pager transactions and savepoints. */
09454 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
09455 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
09456 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
09457 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
09458 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
09459 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
09460 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
09461 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
09462 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
09463 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
09464 
09465 #ifndef SQLITE_OMIT_WAL
09466 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
09467 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
09468 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
09469 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
09470 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
09471 #endif
09472 
09473 #ifdef SQLITE_ENABLE_ZIPVFS
09474 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
09475 #endif
09476 
09477 /* Functions used to query pager state and configuration. */
09478 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
09479 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
09480 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
09481 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
09482 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
09483 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
09484 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
09485 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
09486 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
09487 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
09488 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
09489 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
09490 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
09491 
09492 /* Functions used to truncate the database file. */
09493 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
09494 
09495 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
09496 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
09497 #endif
09498 
09499 /* Functions to support testing and debugging. */
09500 #if !defined(NDEBUG) || defined(SQLITE_TEST)
09501 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
09502 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
09503 #endif
09504 #ifdef SQLITE_TEST
09505 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
09506 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
09507   void disable_simulated_io_errors(void);
09508   void enable_simulated_io_errors(void);
09509 #else
09510 # define disable_simulated_io_errors()
09511 # define enable_simulated_io_errors()
09512 #endif
09513 
09514 #endif /* _PAGER_H_ */
09515 
09516 /************** End of pager.h ***********************************************/
09517 /************** Continuing where we left off in sqliteInt.h ******************/
09518 /************** Include pcache.h in the middle of sqliteInt.h ****************/
09519 /************** Begin file pcache.h ******************************************/
09520 /*
09521 ** 2008 August 05
09522 **
09523 ** The author disclaims copyright to this source code.  In place of
09524 ** a legal notice, here is a blessing:
09525 **
09526 **    May you do good and not evil.
09527 **    May you find forgiveness for yourself and forgive others.
09528 **    May you share freely, never taking more than you give.
09529 **
09530 *************************************************************************
09531 ** This header file defines the interface that the sqlite page cache
09532 ** subsystem. 
09533 */
09534 
09535 #ifndef _PCACHE_H_
09536 
09537 typedef struct PgHdr PgHdr;
09538 typedef struct PCache PCache;
09539 
09540 /*
09541 ** Every page in the cache is controlled by an instance of the following
09542 ** structure.
09543 */
09544 struct PgHdr {
09545   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
09546   void *pData;                   /* Page data */
09547   void *pExtra;                  /* Extra content */
09548   PgHdr *pDirty;                 /* Transient list of dirty pages */
09549   Pager *pPager;                 /* The pager this page is part of */
09550   Pgno pgno;                     /* Page number for this page */
09551 #ifdef SQLITE_CHECK_PAGES
09552   u32 pageHash;                  /* Hash of page content */
09553 #endif
09554   u16 flags;                     /* PGHDR flags defined below */
09555 
09556   /**********************************************************************
09557   ** Elements above are public.  All that follows is private to pcache.c
09558   ** and should not be accessed by other modules.
09559   */
09560   i16 nRef;                      /* Number of users of this page */
09561   PCache *pCache;                /* Cache that owns this page */
09562 
09563   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
09564   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
09565 };
09566 
09567 /* Bit values for PgHdr.flags */
09568 #define PGHDR_DIRTY             0x002  /* Page has changed */
09569 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
09570                                        ** writing this page to the database */
09571 #define PGHDR_NEED_READ         0x008  /* Content is unread */
09572 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
09573 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
09574 
09575 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
09576 
09577 /* Initialize and shutdown the page cache subsystem */
09578 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
09579 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
09580 
09581 /* Page cache buffer management:
09582 ** These routines implement SQLITE_CONFIG_PAGECACHE.
09583 */
09584 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
09585 
09586 /* Create a new pager cache.
09587 ** Under memory stress, invoke xStress to try to make pages clean.
09588 ** Only clean and unpinned pages can be reclaimed.
09589 */
09590 SQLITE_PRIVATE void sqlite3PcacheOpen(
09591   int szPage,                    /* Size of every page */
09592   int szExtra,                   /* Extra space associated with each page */
09593   int bPurgeable,                /* True if pages are on backing store */
09594   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
09595   void *pStress,                 /* Argument to xStress */
09596   PCache *pToInit                /* Preallocated space for the PCache */
09597 );
09598 
09599 /* Modify the page-size after the cache has been created. */
09600 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
09601 
09602 /* Return the size in bytes of a PCache object.  Used to preallocate
09603 ** storage space.
09604 */
09605 SQLITE_PRIVATE int sqlite3PcacheSize(void);
09606 
09607 /* One release per successful fetch.  Page is pinned until released.
09608 ** Reference counted. 
09609 */
09610 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
09611 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
09612 
09613 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
09614 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
09615 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
09616 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
09617 
09618 /* Change a page number.  Used by incr-vacuum. */
09619 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
09620 
09621 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
09622 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
09623 
09624 /* Get a list of all dirty pages in the cache, sorted by page number */
09625 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
09626 
09627 /* Reset and close the cache object */
09628 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
09629 
09630 /* Clear flags from pages of the page cache */
09631 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
09632 
09633 /* Discard the contents of the cache */
09634 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
09635 
09636 /* Return the total number of outstanding page references */
09637 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
09638 
09639 /* Increment the reference count of an existing page */
09640 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
09641 
09642 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
09643 
09644 /* Return the total number of pages stored in the cache */
09645 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
09646 
09647 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
09648 /* Iterate through all dirty pages currently stored in the cache. This
09649 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
09650 ** library is built.
09651 */
09652 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
09653 #endif
09654 
09655 /* Set and get the suggested cache-size for the specified pager-cache.
09656 **
09657 ** If no global maximum is configured, then the system attempts to limit
09658 ** the total number of pages cached by purgeable pager-caches to the sum
09659 ** of the suggested cache-sizes.
09660 */
09661 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
09662 #ifdef SQLITE_TEST
09663 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
09664 #endif
09665 
09666 /* Free up as much memory as possible from the page cache */
09667 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
09668 
09669 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
09670 /* Try to return memory used by the pcache module to the main memory heap */
09671 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
09672 #endif
09673 
09674 #ifdef SQLITE_TEST
09675 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
09676 #endif
09677 
09678 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
09679 
09680 #endif /* _PCACHE_H_ */
09681 
09682 /************** End of pcache.h **********************************************/
09683 /************** Continuing where we left off in sqliteInt.h ******************/
09684 
09685 /************** Include os.h in the middle of sqliteInt.h ********************/
09686 /************** Begin file os.h **********************************************/
09687 /*
09688 ** 2001 September 16
09689 **
09690 ** The author disclaims copyright to this source code.  In place of
09691 ** a legal notice, here is a blessing:
09692 **
09693 **    May you do good and not evil.
09694 **    May you find forgiveness for yourself and forgive others.
09695 **    May you share freely, never taking more than you give.
09696 **
09697 ******************************************************************************
09698 **
09699 ** This header file (together with is companion C source-code file
09700 ** "os.c") attempt to abstract the underlying operating system so that
09701 ** the SQLite library will work on both POSIX and windows systems.
09702 **
09703 ** This header file is #include-ed by sqliteInt.h and thus ends up
09704 ** being included by every source file.
09705 */
09706 #ifndef _SQLITE_OS_H_
09707 #define _SQLITE_OS_H_
09708 
09709 /*
09710 ** Figure out if we are dealing with Unix, Windows, or some other
09711 ** operating system.  After the following block of preprocess macros,
09712 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER 
09713 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
09714 ** three will be 0.
09715 */
09716 #if defined(SQLITE_OS_OTHER)
09717 # if SQLITE_OS_OTHER==1
09718 #   undef SQLITE_OS_UNIX
09719 #   define SQLITE_OS_UNIX 0
09720 #   undef SQLITE_OS_WIN
09721 #   define SQLITE_OS_WIN 0
09722 # else
09723 #   undef SQLITE_OS_OTHER
09724 # endif
09725 #endif
09726 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
09727 # define SQLITE_OS_OTHER 0
09728 # ifndef SQLITE_OS_WIN
09729 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
09730 #     define SQLITE_OS_WIN 1
09731 #     define SQLITE_OS_UNIX 0
09732 #   else
09733 #     define SQLITE_OS_WIN 0
09734 #     define SQLITE_OS_UNIX 1
09735 #  endif
09736 # else
09737 #  define SQLITE_OS_UNIX 0
09738 # endif
09739 #else
09740 # ifndef SQLITE_OS_WIN
09741 #  define SQLITE_OS_WIN 0
09742 # endif
09743 #endif
09744 
09745 #if SQLITE_OS_WIN
09746 # include <windows.h>
09747 #endif
09748 
09749 /*
09750 ** Determine if we are dealing with Windows NT.
09751 **
09752 ** We ought to be able to determine if we are compiling for win98 or winNT
09753 ** using the _WIN32_WINNT macro as follows:
09754 **
09755 ** #if defined(_WIN32_WINNT)
09756 ** # define SQLITE_OS_WINNT 1
09757 ** #else
09758 ** # define SQLITE_OS_WINNT 0
09759 ** #endif
09760 **
09761 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
09762 ** so the above test does not work.  We'll just assume that everything is
09763 ** winNT unless the programmer explicitly says otherwise by setting
09764 ** SQLITE_OS_WINNT to 0.
09765 */
09766 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
09767 # define SQLITE_OS_WINNT 1
09768 #endif
09769 
09770 /*
09771 ** Determine if we are dealing with WindowsCE - which has a much
09772 ** reduced API.
09773 */
09774 #if defined(_WIN32_WCE)
09775 # define SQLITE_OS_WINCE 1
09776 #else
09777 # define SQLITE_OS_WINCE 0
09778 #endif
09779 
09780 /*
09781 ** Determine if we are dealing with WinRT, which provides only a subset of
09782 ** the full Win32 API.
09783 */
09784 #if !defined(SQLITE_OS_WINRT)
09785 # define SQLITE_OS_WINRT 0
09786 #endif
09787 
09788 /* If the SET_FULLSYNC macro is not defined above, then make it
09789 ** a no-op
09790 */
09791 #ifndef SET_FULLSYNC
09792 # define SET_FULLSYNC(x,y)
09793 #endif
09794 
09795 /*
09796 ** The default size of a disk sector
09797 */
09798 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
09799 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
09800 #endif
09801 
09802 /*
09803 ** Temporary files are named starting with this prefix followed by 16 random
09804 ** alphanumeric characters, and no file extension. They are stored in the
09805 ** OS's standard temporary file directory, and are deleted prior to exit.
09806 ** If sqlite is being embedded in another program, you may wish to change the
09807 ** prefix to reflect your program's name, so that if your program exits
09808 ** prematurely, old temporary files can be easily identified. This can be done
09809 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
09810 **
09811 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
09812 ** Mcafee started using SQLite in their anti-virus product and it
09813 ** started putting files with the "sqlite" name in the c:/temp folder.
09814 ** This annoyed many windows users.  Those users would then do a 
09815 ** Google search for "sqlite", find the telephone numbers of the
09816 ** developers and call to wake them up at night and complain.
09817 ** For this reason, the default name prefix is changed to be "sqlite" 
09818 ** spelled backwards.  So the temp files are still identified, but
09819 ** anybody smart enough to figure out the code is also likely smart
09820 ** enough to know that calling the developer will not help get rid
09821 ** of the file.
09822 */
09823 #ifndef SQLITE_TEMP_FILE_PREFIX
09824 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
09825 #endif
09826 
09827 /*
09828 ** The following values may be passed as the second argument to
09829 ** sqlite3OsLock(). The various locks exhibit the following semantics:
09830 **
09831 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
09832 ** RESERVED:  A single process may hold a RESERVED lock on a file at
09833 **            any time. Other processes may hold and obtain new SHARED locks.
09834 ** PENDING:   A single process may hold a PENDING lock on a file at
09835 **            any one time. Existing SHARED locks may persist, but no new
09836 **            SHARED locks may be obtained by other processes.
09837 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
09838 **
09839 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
09840 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
09841 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
09842 ** sqlite3OsLock().
09843 */
09844 #define NO_LOCK         0
09845 #define SHARED_LOCK     1
09846 #define RESERVED_LOCK   2
09847 #define PENDING_LOCK    3
09848 #define EXCLUSIVE_LOCK  4
09849 
09850 /*
09851 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
09852 **
09853 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
09854 ** those functions are not available.  So we use only LockFile() and
09855 ** UnlockFile().
09856 **
09857 ** LockFile() prevents not just writing but also reading by other processes.
09858 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
09859 ** byte out of a specific range of bytes. The lock byte is obtained at 
09860 ** random so two separate readers can probably access the file at the 
09861 ** same time, unless they are unlucky and choose the same lock byte.
09862 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
09863 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
09864 ** a single byte of the file that is designated as the reserved lock byte.
09865 ** A PENDING_LOCK is obtained by locking a designated byte different from
09866 ** the RESERVED_LOCK byte.
09867 **
09868 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
09869 ** which means we can use reader/writer locks.  When reader/writer locks
09870 ** are used, the lock is placed on the same range of bytes that is used
09871 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
09872 ** will support two or more Win95 readers or two or more WinNT readers.
09873 ** But a single Win95 reader will lock out all WinNT readers and a single
09874 ** WinNT reader will lock out all other Win95 readers.
09875 **
09876 ** The following #defines specify the range of bytes used for locking.
09877 ** SHARED_SIZE is the number of bytes available in the pool from which
09878 ** a random byte is selected for a shared lock.  The pool of bytes for
09879 ** shared locks begins at SHARED_FIRST. 
09880 **
09881 ** The same locking strategy and
09882 ** byte ranges are used for Unix.  This leaves open the possiblity of having
09883 ** clients on win95, winNT, and unix all talking to the same shared file
09884 ** and all locking correctly.  To do so would require that samba (or whatever
09885 ** tool is being used for file sharing) implements locks correctly between
09886 ** windows and unix.  I'm guessing that isn't likely to happen, but by
09887 ** using the same locking range we are at least open to the possibility.
09888 **
09889 ** Locking in windows is manditory.  For this reason, we cannot store
09890 ** actual data in the bytes used for locking.  The pager never allocates
09891 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
09892 ** that all locks will fit on a single page even at the minimum page size.
09893 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
09894 ** is set high so that we don't have to allocate an unused page except
09895 ** for very large databases.  But one should test the page skipping logic 
09896 ** by setting PENDING_BYTE low and running the entire regression suite.
09897 **
09898 ** Changing the value of PENDING_BYTE results in a subtly incompatible
09899 ** file format.  Depending on how it is changed, you might not notice
09900 ** the incompatibility right away, even running a full regression test.
09901 ** The default location of PENDING_BYTE is the first byte past the
09902 ** 1GB boundary.
09903 **
09904 */
09905 #ifdef SQLITE_OMIT_WSD
09906 # define PENDING_BYTE     (0x40000000)
09907 #else
09908 # define PENDING_BYTE      sqlite3PendingByte
09909 #endif
09910 #define RESERVED_BYTE     (PENDING_BYTE+1)
09911 #define SHARED_FIRST      (PENDING_BYTE+2)
09912 #define SHARED_SIZE       510
09913 
09914 /*
09915 ** Wrapper around OS specific sqlite3_os_init() function.
09916 */
09917 SQLITE_PRIVATE int sqlite3OsInit(void);
09918 
09919 /* 
09920 ** Functions for accessing sqlite3_file methods 
09921 */
09922 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
09923 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
09924 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
09925 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
09926 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
09927 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
09928 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
09929 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
09930 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
09931 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
09932 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
09933 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
09934 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
09935 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
09936 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
09937 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
09938 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
09939 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
09940 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
09941 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
09942 
09943 
09944 /* 
09945 ** Functions for accessing sqlite3_vfs methods 
09946 */
09947 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
09948 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
09949 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
09950 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
09951 #ifndef SQLITE_OMIT_LOAD_EXTENSION
09952 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
09953 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
09954 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
09955 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
09956 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
09957 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
09958 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
09959 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
09960 
09961 /*
09962 ** Convenience functions for opening and closing files using 
09963 ** sqlite3_malloc() to obtain space for the file-handle structure.
09964 */
09965 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
09966 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
09967 
09968 #endif /* _SQLITE_OS_H_ */
09969 
09970 /************** End of os.h **************************************************/
09971 /************** Continuing where we left off in sqliteInt.h ******************/
09972 /************** Include mutex.h in the middle of sqliteInt.h *****************/
09973 /************** Begin file mutex.h *******************************************/
09974 /*
09975 ** 2007 August 28
09976 **
09977 ** The author disclaims copyright to this source code.  In place of
09978 ** a legal notice, here is a blessing:
09979 **
09980 **    May you do good and not evil.
09981 **    May you find forgiveness for yourself and forgive others.
09982 **    May you share freely, never taking more than you give.
09983 **
09984 *************************************************************************
09985 **
09986 ** This file contains the common header for all mutex implementations.
09987 ** The sqliteInt.h header #includes this file so that it is available
09988 ** to all source files.  We break it out in an effort to keep the code
09989 ** better organized.
09990 **
09991 ** NOTE:  source files should *not* #include this header file directly.
09992 ** Source files should #include the sqliteInt.h file and let that file
09993 ** include this one indirectly.
09994 */
09995 
09996 
09997 /*
09998 ** Figure out what version of the code to use.  The choices are
09999 **
10000 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
10001 **                             mutexes implemention cannot be overridden
10002 **                             at start-time.
10003 **
10004 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
10005 **                             mutual exclusion is provided.  But this
10006 **                             implementation can be overridden at
10007 **                             start-time.
10008 **
10009 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
10010 **
10011 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
10012 */
10013 #if !SQLITE_THREADSAFE
10014 # define SQLITE_MUTEX_OMIT
10015 #endif
10016 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10017 #  if SQLITE_OS_UNIX
10018 #    define SQLITE_MUTEX_PTHREADS
10019 #  elif SQLITE_OS_WIN
10020 #    define SQLITE_MUTEX_W32
10021 #  else
10022 #    define SQLITE_MUTEX_NOOP
10023 #  endif
10024 #endif
10025 
10026 #ifdef SQLITE_MUTEX_OMIT
10027 /*
10028 ** If this is a no-op implementation, implement everything as macros.
10029 */
10030 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
10031 #define sqlite3_mutex_free(X)
10032 #define sqlite3_mutex_enter(X)    
10033 #define sqlite3_mutex_try(X)      SQLITE_OK
10034 #define sqlite3_mutex_leave(X)    
10035 #define sqlite3_mutex_held(X)     ((void)(X),1)
10036 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
10037 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
10038 #define sqlite3MutexInit()        SQLITE_OK
10039 #define sqlite3MutexEnd()
10040 #define MUTEX_LOGIC(X)
10041 #else
10042 #define MUTEX_LOGIC(X)            X
10043 #endif /* defined(SQLITE_MUTEX_OMIT) */
10044 
10045 /************** End of mutex.h ***********************************************/
10046 /************** Continuing where we left off in sqliteInt.h ******************/
10047 
10048 
10049 /*
10050 ** Each database file to be accessed by the system is an instance
10051 ** of the following structure.  There are normally two of these structures
10052 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
10053 ** aDb[1] is the database file used to hold temporary tables.  Additional
10054 ** databases may be attached.
10055 */
10056 struct Db {
10057   char *zName;         /* Name of this database */
10058   Btree *pBt;          /* The B*Tree structure for this database file */
10059   u8 safety_level;     /* How aggressive at syncing data to disk */
10060   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
10061 };
10062 
10063 /*
10064 ** An instance of the following structure stores a database schema.
10065 **
10066 ** Most Schema objects are associated with a Btree.  The exception is
10067 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10068 ** In shared cache mode, a single Schema object can be shared by multiple
10069 ** Btrees that refer to the same underlying BtShared object.
10070 ** 
10071 ** Schema objects are automatically deallocated when the last Btree that
10072 ** references them is destroyed.   The TEMP Schema is manually freed by
10073 ** sqlite3_close().
10074 *
10075 ** A thread must be holding a mutex on the corresponding Btree in order
10076 ** to access Schema content.  This implies that the thread must also be
10077 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10078 ** For a TEMP Schema, only the connection mutex is required.
10079 */
10080 struct Schema {
10081   int schema_cookie;   /* Database schema version number for this file */
10082   int iGeneration;     /* Generation counter.  Incremented with each change */
10083   Hash tblHash;        /* All tables indexed by name */
10084   Hash idxHash;        /* All (named) indices indexed by name */
10085   Hash trigHash;       /* All triggers indexed by name */
10086   Hash fkeyHash;       /* All foreign keys by referenced table name */
10087   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
10088   u8 file_format;      /* Schema format version for this file */
10089   u8 enc;              /* Text encoding used by this database */
10090   u16 flags;           /* Flags associated with this schema */
10091   int cache_size;      /* Number of pages to use in the cache */
10092 };
10093 
10094 /*
10095 ** These macros can be used to test, set, or clear bits in the 
10096 ** Db.pSchema->flags field.
10097 */
10098 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
10099 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
10100 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
10101 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
10102 
10103 /*
10104 ** Allowed values for the DB.pSchema->flags field.
10105 **
10106 ** The DB_SchemaLoaded flag is set after the database schema has been
10107 ** read into internal hash tables.
10108 **
10109 ** DB_UnresetViews means that one or more views have column names that
10110 ** have been filled out.  If the schema changes, these column names might
10111 ** changes and so the view will need to be reset.
10112 */
10113 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
10114 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
10115 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
10116 
10117 /*
10118 ** The number of different kinds of things that can be limited
10119 ** using the sqlite3_limit() interface.
10120 */
10121 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
10122 
10123 /*
10124 ** Lookaside malloc is a set of fixed-size buffers that can be used
10125 ** to satisfy small transient memory allocation requests for objects
10126 ** associated with a particular database connection.  The use of
10127 ** lookaside malloc provides a significant performance enhancement
10128 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10129 ** SQL statements.
10130 **
10131 ** The Lookaside structure holds configuration information about the
10132 ** lookaside malloc subsystem.  Each available memory allocation in
10133 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10134 ** objects.
10135 **
10136 ** Lookaside allocations are only allowed for objects that are associated
10137 ** with a particular database connection.  Hence, schema information cannot
10138 ** be stored in lookaside because in shared cache mode the schema information
10139 ** is shared by multiple database connections.  Therefore, while parsing
10140 ** schema information, the Lookaside.bEnabled flag is cleared so that
10141 ** lookaside allocations are not used to construct the schema objects.
10142 */
10143 struct Lookaside {
10144   u16 sz;                 /* Size of each buffer in bytes */
10145   u8 bEnabled;            /* False to disable new lookaside allocations */
10146   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10147   int nOut;               /* Number of buffers currently checked out */
10148   int mxOut;              /* Highwater mark for nOut */
10149   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10150   LookasideSlot *pFree;   /* List of available buffers */
10151   void *pStart;           /* First byte of available memory space */
10152   void *pEnd;             /* First byte past end of available space */
10153 };
10154 struct LookasideSlot {
10155   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10156 };
10157 
10158 /*
10159 ** A hash table for function definitions.
10160 **
10161 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10162 ** Collisions are on the FuncDef.pHash chain.
10163 */
10164 struct FuncDefHash {
10165   FuncDef *a[23];       /* Hash table for functions */
10166 };
10167 
10168 /*
10169 ** Each database connection is an instance of the following structure.
10170 */
10171 struct sqlite3 {
10172   sqlite3_vfs *pVfs;            /* OS Interface */
10173   struct Vdbe *pVdbe;           /* List of active virtual machines */
10174   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10175   sqlite3_mutex *mutex;         /* Connection mutex */
10176   Db *aDb;                      /* All backends */
10177   int nDb;                      /* Number of backends currently in use */
10178   int flags;                    /* Miscellaneous flags. See below */
10179   i64 lastRowid;                /* ROWID of most recent insert (see above) */
10180   i64 szMmap;                   /* Default mmap_size setting */
10181   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10182   int errCode;                  /* Most recent error code (SQLITE_*) */
10183   int errMask;                  /* & result codes with this before returning */
10184   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10185   u8 autoCommit;                /* The auto-commit flag. */
10186   u8 temp_store;                /* 1: file 2: memory 0: default */
10187   u8 mallocFailed;              /* True if we have seen a malloc failure */
10188   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10189   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10190   u8 suppressErr;               /* Do not issue error messages if true */
10191   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10192   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10193   int nextPagesize;             /* Pagesize after VACUUM if >0 */
10194   u32 magic;                    /* Magic number for detect library misuse */
10195   int nChange;                  /* Value returned by sqlite3_changes() */
10196   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10197   int aLimit[SQLITE_N_LIMIT];   /* Limits */
10198   struct sqlite3InitInfo {      /* Information used during initialization */
10199     int newTnum;                /* Rootpage of table being initialized */
10200     u8 iDb;                     /* Which db file is being initialized */
10201     u8 busy;                    /* TRUE if currently initializing */
10202     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10203   } init;
10204   int nVdbeActive;              /* Number of VDBEs currently running */
10205   int nVdbeRead;                /* Number of active VDBEs that read or write */
10206   int nVdbeWrite;               /* Number of active VDBEs that read and write */
10207   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
10208   int nExtension;               /* Number of loaded extensions */
10209   void **aExtension;            /* Array of shared library handles */
10210   void (*xTrace)(void*,const char*);        /* Trace function */
10211   void *pTraceArg;                          /* Argument to the trace function */
10212   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10213   void *pProfileArg;                        /* Argument to profile function */
10214   void *pCommitArg;                 /* Argument to xCommitCallback() */   
10215   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10216   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
10217   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10218   void *pUpdateArg;
10219   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10220 #ifndef SQLITE_OMIT_WAL
10221   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10222   void *pWalArg;
10223 #endif
10224   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10225   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10226   void *pCollNeededArg;
10227   sqlite3_value *pErr;          /* Most recent error message */
10228   union {
10229     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10230     double notUsed1;            /* Spacer */
10231   } u1;
10232   Lookaside lookaside;          /* Lookaside malloc configuration */
10233 #ifndef SQLITE_OMIT_AUTHORIZATION
10234   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10235                                 /* Access authorization function */
10236   void *pAuthArg;               /* 1st argument to the access auth function */
10237 #endif
10238 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10239   int (*xProgress)(void *);     /* The progress callback */
10240   void *pProgressArg;           /* Argument to the progress callback */
10241   unsigned nProgressOps;        /* Number of opcodes for progress callback */
10242 #endif
10243 #ifndef SQLITE_OMIT_VIRTUALTABLE
10244   int nVTrans;                  /* Allocated size of aVTrans */
10245   Hash aModule;                 /* populated by sqlite3_create_module() */
10246   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10247   VTable **aVTrans;             /* Virtual tables with open transactions */
10248   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10249 #endif
10250   FuncDefHash aFunc;            /* Hash table of connection functions */
10251   Hash aCollSeq;                /* All collating sequences */
10252   BusyHandler busyHandler;      /* Busy callback */
10253   Db aDbStatic[2];              /* Static space for the 2 default backends */
10254   Savepoint *pSavepoint;        /* List of active savepoints */
10255   int busyTimeout;              /* Busy handler timeout, in msec */
10256   int nSavepoint;               /* Number of non-transaction savepoints */
10257   int nStatement;               /* Number of nested statement-transactions  */
10258   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10259   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
10260   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10261 
10262 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10263   /* The following variables are all protected by the STATIC_MASTER 
10264   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
10265   **
10266   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10267   ** unlock so that it can proceed.
10268   **
10269   ** When X.pBlockingConnection==Y, that means that something that X tried
10270   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10271   ** held by Y.
10272   */
10273   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10274   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10275   void *pUnlockArg;                     /* Argument to xUnlockNotify */
10276   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10277   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10278 #endif
10279 };
10280 
10281 /*
10282 ** A macro to discover the encoding of a database.
10283 */
10284 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10285 
10286 /*
10287 ** Possible values for the sqlite3.flags.
10288 */
10289 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10290 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10291 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
10292 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
10293 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
10294 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
10295 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
10296 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
10297                                           /*   DELETE, or UPDATE and return */
10298                                           /*   the count using a callback. */
10299 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
10300                                           /*   result set is empty */
10301 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
10302 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
10303 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
10304 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
10305 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
10306 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
10307 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
10308 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
10309 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
10310 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
10311 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
10312 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
10313 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
10314 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
10315 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
10316 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
10317 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
10318 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
10319 
10320 
10321 /*
10322 ** Bits of the sqlite3.dbOptFlags field that are used by the
10323 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10324 ** selectively disable various optimizations.
10325 */
10326 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10327 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10328 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10329 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10330 #define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10331 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10332 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10333 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10334 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10335 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
10336 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
10337 #define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
10338 #define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
10339 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10340 
10341 /*
10342 ** Macros for testing whether or not optimizations are enabled or disabled.
10343 */
10344 #ifndef SQLITE_OMIT_BUILTIN_TEST
10345 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10346 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10347 #else
10348 #define OptimizationDisabled(db, mask)  0
10349 #define OptimizationEnabled(db, mask)   1
10350 #endif
10351 
10352 /*
10353 ** Return true if it OK to factor constant expressions into the initialization
10354 ** code. The argument is a Parse object for the code generator.
10355 */
10356 #define ConstFactorOk(P) \
10357   ((P)->cookieGoto>0 && OptimizationEnabled((P)->db,SQLITE_FactorOutConst))
10358 
10359 /*
10360 ** Possible values for the sqlite.magic field.
10361 ** The numbers are obtained at random and have no special meaning, other
10362 ** than being distinct from one another.
10363 */
10364 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10365 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10366 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10367 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10368 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10369 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10370 
10371 /*
10372 ** Each SQL function is defined by an instance of the following
10373 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10374 ** hash table.  When multiple functions have the same name, the hash table
10375 ** points to a linked list of these structures.
10376 */
10377 struct FuncDef {
10378   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10379   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
10380   void *pUserData;     /* User data parameter */
10381   FuncDef *pNext;      /* Next function with same name */
10382   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10383   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10384   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10385   char *zName;         /* SQL name of the function. */
10386   FuncDef *pHash;      /* Next with a different name but the same hash */
10387   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10388 };
10389 
10390 /*
10391 ** This structure encapsulates a user-function destructor callback (as
10392 ** configured using create_function_v2()) and a reference counter. When
10393 ** create_function_v2() is called to create a function with a destructor,
10394 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
10395 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10396 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10397 ** member of each of the new FuncDef objects is set to point to the allocated
10398 ** FuncDestructor.
10399 **
10400 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10401 ** count on this object is decremented. When it reaches 0, the destructor
10402 ** is invoked and the FuncDestructor structure freed.
10403 */
10404 struct FuncDestructor {
10405   int nRef;
10406   void (*xDestroy)(void *);
10407   void *pUserData;
10408 };
10409 
10410 /*
10411 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10412 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10413 ** are assert() statements in the code to verify this.
10414 */
10415 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10416 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
10417 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
10418 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
10419 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10420 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
10421 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
10422 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
10423 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10424 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10425 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10426 
10427 /*
10428 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10429 ** used to create the initializers for the FuncDef structures.
10430 **
10431 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10432 **     Used to create a scalar function definition of a function zName 
10433 **     implemented by C function xFunc that accepts nArg arguments. The
10434 **     value passed as iArg is cast to a (void*) and made available
10435 **     as the user-data (sqlite3_user_data()) for the function. If 
10436 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10437 **
10438 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10439 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10440 **
10441 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10442 **     Used to create an aggregate function definition implemented by
10443 **     the C functions xStep and xFinal. The first four parameters
10444 **     are interpreted in the same way as the first 4 parameters to
10445 **     FUNCTION().
10446 **
10447 **   LIKEFUNC(zName, nArg, pArg, flags)
10448 **     Used to create a scalar function definition of a function zName 
10449 **     that accepts nArg arguments and is implemented by a call to C 
10450 **     function likeFunc. Argument pArg is cast to a (void *) and made
10451 **     available as the function user-data (sqlite3_user_data()). The
10452 **     FuncDef.flags variable is set to the value passed as the flags
10453 **     parameter.
10454 */
10455 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10456   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10457    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10458 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10459   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10460    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10461 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10462   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10463    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10464 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10465   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10466    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10467 #define LIKEFUNC(zName, nArg, arg, flags) \
10468   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10469    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10470 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10471   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10472    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10473 
10474 /*
10475 ** All current savepoints are stored in a linked list starting at
10476 ** sqlite3.pSavepoint. The first element in the list is the most recently
10477 ** opened savepoint. Savepoints are added to the list by the vdbe
10478 ** OP_Savepoint instruction.
10479 */
10480 struct Savepoint {
10481   char *zName;                        /* Savepoint name (nul-terminated) */
10482   i64 nDeferredCons;                  /* Number of deferred fk violations */
10483   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
10484   Savepoint *pNext;                   /* Parent savepoint (if any) */
10485 };
10486 
10487 /*
10488 ** The following are used as the second parameter to sqlite3Savepoint(),
10489 ** and as the P1 argument to the OP_Savepoint instruction.
10490 */
10491 #define SAVEPOINT_BEGIN      0
10492 #define SAVEPOINT_RELEASE    1
10493 #define SAVEPOINT_ROLLBACK   2
10494 
10495 
10496 /*
10497 ** Each SQLite module (virtual table definition) is defined by an
10498 ** instance of the following structure, stored in the sqlite3.aModule
10499 ** hash table.
10500 */
10501 struct Module {
10502   const sqlite3_module *pModule;       /* Callback pointers */
10503   const char *zName;                   /* Name passed to create_module() */
10504   void *pAux;                          /* pAux passed to create_module() */
10505   void (*xDestroy)(void *);            /* Module destructor function */
10506 };
10507 
10508 /*
10509 ** information about each column of an SQL table is held in an instance
10510 ** of this structure.
10511 */
10512 struct Column {
10513   char *zName;     /* Name of this column */
10514   Expr *pDflt;     /* Default value of this column */
10515   char *zDflt;     /* Original text of the default value */
10516   char *zType;     /* Data type for this column */
10517   char *zColl;     /* Collating sequence.  If NULL, use the default */
10518   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10519   char affinity;   /* One of the SQLITE_AFF_... values */
10520   u8 szEst;        /* Estimated size of this column.  INT==1 */
10521   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
10522 };
10523 
10524 /* Allowed values for Column.colFlags:
10525 */
10526 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10527 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10528 
10529 /*
10530 ** A "Collating Sequence" is defined by an instance of the following
10531 ** structure. Conceptually, a collating sequence consists of a name and
10532 ** a comparison routine that defines the order of that sequence.
10533 **
10534 ** If CollSeq.xCmp is NULL, it means that the
10535 ** collating sequence is undefined.  Indices built on an undefined
10536 ** collating sequence may not be read or written.
10537 */
10538 struct CollSeq {
10539   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10540   u8 enc;               /* Text encoding handled by xCmp() */
10541   void *pUser;          /* First argument to xCmp() */
10542   int (*xCmp)(void*,int, const void*, int, const void*);
10543   void (*xDel)(void*);  /* Destructor for pUser */
10544 };
10545 
10546 /*
10547 ** A sort order can be either ASC or DESC.
10548 */
10549 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10550 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10551 
10552 /*
10553 ** Column affinity types.
10554 **
10555 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10556 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10557 ** the speed a little by numbering the values consecutively.  
10558 **
10559 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10560 ** when multiple affinity types are concatenated into a string and
10561 ** used as the P4 operand, they will be more readable.
10562 **
10563 ** Note also that the numeric types are grouped together so that testing
10564 ** for a numeric type is a single comparison.
10565 */
10566 #define SQLITE_AFF_TEXT     'a'
10567 #define SQLITE_AFF_NONE     'b'
10568 #define SQLITE_AFF_NUMERIC  'c'
10569 #define SQLITE_AFF_INTEGER  'd'
10570 #define SQLITE_AFF_REAL     'e'
10571 
10572 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10573 
10574 /*
10575 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10576 ** affinity value. 
10577 */
10578 #define SQLITE_AFF_MASK     0x67
10579 
10580 /*
10581 ** Additional bit values that can be ORed with an affinity without
10582 ** changing the affinity.
10583 */
10584 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10585 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10586 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10587 
10588 /*
10589 ** An object of this type is created for each virtual table present in
10590 ** the database schema. 
10591 **
10592 ** If the database schema is shared, then there is one instance of this
10593 ** structure for each database connection (sqlite3*) that uses the shared
10594 ** schema. This is because each database connection requires its own unique
10595 ** instance of the sqlite3_vtab* handle used to access the virtual table 
10596 ** implementation. sqlite3_vtab* handles can not be shared between 
10597 ** database connections, even when the rest of the in-memory database 
10598 ** schema is shared, as the implementation often stores the database
10599 ** connection handle passed to it via the xConnect() or xCreate() method
10600 ** during initialization internally. This database connection handle may
10601 ** then be used by the virtual table implementation to access real tables 
10602 ** within the database. So that they appear as part of the callers 
10603 ** transaction, these accesses need to be made via the same database 
10604 ** connection as that used to execute SQL operations on the virtual table.
10605 **
10606 ** All VTable objects that correspond to a single table in a shared
10607 ** database schema are initially stored in a linked-list pointed to by
10608 ** the Table.pVTable member variable of the corresponding Table object.
10609 ** When an sqlite3_prepare() operation is required to access the virtual
10610 ** table, it searches the list for the VTable that corresponds to the
10611 ** database connection doing the preparing so as to use the correct
10612 ** sqlite3_vtab* handle in the compiled query.
10613 **
10614 ** When an in-memory Table object is deleted (for example when the
10615 ** schema is being reloaded for some reason), the VTable objects are not 
10616 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
10617 ** immediately. Instead, they are moved from the Table.pVTable list to
10618 ** another linked list headed by the sqlite3.pDisconnect member of the
10619 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
10620 ** next time a statement is prepared using said sqlite3*. This is done
10621 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10622 ** Refer to comments above function sqlite3VtabUnlockList() for an
10623 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10624 ** list without holding the corresponding sqlite3.mutex mutex.
10625 **
10626 ** The memory for objects of this type is always allocated by 
10627 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
10628 ** the first argument.
10629 */
10630 struct VTable {
10631   sqlite3 *db;              /* Database connection associated with this table */
10632   Module *pMod;             /* Pointer to module implementation */
10633   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10634   int nRef;                 /* Number of pointers to this structure */
10635   u8 bConstraint;           /* True if constraints are supported */
10636   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10637   VTable *pNext;            /* Next in linked list (see above) */
10638 };
10639 
10640 /*
10641 ** Each SQL table is represented in memory by an instance of the
10642 ** following structure.
10643 **
10644 ** Table.zName is the name of the table.  The case of the original
10645 ** CREATE TABLE statement is stored, but case is not significant for
10646 ** comparisons.
10647 **
10648 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10649 ** pointer to an array of Column structures, one for each column.
10650 **
10651 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10652 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10653 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10654 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10655 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10656 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10657 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10658 **
10659 ** Table.tnum is the page number for the root BTree page of the table in the
10660 ** database file.  If Table.iDb is the index of the database table backend
10661 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10662 ** holds temporary tables and indices.  If TF_Ephemeral is set
10663 ** then the table is stored in a file that is automatically deleted
10664 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
10665 ** refers VDBE cursor number that holds the table open, not to the root
10666 ** page number.  Transient tables are used to hold the results of a
10667 ** sub-query that appears instead of a real table name in the FROM clause 
10668 ** of a SELECT statement.
10669 */
10670 struct Table {
10671   char *zName;         /* Name of the table or view */
10672   Column *aCol;        /* Information about each column */
10673   Index *pIndex;       /* List of SQL indexes on this table. */
10674   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10675   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10676   char *zColAff;       /* String defining the affinity of each column */
10677 #ifndef SQLITE_OMIT_CHECK
10678   ExprList *pCheck;    /* All CHECK constraints */
10679 #endif
10680   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10681   int tnum;            /* Root BTree node for this table (see note above) */
10682   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10683   i16 nCol;            /* Number of columns in this table */
10684   u16 nRef;            /* Number of pointers to this Table */
10685   LogEst szTabRow;     /* Estimated size of each table row in bytes */
10686   u8 tabFlags;         /* Mask of TF_* values */
10687   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10688 #ifndef SQLITE_OMIT_ALTERTABLE
10689   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10690 #endif
10691 #ifndef SQLITE_OMIT_VIRTUALTABLE
10692   int nModuleArg;      /* Number of arguments to the module */
10693   char **azModuleArg;  /* Text of all module args. [0] is module name */
10694   VTable *pVTable;     /* List of VTable objects. */
10695 #endif
10696   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10697   Schema *pSchema;     /* Schema that contains this table */
10698   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10699 };
10700 
10701 /*
10702 ** Allowed values for Tabe.tabFlags.
10703 */
10704 #define TF_Readonly        0x01    /* Read-only system table */
10705 #define TF_Ephemeral       0x02    /* An ephemeral table */
10706 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10707 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10708 #define TF_Virtual         0x10    /* Is a virtual table */
10709 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
10710 
10711 
10712 /*
10713 ** Test to see whether or not a table is a virtual table.  This is
10714 ** done as a macro so that it will be optimized out when virtual
10715 ** table support is omitted from the build.
10716 */
10717 #ifndef SQLITE_OMIT_VIRTUALTABLE
10718 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10719 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10720 #else
10721 #  define IsVirtual(X)      0
10722 #  define IsHiddenColumn(X) 0
10723 #endif
10724 
10725 /* Does the table have a rowid */
10726 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
10727 
10728 /*
10729 ** Each foreign key constraint is an instance of the following structure.
10730 **
10731 ** A foreign key is associated with two tables.  The "from" table is
10732 ** the table that contains the REFERENCES clause that creates the foreign
10733 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10734 ** Consider this example:
10735 **
10736 **     CREATE TABLE ex1(
10737 **       a INTEGER PRIMARY KEY,
10738 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10739 **     );
10740 **
10741 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10742 ** Equivalent names:
10743 **
10744 **     from-table == child-table
10745 **       to-table == parent-table
10746 **
10747 ** Each REFERENCES clause generates an instance of the following structure
10748 ** which is attached to the from-table.  The to-table need not exist when
10749 ** the from-table is created.  The existence of the to-table is not checked.
10750 **
10751 ** The list of all parents for child Table X is held at X.pFKey.
10752 **
10753 ** A list of all children for a table named Z (which might not even exist)
10754 ** is held in Schema.fkeyHash with a hash key of Z.
10755 */
10756 struct FKey {
10757   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10758   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
10759   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10760   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
10761   FKey *pPrevTo;    /* Previous with the same zTo */
10762   int nCol;         /* Number of columns in this key */
10763   /* EV: R-30323-21917 */
10764   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
10765   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
10766   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
10767   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
10768     int iFrom;            /* Index of column in pFrom */
10769     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
10770   } aCol[1];            /* One entry for each of nCol columns */
10771 };
10772 
10773 /*
10774 ** SQLite supports many different ways to resolve a constraint
10775 ** error.  ROLLBACK processing means that a constraint violation
10776 ** causes the operation in process to fail and for the current transaction
10777 ** to be rolled back.  ABORT processing means the operation in process
10778 ** fails and any prior changes from that one operation are backed out,
10779 ** but the transaction is not rolled back.  FAIL processing means that
10780 ** the operation in progress stops and returns an error code.  But prior
10781 ** changes due to the same operation are not backed out and no rollback
10782 ** occurs.  IGNORE means that the particular row that caused the constraint
10783 ** error is not inserted or updated.  Processing continues and no error
10784 ** is returned.  REPLACE means that preexisting database rows that caused
10785 ** a UNIQUE constraint violation are removed so that the new insert or
10786 ** update can proceed.  Processing continues and no error is reported.
10787 **
10788 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10789 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10790 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10791 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10792 ** referenced table row is propagated into the row that holds the
10793 ** foreign key.
10794 ** 
10795 ** The following symbolic values are used to record which type
10796 ** of action to take.
10797 */
10798 #define OE_None     0   /* There is no constraint to check */
10799 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10800 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10801 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10802 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10803 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10804 
10805 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10806 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10807 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10808 #define OE_Cascade  9   /* Cascade the changes */
10809 
10810 #define OE_Default  10  /* Do whatever the default action is */
10811 
10812 
10813 /*
10814 ** An instance of the following structure is passed as the first
10815 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10816 ** comparison of the two index keys.
10817 **
10818 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
10819 ** are nField slots for the columns of an index then one extra slot
10820 ** for the rowid at the end.
10821 */
10822 struct KeyInfo {
10823   u32 nRef;           /* Number of references to this KeyInfo object */
10824   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10825   u16 nField;         /* Number of key columns in the index */
10826   u16 nXField;        /* Number of columns beyond the key columns */
10827   sqlite3 *db;        /* The database connection */
10828   u8 *aSortOrder;     /* Sort order for each column. */
10829   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10830 };
10831 
10832 /*
10833 ** An instance of the following structure holds information about a
10834 ** single index record that has already been parsed out into individual
10835 ** values.
10836 **
10837 ** A record is an object that contains one or more fields of data.
10838 ** Records are used to store the content of a table row and to store
10839 ** the key of an index.  A blob encoding of a record is created by
10840 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10841 ** OP_Column opcode.
10842 **
10843 ** This structure holds a record that has already been disassembled
10844 ** into its constituent fields.
10845 */
10846 struct UnpackedRecord {
10847   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10848   u16 nField;         /* Number of entries in apMem[] */
10849   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10850   Mem *aMem;          /* Values */
10851 };
10852 
10853 /*
10854 ** Allowed values of UnpackedRecord.flags
10855 */
10856 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10857 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10858 
10859 /*
10860 ** Each SQL index is represented in memory by an
10861 ** instance of the following structure.
10862 **
10863 ** The columns of the table that are to be indexed are described
10864 ** by the aiColumn[] field of this structure.  For example, suppose
10865 ** we have the following table and index:
10866 **
10867 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10868 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10869 **
10870 ** In the Table structure describing Ex1, nCol==3 because there are
10871 ** three columns in the table.  In the Index structure describing
10872 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10873 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10874 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10875 ** The second column to be indexed (c1) has an index of 0 in
10876 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10877 **
10878 ** The Index.onError field determines whether or not the indexed columns
10879 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10880 ** it means this is not a unique index.  Otherwise it is a unique index
10881 ** and the value of Index.onError indicate the which conflict resolution 
10882 ** algorithm to employ whenever an attempt is made to insert a non-unique
10883 ** element.
10884 */
10885 struct Index {
10886   char *zName;             /* Name of this index */
10887   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
10888   tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
10889   Table *pTable;           /* The SQL table being indexed */
10890   char *zColAff;           /* String defining the affinity of each column */
10891   Index *pNext;            /* The next index associated with the same table */
10892   Schema *pSchema;         /* Schema containing this index */
10893   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
10894   char **azColl;           /* Array of collation sequence names for index */
10895   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
10896   KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
10897   int tnum;                /* DB Page containing root of this index */
10898   LogEst szIdxRow;         /* Estimated average row size in bytes */
10899   u16 nKeyCol;             /* Number of columns forming the key */
10900   u16 nColumn;             /* Number of columns stored in the index */
10901   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10902   unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10903   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
10904   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
10905   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
10906   unsigned isCovering:1;   /* True if this is a covering index */
10907 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
10908   int nSample;             /* Number of elements in aSample[] */
10909   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
10910   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
10911   IndexSample *aSample;    /* Samples of the left-most key */
10912 #endif
10913 };
10914 
10915 /*
10916 ** Each sample stored in the sqlite_stat3 table is represented in memory 
10917 ** using a structure of this type.  See documentation at the top of the
10918 ** analyze.c source file for additional information.
10919 */
10920 struct IndexSample {
10921   void *p;          /* Pointer to sampled record */
10922   int n;            /* Size of record in bytes */
10923   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
10924   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
10925   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
10926 };
10927 
10928 /*
10929 ** Each token coming out of the lexer is an instance of
10930 ** this structure.  Tokens are also used as part of an expression.
10931 **
10932 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10933 ** may contain random values.  Do not make any assumptions about Token.dyn
10934 ** and Token.n when Token.z==0.
10935 */
10936 struct Token {
10937   const char *z;     /* Text of the token.  Not NULL-terminated! */
10938   unsigned int n;    /* Number of characters in this token */
10939 };
10940 
10941 /*
10942 ** An instance of this structure contains information needed to generate
10943 ** code for a SELECT that contains aggregate functions.
10944 **
10945 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10946 ** pointer to this structure.  The Expr.iColumn field is the index in
10947 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10948 ** code for that node.
10949 **
10950 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10951 ** original Select structure that describes the SELECT statement.  These
10952 ** fields do not need to be freed when deallocating the AggInfo structure.
10953 */
10954 struct AggInfo {
10955   u8 directMode;          /* Direct rendering mode means take data directly
10956                           ** from source tables rather than from accumulators */
10957   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10958                           ** than the source table */
10959   int sortingIdx;         /* Cursor number of the sorting index */
10960   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10961   int nSortingColumn;     /* Number of columns in the sorting index */
10962   ExprList *pGroupBy;     /* The group by clause */
10963   struct AggInfo_col {    /* For each column used in source tables */
10964     Table *pTab;             /* Source table */
10965     int iTable;              /* Cursor number of the source table */
10966     int iColumn;             /* Column number within the source table */
10967     int iSorterColumn;       /* Column number in the sorting index */
10968     int iMem;                /* Memory location that acts as accumulator */
10969     Expr *pExpr;             /* The original expression */
10970   } *aCol;
10971   int nColumn;            /* Number of used entries in aCol[] */
10972   int nAccumulator;       /* Number of columns that show through to the output.
10973                           ** Additional columns are used only as parameters to
10974                           ** aggregate functions */
10975   struct AggInfo_func {   /* For each aggregate function */
10976     Expr *pExpr;             /* Expression encoding the function */
10977     FuncDef *pFunc;          /* The aggregate function implementation */
10978     int iMem;                /* Memory location that acts as accumulator */
10979     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10980   } *aFunc;
10981   int nFunc;              /* Number of entries in aFunc[] */
10982 };
10983 
10984 /*
10985 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10986 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10987 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10988 ** it uses less memory in the Expr object, which is a big memory user
10989 ** in systems with lots of prepared statements.  And few applications
10990 ** need more than about 10 or 20 variables.  But some extreme users want
10991 ** to have prepared statements with over 32767 variables, and for them
10992 ** the option is available (at compile-time).
10993 */
10994 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10995 typedef i16 ynVar;
10996 #else
10997 typedef int ynVar;
10998 #endif
10999 
11000 /*
11001 ** Each node of an expression in the parse tree is an instance
11002 ** of this structure.
11003 **
11004 ** Expr.op is the opcode. The integer parser token codes are reused
11005 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11006 ** code representing the ">=" operator. This same integer code is reused
11007 ** to represent the greater-than-or-equal-to operator in the expression
11008 ** tree.
11009 **
11010 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
11011 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11012 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
11013 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11014 ** then Expr.token contains the name of the function.
11015 **
11016 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11017 ** binary operator. Either or both may be NULL.
11018 **
11019 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11020 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11021 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11022 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11023 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
11024 ** valid.
11025 **
11026 ** An expression of the form ID or ID.ID refers to a column in a table.
11027 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11028 ** the integer cursor number of a VDBE cursor pointing to that table and
11029 ** Expr.iColumn is the column number for the specific column.  If the
11030 ** expression is used as a result in an aggregate SELECT, then the
11031 ** value is also stored in the Expr.iAgg column in the aggregate so that
11032 ** it can be accessed after all aggregates are computed.
11033 **
11034 ** If the expression is an unbound variable marker (a question mark 
11035 ** character '?' in the original SQL) then the Expr.iTable holds the index 
11036 ** number for that variable.
11037 **
11038 ** If the expression is a subquery then Expr.iColumn holds an integer
11039 ** register number containing the result of the subquery.  If the
11040 ** subquery gives a constant result, then iTable is -1.  If the subquery
11041 ** gives a different answer at different times during statement processing
11042 ** then iTable is the address of a subroutine that computes the subquery.
11043 **
11044 ** If the Expr is of type OP_Column, and the table it is selecting from
11045 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11046 ** corresponding table definition.
11047 **
11048 ** ALLOCATION NOTES:
11049 **
11050 ** Expr objects can use a lot of memory space in database schema.  To
11051 ** help reduce memory requirements, sometimes an Expr object will be
11052 ** truncated.  And to reduce the number of memory allocations, sometimes
11053 ** two or more Expr objects will be stored in a single memory allocation,
11054 ** together with Expr.zToken strings.
11055 **
11056 ** If the EP_Reduced and EP_TokenOnly flags are set when
11057 ** an Expr object is truncated.  When EP_Reduced is set, then all
11058 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11059 ** are contained within the same memory allocation.  Note, however, that
11060 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11061 ** allocated, regardless of whether or not EP_Reduced is set.
11062 */
11063 struct Expr {
11064   u8 op;                 /* Operation performed by this node */
11065   char affinity;         /* The affinity of the column or 0 if not a column */
11066   u32 flags;             /* Various flags.  EP_* See below */
11067   union {
11068     char *zToken;          /* Token value. Zero terminated and dequoted */
11069     int iValue;            /* Non-negative integer value if EP_IntValue */
11070   } u;
11071 
11072   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11073   ** space is allocated for the fields below this point. An attempt to
11074   ** access them will result in a segfault or malfunction. 
11075   *********************************************************************/
11076 
11077   Expr *pLeft;           /* Left subnode */
11078   Expr *pRight;          /* Right subnode */
11079   union {
11080     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11081     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11082   } x;
11083 
11084   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11085   ** space is allocated for the fields below this point. An attempt to
11086   ** access them will result in a segfault or malfunction.
11087   *********************************************************************/
11088 
11089 #if SQLITE_MAX_EXPR_DEPTH>0
11090   int nHeight;           /* Height of the tree headed by this node */
11091 #endif
11092   int iTable;            /* TK_COLUMN: cursor number of table holding column
11093                          ** TK_REGISTER: register number
11094                          ** TK_TRIGGER: 1 -> new, 0 -> old
11095                          ** EP_Unlikely:  1000 times likelihood */
11096   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
11097                          ** TK_VARIABLE: variable number (always >= 1). */
11098   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11099   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
11100   u8 op2;                /* TK_REGISTER: original value of Expr.op
11101                          ** TK_COLUMN: the value of p5 for OP_Column
11102                          ** TK_AGG_FUNCTION: nesting depth */
11103   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11104   Table *pTab;           /* Table for TK_COLUMN expressions. */
11105 };
11106 
11107 /*
11108 ** The following are the meanings of bits in the Expr.flags field.
11109 */
11110 #define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
11111 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
11112 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
11113 #define EP_Error     0x000008 /* Expression contains one or more errors */
11114 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
11115 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11116 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11117 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11118 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE opeartor */
11119       /* unused      0x000200 */
11120 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
11121 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11122 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
11123 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11124 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11125 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
11126 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11127 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11128 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
11129 #define EP_Constant  0x080000 /* Node is a constant */
11130 
11131 /*
11132 ** These macros can be used to test, set, or clear bits in the 
11133 ** Expr.flags field.
11134 */
11135 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
11136 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
11137 #define ExprSetProperty(E,P)     (E)->flags|=(P)
11138 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
11139 
11140 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11141 ** and Accreditation only.  It works like ExprSetProperty() during VVA
11142 ** processes but is a no-op for delivery.
11143 */
11144 #ifdef SQLITE_DEBUG
11145 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
11146 #else
11147 # define ExprSetVVAProperty(E,P)
11148 #endif
11149 
11150 /*
11151 ** Macros to determine the number of bytes required by a normal Expr 
11152 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
11153 ** and an Expr struct with the EP_TokenOnly flag set.
11154 */
11155 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
11156 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
11157 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
11158 
11159 /*
11160 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
11161 ** above sqlite3ExprDup() for details.
11162 */
11163 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
11164 
11165 /*
11166 ** A list of expressions.  Each expression may optionally have a
11167 ** name.  An expr/name combination can be used in several ways, such
11168 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11169 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
11170 ** also be used as the argument to a function, in which case the a.zName
11171 ** field is not used.
11172 **
11173 ** By default the Expr.zSpan field holds a human-readable description of
11174 ** the expression that is used in the generation of error messages and
11175 ** column labels.  In this case, Expr.zSpan is typically the text of a
11176 ** column expression as it exists in a SELECT statement.  However, if
11177 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11178 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
11179 ** form is used for name resolution with nested FROM clauses.
11180 */
11181 struct ExprList {
11182   int nExpr;             /* Number of expressions on the list */
11183   int iECursor;          /* VDBE Cursor associated with this ExprList */
11184   struct ExprList_item { /* For each expression in the list */
11185     Expr *pExpr;            /* The list of expressions */
11186     char *zName;            /* Token associated with this expression */
11187     char *zSpan;            /* Original text of the expression */
11188     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11189     unsigned done :1;       /* A flag to indicate when processing is finished */
11190     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11191     unsigned reusable :1;   /* Constant expression is reusable */
11192     union {
11193       struct {
11194         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
11195         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
11196       } x;
11197       int iConstExprReg;      /* Register in which Expr value is cached */
11198     } u;
11199   } *a;                  /* Alloc a power of two greater or equal to nExpr */
11200 };
11201 
11202 /*
11203 ** An instance of this structure is used by the parser to record both
11204 ** the parse tree for an expression and the span of input text for an
11205 ** expression.
11206 */
11207 struct ExprSpan {
11208   Expr *pExpr;          /* The expression parse tree */
11209   const char *zStart;   /* First character of input text */
11210   const char *zEnd;     /* One character past the end of input text */
11211 };
11212 
11213 /*
11214 ** An instance of this structure can hold a simple list of identifiers,
11215 ** such as the list "a,b,c" in the following statements:
11216 **
11217 **      INSERT INTO t(a,b,c) VALUES ...;
11218 **      CREATE INDEX idx ON t(a,b,c);
11219 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11220 **
11221 ** The IdList.a.idx field is used when the IdList represents the list of
11222 ** column names after a table name in an INSERT statement.  In the statement
11223 **
11224 **     INSERT INTO t(a,b,c) ...
11225 **
11226 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11227 */
11228 struct IdList {
11229   struct IdList_item {
11230     char *zName;      /* Name of the identifier */
11231     int idx;          /* Index in some Table.aCol[] of a column named zName */
11232   } *a;
11233   int nId;         /* Number of identifiers on the list */
11234 };
11235 
11236 /*
11237 ** The bitmask datatype defined below is used for various optimizations.
11238 **
11239 ** Changing this from a 64-bit to a 32-bit type limits the number of
11240 ** tables in a join to 32 instead of 64.  But it also reduces the size
11241 ** of the library by 738 bytes on ix86.
11242 */
11243 typedef u64 Bitmask;
11244 
11245 /*
11246 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
11247 */
11248 #define BMS  ((int)(sizeof(Bitmask)*8))
11249 
11250 /*
11251 ** A bit in a Bitmask
11252 */
11253 #define MASKBIT(n)   (((Bitmask)1)<<(n))
11254 
11255 /*
11256 ** The following structure describes the FROM clause of a SELECT statement.
11257 ** Each table or subquery in the FROM clause is a separate element of
11258 ** the SrcList.a[] array.
11259 **
11260 ** With the addition of multiple database support, the following structure
11261 ** can also be used to describe a particular table such as the table that
11262 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
11263 ** such a table must be a simple name: ID.  But in SQLite, the table can
11264 ** now be identified by a database name, a dot, then the table name: ID.ID.
11265 **
11266 ** The jointype starts out showing the join type between the current table
11267 ** and the next table on the list.  The parser builds the list this way.
11268 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11269 ** jointype expresses the join between the table and the previous table.
11270 **
11271 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11272 ** contains more than 63 columns and the 64-th or later column is used.
11273 */
11274 struct SrcList {
11275   u8 nSrc;        /* Number of tables or subqueries in the FROM clause */
11276   u8 nAlloc;      /* Number of entries allocated in a[] below */
11277   struct SrcList_item {
11278     Schema *pSchema;  /* Schema to which this item is fixed */
11279     char *zDatabase;  /* Name of database holding this table */
11280     char *zName;      /* Name of the table */
11281     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
11282     Table *pTab;      /* An SQL table corresponding to zName */
11283     Select *pSelect;  /* A SELECT statement used in place of a table name */
11284     int addrFillSub;  /* Address of subroutine to manifest a subquery */
11285     int regReturn;    /* Register holding return address of addrFillSub */
11286     u8 jointype;      /* Type of join between this able and the previous */
11287     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
11288     unsigned isCorrelated :1;  /* True if sub-query is correlated */
11289     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
11290 #ifndef SQLITE_OMIT_EXPLAIN
11291     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
11292 #endif
11293     int iCursor;      /* The VDBE cursor number used to access this table */
11294     Expr *pOn;        /* The ON clause of a join */
11295     IdList *pUsing;   /* The USING clause of a join */
11296     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
11297     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
11298     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
11299   } a[1];             /* One entry for each identifier on the list */
11300 };
11301 
11302 /*
11303 ** Permitted values of the SrcList.a.jointype field
11304 */
11305 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
11306 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
11307 #define JT_NATURAL   0x0004    /* True for a "natural" join */
11308 #define JT_LEFT      0x0008    /* Left outer join */
11309 #define JT_RIGHT     0x0010    /* Right outer join */
11310 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
11311 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
11312 
11313 
11314 /*
11315 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11316 ** and the WhereInfo.wctrlFlags member.
11317 */
11318 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11319 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11320 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11321 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11322 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11323 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11324 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11325 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11326 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11327 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
11328 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
11329 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
11330 
11331 /* Allowed return values from sqlite3WhereIsDistinct()
11332 */
11333 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11334 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11335 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11336 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11337 
11338 /*
11339 ** A NameContext defines a context in which to resolve table and column
11340 ** names.  The context consists of a list of tables (the pSrcList) field and
11341 ** a list of named expression (pEList).  The named expression list may
11342 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11343 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11344 ** pEList corresponds to the result set of a SELECT and is NULL for
11345 ** other statements.
11346 **
11347 ** NameContexts can be nested.  When resolving names, the inner-most 
11348 ** context is searched first.  If no match is found, the next outer
11349 ** context is checked.  If there is still no match, the next context
11350 ** is checked.  This process continues until either a match is found
11351 ** or all contexts are check.  When a match is found, the nRef member of
11352 ** the context containing the match is incremented. 
11353 **
11354 ** Each subquery gets a new NameContext.  The pNext field points to the
11355 ** NameContext in the parent query.  Thus the process of scanning the
11356 ** NameContext list corresponds to searching through successively outer
11357 ** subqueries looking for a match.
11358 */
11359 struct NameContext {
11360   Parse *pParse;       /* The parser */
11361   SrcList *pSrcList;   /* One or more tables used to resolve names */
11362   ExprList *pEList;    /* Optional list of result-set columns */
11363   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11364   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11365   int nRef;            /* Number of names resolved by this context */
11366   int nErr;            /* Number of errors encountered while resolving names */
11367   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11368 };
11369 
11370 /*
11371 ** Allowed values for the NameContext, ncFlags field.
11372 */
11373 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11374 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11375 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11376 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11377 #define NC_PartIdx   0x10    /* True if resolving a partial index WHERE */
11378 
11379 /*
11380 ** An instance of the following structure contains all information
11381 ** needed to generate code for a single SELECT statement.
11382 **
11383 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11384 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11385 ** limit and nOffset to the value of the offset (or 0 if there is not
11386 ** offset).  But later on, nLimit and nOffset become the memory locations
11387 ** in the VDBE that record the limit and offset counters.
11388 **
11389 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11390 ** These addresses must be stored so that we can go back and fill in
11391 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11392 ** the number of columns in P2 can be computed at the same time
11393 ** as the OP_OpenEphm instruction is coded because not
11394 ** enough information about the compound query is known at that point.
11395 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11396 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11397 ** sequences for the ORDER BY clause.
11398 */
11399 struct Select {
11400   ExprList *pEList;      /* The fields of the result */
11401   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11402   u16 selFlags;          /* Various SF_* values */
11403   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11404   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11405   u64 nSelectRow;        /* Estimated number of result rows */
11406   SrcList *pSrc;         /* The FROM clause */
11407   Expr *pWhere;          /* The WHERE clause */
11408   ExprList *pGroupBy;    /* The GROUP BY clause */
11409   Expr *pHaving;         /* The HAVING clause */
11410   ExprList *pOrderBy;    /* The ORDER BY clause */
11411   Select *pPrior;        /* Prior select in a compound select statement */
11412   Select *pNext;         /* Next select to the left in a compound */
11413   Select *pRightmost;    /* Right-most select in a compound select statement */
11414   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11415   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11416 };
11417 
11418 /*
11419 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11420 ** "Select Flag".
11421 */
11422 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11423 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11424 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11425 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11426 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11427 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11428 #define SF_UseSorter       0x0040  /* Sort using a sorter */
11429 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11430 #define SF_Materialize     0x0100  /* Force materialization of views */
11431 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11432 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
11433 
11434 
11435 /*
11436 ** The results of a select can be distributed in several ways.  The
11437 ** "SRT" prefix means "SELECT Result Type".
11438 */
11439 #define SRT_Union        1  /* Store result as keys in an index */
11440 #define SRT_Except       2  /* Remove result from a UNION index */
11441 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11442 #define SRT_Discard      4  /* Do not save the results anywhere */
11443 
11444 /* The ORDER BY clause is ignored for all of the above */
11445 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11446 
11447 #define SRT_Output       5  /* Output each row of result */
11448 #define SRT_Mem          6  /* Store result in a memory cell */
11449 #define SRT_Set          7  /* Store results as keys in an index */
11450 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11451 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11452 #define SRT_Coroutine   10  /* Generate a single row of result */
11453 
11454 /*
11455 ** An instance of this object describes where to put of the results of
11456 ** a SELECT statement.
11457 */
11458 struct SelectDest {
11459   u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11460   char affSdst;     /* Affinity used when eDest==SRT_Set */
11461   int iSDParm;      /* A parameter used by the eDest disposal method */
11462   int iSdst;        /* Base register where results are written */
11463   int nSdst;        /* Number of registers allocated */
11464 };
11465 
11466 /*
11467 ** During code generation of statements that do inserts into AUTOINCREMENT 
11468 ** tables, the following information is attached to the Table.u.autoInc.p
11469 ** pointer of each autoincrement table to record some side information that
11470 ** the code generator needs.  We have to keep per-table autoincrement
11471 ** information in case inserts are down within triggers.  Triggers do not
11472 ** normally coordinate their activities, but we do need to coordinate the
11473 ** loading and saving of autoincrement information.
11474 */
11475 struct AutoincInfo {
11476   AutoincInfo *pNext;   /* Next info block in a list of them all */
11477   Table *pTab;          /* Table this info block refers to */
11478   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11479   int regCtr;           /* Memory register holding the rowid counter */
11480 };
11481 
11482 /*
11483 ** Size of the column cache
11484 */
11485 #ifndef SQLITE_N_COLCACHE
11486 # define SQLITE_N_COLCACHE 10
11487 #endif
11488 
11489 /*
11490 ** At least one instance of the following structure is created for each 
11491 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11492 ** statement. All such objects are stored in the linked list headed at
11493 ** Parse.pTriggerPrg and deleted once statement compilation has been
11494 ** completed.
11495 **
11496 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11497 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11498 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11499 ** The Parse.pTriggerPrg list never contains two entries with the same
11500 ** values for both pTrigger and orconf.
11501 **
11502 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11503 ** accessed (or set to 0 for triggers fired as a result of INSERT 
11504 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11505 ** a mask of new.* columns used by the program.
11506 */
11507 struct TriggerPrg {
11508   Trigger *pTrigger;      /* Trigger this program was coded from */
11509   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11510   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11511   int orconf;             /* Default ON CONFLICT policy */
11512   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11513 };
11514 
11515 /*
11516 ** The yDbMask datatype for the bitmask of all attached databases.
11517 */
11518 #if SQLITE_MAX_ATTACHED>30
11519   typedef sqlite3_uint64 yDbMask;
11520 #else
11521   typedef unsigned int yDbMask;
11522 #endif
11523 
11524 /*
11525 ** An SQL parser context.  A copy of this structure is passed through
11526 ** the parser and down into all the parser action routine in order to
11527 ** carry around information that is global to the entire parse.
11528 **
11529 ** The structure is divided into two parts.  When the parser and code
11530 ** generate call themselves recursively, the first part of the structure
11531 ** is constant but the second part is reset at the beginning and end of
11532 ** each recursion.
11533 **
11534 ** The nTableLock and aTableLock variables are only used if the shared-cache 
11535 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11536 ** used to store the set of table-locks required by the statement being
11537 ** compiled. Function sqlite3TableLock() is used to add entries to the
11538 ** list.
11539 */
11540 struct Parse {
11541   sqlite3 *db;         /* The main database structure */
11542   char *zErrMsg;       /* An error message */
11543   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11544   int rc;              /* Return code from execution */
11545   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11546   u8 checkSchema;      /* Causes schema cookie check after an error */
11547   u8 nested;           /* Number of nested calls to the parser/code generator */
11548   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11549   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11550   u8 nColCache;        /* Number of entries in aColCache[] */
11551   u8 iColCache;        /* Next entry in aColCache[] to replace */
11552   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11553   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11554   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
11555   int aTempReg[8];     /* Holding area for temporary registers */
11556   int nRangeReg;       /* Size of the temporary register block */
11557   int iRangeReg;       /* First register in temporary register block */
11558   int nErr;            /* Number of errors seen */
11559   int nTab;            /* Number of previously allocated VDBE cursors */
11560   int nMem;            /* Number of memory cells used so far */
11561   int nSet;            /* Number of sets used so far */
11562   int nOnce;           /* Number of OP_Once instructions so far */
11563   int ckBase;          /* Base register of data during check constraints */
11564   int iPartIdxTab;     /* Table corresponding to a partial index */
11565   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11566   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11567   struct yColCache {
11568     int iTable;           /* Table cursor number */
11569     int iColumn;          /* Table column number */
11570     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11571     int iLevel;           /* Nesting level */
11572     int iReg;             /* Reg with value of this column. 0 means none. */
11573     int lru;              /* Least recently used entry has the smallest value */
11574   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11575   ExprList *pConstExpr;/* Constant expressions */
11576   yDbMask writeMask;   /* Start a write transaction on these databases */
11577   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11578   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11579   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11580   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11581   int regRoot;         /* Register holding root page number for new objects */
11582   int nMaxArg;         /* Max args passed to user function by sub-program */
11583   Token constraintName;/* Name of the constraint currently being parsed */
11584 #ifndef SQLITE_OMIT_SHARED_CACHE
11585   int nTableLock;        /* Number of locks in aTableLock */
11586   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11587 #endif
11588   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11589 
11590   /* Information used while coding trigger programs. */
11591   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11592   Table *pTriggerTab;  /* Table triggers are being coded for */
11593   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
11594   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
11595   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
11596   u32 oldmask;         /* Mask of old.* columns referenced */
11597   u32 newmask;         /* Mask of new.* columns referenced */
11598   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11599   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11600   u8 disableTriggers;  /* True to disable triggers */
11601 
11602   /* Above is constant between recursions.  Below is reset before and after
11603   ** each recursion */
11604 
11605   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11606   int nzVar;                /* Number of available slots in azVar[] */
11607   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
11608   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11609 #ifndef SQLITE_OMIT_VIRTUALTABLE
11610   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11611   int nVtabLock;            /* Number of virtual tables to lock */
11612 #endif
11613   int nAlias;               /* Number of aliased result set columns */
11614   int nHeight;              /* Expression tree height of current sub-select */
11615 #ifndef SQLITE_OMIT_EXPLAIN
11616   int iSelectId;            /* ID of current select for EXPLAIN output */
11617   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11618 #endif
11619   char **azVar;             /* Pointers to names of parameters */
11620   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11621   const char *zTail;        /* All SQL text past the last semicolon parsed */
11622   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11623   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11624   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11625   Token sNameToken;         /* Token with unqualified schema object name */
11626   Token sLastToken;         /* The last token parsed */
11627 #ifndef SQLITE_OMIT_VIRTUALTABLE
11628   Token sArg;               /* Complete text of a module argument */
11629   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11630 #endif
11631   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11632   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11633 };
11634 
11635 /*
11636 ** Return true if currently inside an sqlite3_declare_vtab() call.
11637 */
11638 #ifdef SQLITE_OMIT_VIRTUALTABLE
11639   #define IN_DECLARE_VTAB 0
11640 #else
11641   #define IN_DECLARE_VTAB (pParse->declareVtab)
11642 #endif
11643 
11644 /*
11645 ** An instance of the following structure can be declared on a stack and used
11646 ** to save the Parse.zAuthContext value so that it can be restored later.
11647 */
11648 struct AuthContext {
11649   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11650   Parse *pParse;              /* The Parse structure */
11651 };
11652 
11653 /*
11654 ** Bitfield flags for P5 value in various opcodes.
11655 */
11656 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11657 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11658 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11659 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11660 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11661 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11662 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11663 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11664 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11665 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11666 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11667 
11668 /*
11669  * Each trigger present in the database schema is stored as an instance of
11670  * struct Trigger. 
11671  *
11672  * Pointers to instances of struct Trigger are stored in two ways.
11673  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
11674  *    database). This allows Trigger structures to be retrieved by name.
11675  * 2. All triggers associated with a single table form a linked list, using the
11676  *    pNext member of struct Trigger. A pointer to the first element of the
11677  *    linked list is stored as the "pTrigger" member of the associated
11678  *    struct Table.
11679  *
11680  * The "step_list" member points to the first element of a linked list
11681  * containing the SQL statements specified as the trigger program.
11682  */
11683 struct Trigger {
11684   char *zName;            /* The name of the trigger                        */
11685   char *table;            /* The table or view to which the trigger applies */
11686   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11687   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11688   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11689   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11690                              the <column-list> is stored here */
11691   Schema *pSchema;        /* Schema containing the trigger */
11692   Schema *pTabSchema;     /* Schema containing the table */
11693   TriggerStep *step_list; /* Link list of trigger program steps             */
11694   Trigger *pNext;         /* Next trigger associated with the table */
11695 };
11696 
11697 /*
11698 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11699 ** determine which. 
11700 **
11701 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11702 ** In that cases, the constants below can be ORed together.
11703 */
11704 #define TRIGGER_BEFORE  1
11705 #define TRIGGER_AFTER   2
11706 
11707 /*
11708  * An instance of struct TriggerStep is used to store a single SQL statement
11709  * that is a part of a trigger-program. 
11710  *
11711  * Instances of struct TriggerStep are stored in a singly linked list (linked
11712  * using the "pNext" member) referenced by the "step_list" member of the 
11713  * associated struct Trigger instance. The first element of the linked list is
11714  * the first step of the trigger-program.
11715  * 
11716  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11717  * "SELECT" statement. The meanings of the other members is determined by the 
11718  * value of "op" as follows:
11719  *
11720  * (op == TK_INSERT)
11721  * orconf    -> stores the ON CONFLICT algorithm
11722  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11723  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11724  * target    -> A token holding the quoted name of the table to insert into.
11725  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11726  *              this stores values to be inserted. Otherwise NULL.
11727  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11728  *              statement, then this stores the column-names to be
11729  *              inserted into.
11730  *
11731  * (op == TK_DELETE)
11732  * target    -> A token holding the quoted name of the table to delete from.
11733  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11734  *              Otherwise NULL.
11735  * 
11736  * (op == TK_UPDATE)
11737  * target    -> A token holding the quoted name of the table to update rows of.
11738  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11739  *              Otherwise NULL.
11740  * pExprList -> A list of the columns to update and the expressions to update
11741  *              them to. See sqlite3Update() documentation of "pChanges"
11742  *              argument.
11743  * 
11744  */
11745 struct TriggerStep {
11746   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11747   u8 orconf;           /* OE_Rollback etc. */
11748   Trigger *pTrig;      /* The trigger that this step is a part of */
11749   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11750   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11751   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11752   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11753   IdList *pIdList;     /* Column names for INSERT */
11754   TriggerStep *pNext;  /* Next in the link-list */
11755   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11756 };
11757 
11758 /*
11759 ** The following structure contains information used by the sqliteFix...
11760 ** routines as they walk the parse tree to make database references
11761 ** explicit.  
11762 */
11763 typedef struct DbFixer DbFixer;
11764 struct DbFixer {
11765   Parse *pParse;      /* The parsing context.  Error messages written here */
11766   Schema *pSchema;    /* Fix items to this schema */
11767   int bVarOnly;       /* Check for variable references only */
11768   const char *zDb;    /* Make sure all objects are contained in this database */
11769   const char *zType;  /* Type of the container - used for error messages */
11770   const Token *pName; /* Name of the container - used for error messages */
11771 };
11772 
11773 /*
11774 ** An objected used to accumulate the text of a string where we
11775 ** do not necessarily know how big the string will be in the end.
11776 */
11777 struct StrAccum {
11778   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11779   char *zBase;         /* A base allocation.  Not from malloc. */
11780   char *zText;         /* The string collected so far */
11781   int  nChar;          /* Length of the string so far */
11782   int  nAlloc;         /* Amount of space allocated in zText */
11783   int  mxAlloc;        /* Maximum allowed string length */
11784   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11785   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
11786 };
11787 #define STRACCUM_NOMEM   1
11788 #define STRACCUM_TOOBIG  2
11789 
11790 /*
11791 ** A pointer to this structure is used to communicate information
11792 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11793 */
11794 typedef struct {
11795   sqlite3 *db;        /* The database being initialized */
11796   char **pzErrMsg;    /* Error message stored here */
11797   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11798   int rc;             /* Result code stored here */
11799 } InitData;
11800 
11801 /*
11802 ** Structure containing global configuration data for the SQLite library.
11803 **
11804 ** This structure also contains some state information.
11805 */
11806 struct Sqlite3Config {
11807   int bMemstat;                     /* True to enable memory status */
11808   int bCoreMutex;                   /* True to enable core mutexing */
11809   int bFullMutex;                   /* True to enable full mutexing */
11810   int bOpenUri;                     /* True to interpret filenames as URIs */
11811   int bUseCis;                      /* Use covering indices for full-scans */
11812   int mxStrlen;                     /* Maximum string length */
11813   int neverCorrupt;                 /* Database is always well-formed */
11814   int szLookaside;                  /* Default lookaside buffer size */
11815   int nLookaside;                   /* Default lookaside buffer count */
11816   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11817   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11818   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11819   void *pHeap;                      /* Heap storage space */
11820   int nHeap;                        /* Size of pHeap[] */
11821   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11822   sqlite3_int64 szMmap;             /* mmap() space per open file */
11823   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
11824   void *pScratch;                   /* Scratch memory */
11825   int szScratch;                    /* Size of each scratch buffer */
11826   int nScratch;                     /* Number of scratch buffers */
11827   void *pPage;                      /* Page cache memory */
11828   int szPage;                       /* Size of each page in pPage[] */
11829   int nPage;                        /* Number of pages in pPage[] */
11830   int mxParserStack;                /* maximum depth of the parser stack */
11831   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11832   /* The above might be initialized to non-zero.  The following need to always
11833   ** initially be zero, however. */
11834   int isInit;                       /* True after initialization has finished */
11835   int inProgress;                   /* True while initialization in progress */
11836   int isMutexInit;                  /* True after mutexes are initialized */
11837   int isMallocInit;                 /* True after malloc is initialized */
11838   int isPCacheInit;                 /* True after malloc is initialized */
11839   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11840   int nRefInitMutex;                /* Number of users of pInitMutex */
11841   void (*xLog)(void*,int,const char*); /* Function for logging */
11842   void *pLogArg;                       /* First argument to xLog() */
11843   int bLocaltimeFault;              /* True to fail localtime() calls */
11844 #ifdef SQLITE_ENABLE_SQLLOG
11845   void(*xSqllog)(void*,sqlite3*,const char*, int);
11846   void *pSqllogArg;
11847 #endif
11848 };
11849 
11850 /*
11851 ** This macro is used inside of assert() statements to indicate that
11852 ** the assert is only valid on a well-formed database.  Instead of:
11853 **
11854 **     assert( X );
11855 **
11856 ** One writes:
11857 **
11858 **     assert( X || CORRUPT_DB );
11859 **
11860 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
11861 ** that the database is definitely corrupt, only that it might be corrupt.
11862 ** For most test cases, CORRUPT_DB is set to false using a special
11863 ** sqlite3_test_control().  This enables assert() statements to prove
11864 ** things that are always true for well-formed databases.
11865 */
11866 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
11867 
11868 /*
11869 ** Context pointer passed down through the tree-walk.
11870 */
11871 struct Walker {
11872   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11873   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11874   Parse *pParse;                            /* Parser context.  */
11875   int walkerDepth;                          /* Number of subqueries */
11876   u8 bSelectDepthFirst;                     /* Do subqueries first */
11877   union {                                   /* Extra data for callback */
11878     NameContext *pNC;                          /* Naming context */
11879     int i;                                     /* Integer value */
11880     SrcList *pSrcList;                         /* FROM clause */
11881     struct SrcCount *pSrcCount;                /* Counting column references */
11882   } u;
11883 };
11884 
11885 /* Forward declarations */
11886 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11887 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11888 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11889 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11890 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11891 
11892 /*
11893 ** Return code from the parse-tree walking primitives and their
11894 ** callbacks.
11895 */
11896 #define WRC_Continue    0   /* Continue down into children */
11897 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11898 #define WRC_Abort       2   /* Abandon the tree walk */
11899 
11900 /*
11901 ** Assuming zIn points to the first byte of a UTF-8 character,
11902 ** advance zIn to point to the first byte of the next UTF-8 character.
11903 */
11904 #define SQLITE_SKIP_UTF8(zIn) {                        \
11905   if( (*(zIn++))>=0xc0 ){                              \
11906     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11907   }                                                    \
11908 }
11909 
11910 /*
11911 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11912 ** the same name but without the _BKPT suffix.  These macros invoke
11913 ** routines that report the line-number on which the error originated
11914 ** using sqlite3_log().  The routines also provide a convenient place
11915 ** to set a debugger breakpoint.
11916 */
11917 SQLITE_PRIVATE int sqlite3CorruptError(int);
11918 SQLITE_PRIVATE int sqlite3MisuseError(int);
11919 SQLITE_PRIVATE int sqlite3CantopenError(int);
11920 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11921 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11922 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11923 
11924 
11925 /*
11926 ** FTS4 is really an extension for FTS3.  It is enabled using the
11927 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11928 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11929 */
11930 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11931 # define SQLITE_ENABLE_FTS3
11932 #endif
11933 
11934 /*
11935 ** The ctype.h header is needed for non-ASCII systems.  It is also
11936 ** needed by FTS3 when FTS3 is included in the amalgamation.
11937 */
11938 #if !defined(SQLITE_ASCII) || \
11939     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11940 # include <ctype.h>
11941 #endif
11942 
11943 /*
11944 ** The following macros mimic the standard library functions toupper(),
11945 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11946 ** sqlite versions only work for ASCII characters, regardless of locale.
11947 */
11948 #ifdef SQLITE_ASCII
11949 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11950 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11951 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11952 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11953 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11954 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11955 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11956 #else
11957 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11958 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11959 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11960 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11961 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11962 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11963 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11964 #endif
11965 
11966 /*
11967 ** Internal function prototypes
11968 */
11969 #define sqlite3StrICmp sqlite3_stricmp
11970 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11971 #define sqlite3StrNICmp sqlite3_strnicmp
11972 
11973 SQLITE_PRIVATE int sqlite3MallocInit(void);
11974 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11975 SQLITE_PRIVATE void *sqlite3Malloc(int);
11976 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11977 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11978 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11979 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11980 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11981 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11982 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11983 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11984 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11985 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11986 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11987 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11988 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11989 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11990 SQLITE_PRIVATE void sqlite3PageFree(void*);
11991 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11992 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11993 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11994 
11995 /*
11996 ** On systems with ample stack space and that support alloca(), make
11997 ** use of alloca() to obtain space for large automatic objects.  By default,
11998 ** obtain space from malloc().
11999 **
12000 ** The alloca() routine never returns NULL.  This will cause code paths
12001 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12002 */
12003 #ifdef SQLITE_USE_ALLOCA
12004 # define sqlite3StackAllocRaw(D,N)   alloca(N)
12005 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
12006 # define sqlite3StackFree(D,P)       
12007 #else
12008 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
12009 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
12010 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
12011 #endif
12012 
12013 #ifdef SQLITE_ENABLE_MEMSYS3
12014 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12015 #endif
12016 #ifdef SQLITE_ENABLE_MEMSYS5
12017 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12018 #endif
12019 
12020 
12021 #ifndef SQLITE_MUTEX_OMIT
12022 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12023 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12024 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
12025 SQLITE_PRIVATE   int sqlite3MutexInit(void);
12026 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
12027 #endif
12028 
12029 SQLITE_PRIVATE int sqlite3StatusValue(int);
12030 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12031 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12032 
12033 #ifndef SQLITE_OMIT_FLOATING_POINT
12034 SQLITE_PRIVATE   int sqlite3IsNaN(double);
12035 #else
12036 # define sqlite3IsNaN(X)  0
12037 #endif
12038 
12039 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
12040 #ifndef SQLITE_OMIT_TRACE
12041 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
12042 #endif
12043 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12044 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12045 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12046 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12047 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
12048 #endif
12049 #if defined(SQLITE_TEST)
12050 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
12051 #endif
12052 
12053 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
12054 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
12055 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
12056 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
12057 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
12058 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
12059 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
12060 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
12061 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
12062 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
12063 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
12064 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
12065 #else
12066 # define sqlite3ExplainBegin(X)
12067 # define sqlite3ExplainSelect(A,B)
12068 # define sqlite3ExplainExpr(A,B)
12069 # define sqlite3ExplainExprList(A,B)
12070 # define sqlite3ExplainFinish(X)
12071 # define sqlite3VdbeExplanation(X) 0
12072 #endif
12073 
12074 
12075 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12076 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12077 SQLITE_PRIVATE int sqlite3Dequote(char*);
12078 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12079 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12080 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12081 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12082 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12083 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12084 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12085 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12086 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12087 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12088 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12089 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12090 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12091 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12092 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12093 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12094 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12095 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12096 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12097 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12098 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12099 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12100 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12101 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12102 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12103 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12104 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12105 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12106 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12107 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12108 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12109 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12110 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12111 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12112 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12113 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12114 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12115 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12116 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12117 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12118 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12119 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12120                     sqlite3_vfs**,char**,char **);
12121 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12122 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12123 
12124 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12125 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12126 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12127 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12128 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12129 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12130 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12131 
12132 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12133 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12134 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12135 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
12136 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12137 
12138 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12139 
12140 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12141 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
12142 #else
12143 # define sqlite3ViewGetColumnNames(A,B) 0
12144 #endif
12145 
12146 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12147 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12148 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12149 #ifndef SQLITE_OMIT_AUTOINCREMENT
12150 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
12151 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
12152 #else
12153 # define sqlite3AutoincrementBegin(X)
12154 # define sqlite3AutoincrementEnd(X)
12155 #endif
12156 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
12157 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
12158 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12159 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12160 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12161 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12162 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12163 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12164                                       Token*, Select*, Expr*, IdList*);
12165 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12166 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12167 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12168 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12169 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12170 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12171 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12172 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12173                           Expr*, int, int);
12174 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12175 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12176 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12177                          Expr*,ExprList*,u16,Expr*,Expr*);
12178 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12179 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12180 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12181 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12182 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12183 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12184 #endif
12185 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12186 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12187 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12188 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12189 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12190 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12191 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12192 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12193 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12194 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12195 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12196 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12197 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12198 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12199 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12200 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
12201 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12202 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12203 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12204 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
12205 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12206 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12207 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12208 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12209 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12210 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
12211 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
12212 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12213 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12214 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12215 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12216 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12217 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12218 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12219 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12220 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12221 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12222 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12223 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12224 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12225 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12226 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12227 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12228 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12229 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12230 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12231 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12232 SQLITE_PRIVATE void sqlite3PrngResetState(void);
12233 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12234 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12235 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12236 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12237 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12238 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12239 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12240 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12241 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12242 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12243 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12244 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12245 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12246 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12247 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
12248 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12249 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12250 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12251 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12252 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
12253 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12254                                      u8,u8,int,int*);
12255 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12256 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12257 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12258 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12259 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12260 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12261 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12262 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12263 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12264 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12265 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12266 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12267 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12268 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12269 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12270 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12271 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12272 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12273 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12274 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12275 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12276 
12277 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12278 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12279 #endif
12280 
12281 #ifndef SQLITE_OMIT_TRIGGER
12282 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12283                            Expr*,int, int);
12284 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12285 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12286 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12287 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12288 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12289 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12290                             int, int, int);
12291 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12292   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12293 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12294 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12295 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12296                                         ExprList*,Select*,u8);
12297 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12298 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12299 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12300 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12301 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12302 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12303 #else
12304 # define sqlite3TriggersExist(B,C,D,E,F) 0
12305 # define sqlite3DeleteTrigger(A,B)
12306 # define sqlite3DropTriggerPtr(A,B)
12307 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12308 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12309 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12310 # define sqlite3TriggerList(X, Y) 0
12311 # define sqlite3ParseToplevel(p) p
12312 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12313 #endif
12314 
12315 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12316 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12317 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12318 #ifndef SQLITE_OMIT_AUTHORIZATION
12319 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12320 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12321 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12322 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12323 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12324 #else
12325 # define sqlite3AuthRead(a,b,c,d)
12326 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12327 # define sqlite3AuthContextPush(a,b,c)
12328 # define sqlite3AuthContextPop(a)  ((void)(a))
12329 #endif
12330 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12331 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12332 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12333 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12334 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12335 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12336 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12337 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12338 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12339 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12340 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12341 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12342 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12343 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12344 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12345 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12346 #ifndef SQLITE_OMIT_VIRTUALTABLE
12347 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12348 #endif
12349 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12350 
12351 /*
12352 ** Routines to read and write variable-length integers.  These used to
12353 ** be defined locally, but now we use the varint routines in the util.c
12354 ** file.  Code should use the MACRO forms below, as the Varint32 versions
12355 ** are coded to assume the single byte case is already handled (which 
12356 ** the MACRO form does).
12357 */
12358 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12359 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12360 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12361 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12362 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12363 
12364 /*
12365 ** The header of a record consists of a sequence variable-length integers.
12366 ** These integers are almost always small and are encoded as a single byte.
12367 ** The following macros take advantage this fact to provide a fast encode
12368 ** and decode of the integers in a record header.  It is faster for the common
12369 ** case where the integer is a single byte.  It is a little slower when the
12370 ** integer is two or more bytes.  But overall it is faster.
12371 **
12372 ** The following expressions are equivalent:
12373 **
12374 **     x = sqlite3GetVarint32( A, &B );
12375 **     x = sqlite3PutVarint32( A, B );
12376 **
12377 **     x = getVarint32( A, B );
12378 **     x = putVarint32( A, B );
12379 **
12380 */
12381 #define getVarint32(A,B)  \
12382   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12383 #define putVarint32(A,B)  \
12384   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12385   sqlite3PutVarint32((A),(B)))
12386 #define getVarint    sqlite3GetVarint
12387 #define putVarint    sqlite3PutVarint
12388 
12389 
12390 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12391 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12392 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12393 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12394 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12395 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12396 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12397 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12398 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12399 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12400 
12401 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
12402     defined(SQLITE_DEBUG_OS_TRACE)
12403 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12404 #endif
12405 
12406 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12407 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12408 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12409 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12410 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12411 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12412 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12413 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12414 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12415 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12416 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12417 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12418 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12419 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12420 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12421 #ifdef SQLITE_ENABLE_8_3_NAMES
12422 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12423 #else
12424 # define sqlite3FileSuffix3(X,Y)
12425 #endif
12426 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12427 
12428 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12429 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12430 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
12431                         void(*)(void*));
12432 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12433 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12434 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12435 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12436 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12437 #ifndef SQLITE_AMALGAMATION
12438 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12439 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12440 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12441 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12442 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12443 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12444 #ifndef SQLITE_OMIT_WSD
12445 SQLITE_PRIVATE int sqlite3PendingByte;
12446 #endif
12447 #endif
12448 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12449 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12450 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12451 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12452 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12453 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12454 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12455 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12456 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12457 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12458 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12459 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12460 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
12461 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12462 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12463 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12464 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12465 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12466 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
12467 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12468 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12469 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12470 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12471 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12472 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12473 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12474 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12475 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12476 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12477 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12478 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12479 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12480 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
12481 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
12482 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
12483 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
12484 #ifdef SQLITE_DEBUG
12485 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
12486 #endif
12487 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
12488   void (*)(sqlite3_context*,int,sqlite3_value **),
12489   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12490   FuncDestructor *pDestructor
12491 );
12492 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12493 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12494 
12495 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12496 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12497 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12498 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12499 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12500 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12501 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12502 
12503 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12504 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12505 
12506 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
12507 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
12508 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
12509 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
12510 #endif
12511 
12512 /*
12513 ** The interface to the LEMON-generated parser
12514 */
12515 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12516 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12517 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12518 #ifdef YYTRACKMAXSTACKDEPTH
12519 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12520 #endif
12521 
12522 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12523 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12524 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12525 #else
12526 # define sqlite3CloseExtensions(X)
12527 #endif
12528 
12529 #ifndef SQLITE_OMIT_SHARED_CACHE
12530 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12531 #else
12532   #define sqlite3TableLock(v,w,x,y,z)
12533 #endif
12534 
12535 #ifdef SQLITE_TEST
12536 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12537 #endif
12538 
12539 #ifdef SQLITE_OMIT_VIRTUALTABLE
12540 #  define sqlite3VtabClear(Y)
12541 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12542 #  define sqlite3VtabRollback(X)
12543 #  define sqlite3VtabCommit(X)
12544 #  define sqlite3VtabInSync(db) 0
12545 #  define sqlite3VtabLock(X) 
12546 #  define sqlite3VtabUnlock(X)
12547 #  define sqlite3VtabUnlockList(X)
12548 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12549 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12550 #else
12551 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12552 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12553 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
12554 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12555 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12556 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12557 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12558 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12559 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12560 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
12561 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12562 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12563 #endif
12564 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12565 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12566 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12567 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12568 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12569 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12570 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12571 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12572 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12573 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12574 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12575 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
12576 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12577 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12578 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
12579 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12580 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12581 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12582 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12583 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12584 #ifndef SQLITE_OMIT_WAL
12585 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12586 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12587 #endif
12588 
12589 /* Declarations for functions in fkey.c. All of these are replaced by
12590 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12591 ** key functionality is available. If OMIT_TRIGGER is defined but
12592 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12593 ** this case foreign keys are parsed, but no other functionality is 
12594 ** provided (enforcement of FK constraints requires the triggers sub-system).
12595 */
12596 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12597 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
12598 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12599 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
12600 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12601 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12602 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12603 #else
12604   #define sqlite3FkActions(a,b,c,d,e,f)
12605   #define sqlite3FkCheck(a,b,c,d,e,f)
12606   #define sqlite3FkDropTable(a,b,c)
12607   #define sqlite3FkOldmask(a,b)         0
12608   #define sqlite3FkRequired(a,b,c,d)    0
12609 #endif
12610 #ifndef SQLITE_OMIT_FOREIGN_KEY
12611 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12612 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12613 #else
12614   #define sqlite3FkDelete(a,b)
12615   #define sqlite3FkLocateIndex(a,b,c,d,e)
12616 #endif
12617 
12618 
12619 /*
12620 ** Available fault injectors.  Should be numbered beginning with 0.
12621 */
12622 #define SQLITE_FAULTINJECTOR_MALLOC     0
12623 #define SQLITE_FAULTINJECTOR_COUNT      1
12624 
12625 /*
12626 ** The interface to the code in fault.c used for identifying "benign"
12627 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12628 ** is not defined.
12629 */
12630 #ifndef SQLITE_OMIT_BUILTIN_TEST
12631 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12632 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12633 #else
12634   #define sqlite3BeginBenignMalloc()
12635   #define sqlite3EndBenignMalloc()
12636 #endif
12637 
12638 #define IN_INDEX_ROWID           1
12639 #define IN_INDEX_EPH             2
12640 #define IN_INDEX_INDEX_ASC       3
12641 #define IN_INDEX_INDEX_DESC      4
12642 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12643 
12644 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12645 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12646 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12647 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12648 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12649 #else
12650   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12651   #define sqlite3JournalExists(p) 1
12652 #endif
12653 
12654 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12655 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12656 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12657 
12658 #if SQLITE_MAX_EXPR_DEPTH>0
12659 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12660 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12661 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12662 #else
12663   #define sqlite3ExprSetHeight(x,y)
12664   #define sqlite3SelectExprHeight(x) 0
12665   #define sqlite3ExprCheckHeight(x,y)
12666 #endif
12667 
12668 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12669 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12670 
12671 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12672 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12673 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12674 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12675 #else
12676   #define sqlite3ConnectionBlocked(x,y)
12677   #define sqlite3ConnectionUnlocked(x)
12678   #define sqlite3ConnectionClosed(x)
12679 #endif
12680 
12681 #ifdef SQLITE_DEBUG
12682 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12683 #endif
12684 
12685 /*
12686 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12687 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12688 ** print I/O tracing messages. 
12689 */
12690 #ifdef SQLITE_ENABLE_IOTRACE
12691 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12692 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12693 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12694 #else
12695 # define IOTRACE(A)
12696 # define sqlite3VdbeIOTraceSql(X)
12697 #endif
12698 
12699 /*
12700 ** These routines are available for the mem2.c debugging memory allocator
12701 ** only.  They are used to verify that different "types" of memory
12702 ** allocations are properly tracked by the system.
12703 **
12704 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12705 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12706 ** a single bit set.
12707 **
12708 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12709 ** argument match the type set by the previous sqlite3MemdebugSetType().
12710 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12711 **
12712 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12713 ** argument match the type set by the previous sqlite3MemdebugSetType().
12714 **
12715 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12716 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12717 ** it might have been allocated by lookaside, except the allocation was
12718 ** too large or lookaside was already full.  It is important to verify
12719 ** that allocations that might have been satisfied by lookaside are not
12720 ** passed back to non-lookaside free() routines.  Asserts such as the
12721 ** example above are placed on the non-lookaside free() routines to verify
12722 ** this constraint. 
12723 **
12724 ** All of this is no-op for a production build.  It only comes into
12725 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12726 */
12727 #ifdef SQLITE_MEMDEBUG
12728 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12729 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12730 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12731 #else
12732 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12733 # define sqlite3MemdebugHasType(X,Y)  1
12734 # define sqlite3MemdebugNoType(X,Y)   1
12735 #endif
12736 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12737 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12738 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12739 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12740 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12741 
12742 #endif /* _SQLITEINT_H_ */
12743 
12744 /************** End of sqliteInt.h *******************************************/
12745 /************** Begin file global.c ******************************************/
12746 /*
12747 ** 2008 June 13
12748 **
12749 ** The author disclaims copyright to this source code.  In place of
12750 ** a legal notice, here is a blessing:
12751 **
12752 **    May you do good and not evil.
12753 **    May you find forgiveness for yourself and forgive others.
12754 **    May you share freely, never taking more than you give.
12755 **
12756 *************************************************************************
12757 **
12758 ** This file contains definitions of global variables and contants.
12759 */
12760 
12761 /* An array to map all upper-case characters into their corresponding
12762 ** lower-case character. 
12763 **
12764 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12765 ** handle case conversions for the UTF character set since the tables
12766 ** involved are nearly as big or bigger than SQLite itself.
12767 */
12768 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12769 #ifdef SQLITE_ASCII
12770       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12771      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12772      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12773      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12774     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12775     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12776     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12777     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12778     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12779     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12780     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12781     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12782     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12783     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12784     252,253,254,255
12785 #endif
12786 #ifdef SQLITE_EBCDIC
12787       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12788      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12789      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12790      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12791      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12792      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12793      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12794     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12795     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12796     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12797     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12798     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12799     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12800     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12801     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12802     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12803 #endif
12804 };
12805 
12806 /*
12807 ** The following 256 byte lookup table is used to support SQLites built-in
12808 ** equivalents to the following standard library functions:
12809 **
12810 **   isspace()                        0x01
12811 **   isalpha()                        0x02
12812 **   isdigit()                        0x04
12813 **   isalnum()                        0x06
12814 **   isxdigit()                       0x08
12815 **   toupper()                        0x20
12816 **   SQLite identifier character      0x40
12817 **
12818 ** Bit 0x20 is set if the mapped character requires translation to upper
12819 ** case. i.e. if the character is a lower-case ASCII character.
12820 ** If x is a lower-case ASCII character, then its upper-case equivalent
12821 ** is (x - 0x20). Therefore toupper() can be implemented as:
12822 **
12823 **   (x & ~(map[x]&0x20))
12824 **
12825 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12826 ** array. tolower() is used more often than toupper() by SQLite.
12827 **
12828 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12829 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12830 ** non-ASCII UTF character. Hence the test for whether or not a character is
12831 ** part of an identifier is 0x46.
12832 **
12833 ** SQLite's versions are identical to the standard versions assuming a
12834 ** locale of "C". They are implemented as macros in sqliteInt.h.
12835 */
12836 #ifdef SQLITE_ASCII
12837 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12838   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12839   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12840   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12841   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12842   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12843   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12844   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12845   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12846 
12847   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12848   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12849   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12850   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12851   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12852   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12853   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12854   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12855 
12856   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12857   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12858   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12859   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12860   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12861   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12862   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12863   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12864 
12865   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12866   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12867   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12868   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12869   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12870   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12871   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12872   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12873 };
12874 #endif
12875 
12876 #ifndef SQLITE_USE_URI
12877 # define  SQLITE_USE_URI 0
12878 #endif
12879 
12880 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12881 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12882 #endif
12883 
12884 /*
12885 ** The following singleton contains the global configuration for
12886 ** the SQLite library.
12887 */
12888 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12889    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12890    1,                         /* bCoreMutex */
12891    SQLITE_THREADSAFE==1,      /* bFullMutex */
12892    SQLITE_USE_URI,            /* bOpenUri */
12893    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12894    0x7ffffffe,                /* mxStrlen */
12895    0,                         /* neverCorrupt */
12896    128,                       /* szLookaside */
12897    500,                       /* nLookaside */
12898    {0,0,0,0,0,0,0,0},         /* m */
12899    {0,0,0,0,0,0,0,0,0},       /* mutex */
12900    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12901    (void*)0,                  /* pHeap */
12902    0,                         /* nHeap */
12903    0, 0,                      /* mnHeap, mxHeap */
12904    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
12905    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
12906    (void*)0,                  /* pScratch */
12907    0,                         /* szScratch */
12908    0,                         /* nScratch */
12909    (void*)0,                  /* pPage */
12910    0,                         /* szPage */
12911    0,                         /* nPage */
12912    0,                         /* mxParserStack */
12913    0,                         /* sharedCacheEnabled */
12914    /* All the rest should always be initialized to zero */
12915    0,                         /* isInit */
12916    0,                         /* inProgress */
12917    0,                         /* isMutexInit */
12918    0,                         /* isMallocInit */
12919    0,                         /* isPCacheInit */
12920    0,                         /* pInitMutex */
12921    0,                         /* nRefInitMutex */
12922    0,                         /* xLog */
12923    0,                         /* pLogArg */
12924    0,                         /* bLocaltimeFault */
12925 #ifdef SQLITE_ENABLE_SQLLOG
12926    0,                         /* xSqllog */
12927    0                          /* pSqllogArg */
12928 #endif
12929 };
12930 
12931 /*
12932 ** Hash table for global functions - functions common to all
12933 ** database connections.  After initialization, this table is
12934 ** read-only.
12935 */
12936 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12937 
12938 /*
12939 ** Constant tokens for values 0 and 1.
12940 */
12941 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12942    { "0", 1 },
12943    { "1", 1 }
12944 };
12945 
12946 
12947 /*
12948 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12949 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12950 ** the database page that contains the pending byte.  It never attempts
12951 ** to read or write that page.  The pending byte page is set assign
12952 ** for use by the VFS layers as space for managing file locks.
12953 **
12954 ** During testing, it is often desirable to move the pending byte to
12955 ** a different position in the file.  This allows code that has to
12956 ** deal with the pending byte to run on files that are much smaller
12957 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12958 ** move the pending byte.
12959 **
12960 ** IMPORTANT:  Changing the pending byte to any value other than
12961 ** 0x40000000 results in an incompatible database file format!
12962 ** Changing the pending byte during operating results in undefined
12963 ** and dileterious behavior.
12964 */
12965 #ifndef SQLITE_OMIT_WSD
12966 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12967 #endif
12968 
12969 /*
12970 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12971 ** created by mkopcodeh.awk during compilation.  Data is obtained
12972 ** from the comments following the "case OP_xxxx:" statements in
12973 ** the vdbe.c file.  
12974 */
12975 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12976 
12977 /************** End of global.c **********************************************/
12978 /************** Begin file ctime.c *******************************************/
12979 /*
12980 ** 2010 February 23
12981 **
12982 ** The author disclaims copyright to this source code.  In place of
12983 ** a legal notice, here is a blessing:
12984 **
12985 **    May you do good and not evil.
12986 **    May you find forgiveness for yourself and forgive others.
12987 **    May you share freely, never taking more than you give.
12988 **
12989 *************************************************************************
12990 **
12991 ** This file implements routines used to report what compile-time options
12992 ** SQLite was built with.
12993 */
12994 
12995 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12996 
12997 
12998 /*
12999 ** An array of names of all compile-time options.  This array should 
13000 ** be sorted A-Z.
13001 **
13002 ** This array looks large, but in a typical installation actually uses
13003 ** only a handful of compile-time options, so most times this array is usually
13004 ** rather short and uses little memory space.
13005 */
13006 static const char * const azCompileOpt[] = {
13007 
13008 /* These macros are provided to "stringify" the value of the define
13009 ** for those options in which the value is meaningful. */
13010 #define CTIMEOPT_VAL_(opt) #opt
13011 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13012 
13013 #ifdef SQLITE_32BIT_ROWID
13014   "32BIT_ROWID",
13015 #endif
13016 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13017   "4_BYTE_ALIGNED_MALLOC",
13018 #endif
13019 #ifdef SQLITE_CASE_SENSITIVE_LIKE
13020   "CASE_SENSITIVE_LIKE",
13021 #endif
13022 #ifdef SQLITE_CHECK_PAGES
13023   "CHECK_PAGES",
13024 #endif
13025 #ifdef SQLITE_COVERAGE_TEST
13026   "COVERAGE_TEST",
13027 #endif
13028 #ifdef SQLITE_DEBUG
13029   "DEBUG",
13030 #endif
13031 #ifdef SQLITE_DEFAULT_LOCKING_MODE
13032   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13033 #endif
13034 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13035   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13036 #endif
13037 #ifdef SQLITE_DISABLE_DIRSYNC
13038   "DISABLE_DIRSYNC",
13039 #endif
13040 #ifdef SQLITE_DISABLE_LFS
13041   "DISABLE_LFS",
13042 #endif
13043 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13044   "ENABLE_ATOMIC_WRITE",
13045 #endif
13046 #ifdef SQLITE_ENABLE_CEROD
13047   "ENABLE_CEROD",
13048 #endif
13049 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13050   "ENABLE_COLUMN_METADATA",
13051 #endif
13052 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13053   "ENABLE_EXPENSIVE_ASSERT",
13054 #endif
13055 #ifdef SQLITE_ENABLE_FTS1
13056   "ENABLE_FTS1",
13057 #endif
13058 #ifdef SQLITE_ENABLE_FTS2
13059   "ENABLE_FTS2",
13060 #endif
13061 #ifdef SQLITE_ENABLE_FTS3
13062   "ENABLE_FTS3",
13063 #endif
13064 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13065   "ENABLE_FTS3_PARENTHESIS",
13066 #endif
13067 #ifdef SQLITE_ENABLE_FTS4
13068   "ENABLE_FTS4",
13069 #endif
13070 #ifdef SQLITE_ENABLE_ICU
13071   "ENABLE_ICU",
13072 #endif
13073 #ifdef SQLITE_ENABLE_IOTRACE
13074   "ENABLE_IOTRACE",
13075 #endif
13076 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
13077   "ENABLE_LOAD_EXTENSION",
13078 #endif
13079 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13080   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13081 #endif
13082 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13083   "ENABLE_MEMORY_MANAGEMENT",
13084 #endif
13085 #ifdef SQLITE_ENABLE_MEMSYS3
13086   "ENABLE_MEMSYS3",
13087 #endif
13088 #ifdef SQLITE_ENABLE_MEMSYS5
13089   "ENABLE_MEMSYS5",
13090 #endif
13091 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13092   "ENABLE_OVERSIZE_CELL_CHECK",
13093 #endif
13094 #ifdef SQLITE_ENABLE_RTREE
13095   "ENABLE_RTREE",
13096 #endif
13097 #if defined(SQLITE_ENABLE_STAT4)
13098   "ENABLE_STAT4",
13099 #elif defined(SQLITE_ENABLE_STAT3)
13100   "ENABLE_STAT3",
13101 #endif
13102 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13103   "ENABLE_UNLOCK_NOTIFY",
13104 #endif
13105 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13106   "ENABLE_UPDATE_DELETE_LIMIT",
13107 #endif
13108 #ifdef SQLITE_HAS_CODEC
13109   "HAS_CODEC",
13110 #endif
13111 #ifdef SQLITE_HAVE_ISNAN
13112   "HAVE_ISNAN",
13113 #endif
13114 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13115   "HOMEGROWN_RECURSIVE_MUTEX",
13116 #endif
13117 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13118   "IGNORE_AFP_LOCK_ERRORS",
13119 #endif
13120 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13121   "IGNORE_FLOCK_LOCK_ERRORS",
13122 #endif
13123 #ifdef SQLITE_INT64_TYPE
13124   "INT64_TYPE",
13125 #endif
13126 #ifdef SQLITE_LOCK_TRACE
13127   "LOCK_TRACE",
13128 #endif
13129 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13130   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13131 #endif
13132 #ifdef SQLITE_MAX_SCHEMA_RETRY
13133   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13134 #endif
13135 #ifdef SQLITE_MEMDEBUG
13136   "MEMDEBUG",
13137 #endif
13138 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13139   "MIXED_ENDIAN_64BIT_FLOAT",
13140 #endif
13141 #ifdef SQLITE_NO_SYNC
13142   "NO_SYNC",
13143 #endif
13144 #ifdef SQLITE_OMIT_ALTERTABLE
13145   "OMIT_ALTERTABLE",
13146 #endif
13147 #ifdef SQLITE_OMIT_ANALYZE
13148   "OMIT_ANALYZE",
13149 #endif
13150 #ifdef SQLITE_OMIT_ATTACH
13151   "OMIT_ATTACH",
13152 #endif
13153 #ifdef SQLITE_OMIT_AUTHORIZATION
13154   "OMIT_AUTHORIZATION",
13155 #endif
13156 #ifdef SQLITE_OMIT_AUTOINCREMENT
13157   "OMIT_AUTOINCREMENT",
13158 #endif
13159 #ifdef SQLITE_OMIT_AUTOINIT
13160   "OMIT_AUTOINIT",
13161 #endif
13162 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13163   "OMIT_AUTOMATIC_INDEX",
13164 #endif
13165 #ifdef SQLITE_OMIT_AUTORESET
13166   "OMIT_AUTORESET",
13167 #endif
13168 #ifdef SQLITE_OMIT_AUTOVACUUM
13169   "OMIT_AUTOVACUUM",
13170 #endif
13171 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13172   "OMIT_BETWEEN_OPTIMIZATION",
13173 #endif
13174 #ifdef SQLITE_OMIT_BLOB_LITERAL
13175   "OMIT_BLOB_LITERAL",
13176 #endif
13177 #ifdef SQLITE_OMIT_BTREECOUNT
13178   "OMIT_BTREECOUNT",
13179 #endif
13180 #ifdef SQLITE_OMIT_BUILTIN_TEST
13181   "OMIT_BUILTIN_TEST",
13182 #endif
13183 #ifdef SQLITE_OMIT_CAST
13184   "OMIT_CAST",
13185 #endif
13186 #ifdef SQLITE_OMIT_CHECK
13187   "OMIT_CHECK",
13188 #endif
13189 #ifdef SQLITE_OMIT_COMPLETE
13190   "OMIT_COMPLETE",
13191 #endif
13192 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13193   "OMIT_COMPOUND_SELECT",
13194 #endif
13195 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13196   "OMIT_DATETIME_FUNCS",
13197 #endif
13198 #ifdef SQLITE_OMIT_DECLTYPE
13199   "OMIT_DECLTYPE",
13200 #endif
13201 #ifdef SQLITE_OMIT_DEPRECATED
13202   "OMIT_DEPRECATED",
13203 #endif
13204 #ifdef SQLITE_OMIT_DISKIO
13205   "OMIT_DISKIO",
13206 #endif
13207 #ifdef SQLITE_OMIT_EXPLAIN
13208   "OMIT_EXPLAIN",
13209 #endif
13210 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13211   "OMIT_FLAG_PRAGMAS",
13212 #endif
13213 #ifdef SQLITE_OMIT_FLOATING_POINT
13214   "OMIT_FLOATING_POINT",
13215 #endif
13216 #ifdef SQLITE_OMIT_FOREIGN_KEY
13217   "OMIT_FOREIGN_KEY",
13218 #endif
13219 #ifdef SQLITE_OMIT_GET_TABLE
13220   "OMIT_GET_TABLE",
13221 #endif
13222 #ifdef SQLITE_OMIT_INCRBLOB
13223   "OMIT_INCRBLOB",
13224 #endif
13225 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13226   "OMIT_INTEGRITY_CHECK",
13227 #endif
13228 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13229   "OMIT_LIKE_OPTIMIZATION",
13230 #endif
13231 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13232   "OMIT_LOAD_EXTENSION",
13233 #endif
13234 #ifdef SQLITE_OMIT_LOCALTIME
13235   "OMIT_LOCALTIME",
13236 #endif
13237 #ifdef SQLITE_OMIT_LOOKASIDE
13238   "OMIT_LOOKASIDE",
13239 #endif
13240 #ifdef SQLITE_OMIT_MEMORYDB
13241   "OMIT_MEMORYDB",
13242 #endif
13243 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13244   "OMIT_OR_OPTIMIZATION",
13245 #endif
13246 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13247   "OMIT_PAGER_PRAGMAS",
13248 #endif
13249 #ifdef SQLITE_OMIT_PRAGMA
13250   "OMIT_PRAGMA",
13251 #endif
13252 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13253   "OMIT_PROGRESS_CALLBACK",
13254 #endif
13255 #ifdef SQLITE_OMIT_QUICKBALANCE
13256   "OMIT_QUICKBALANCE",
13257 #endif
13258 #ifdef SQLITE_OMIT_REINDEX
13259   "OMIT_REINDEX",
13260 #endif
13261 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13262   "OMIT_SCHEMA_PRAGMAS",
13263 #endif
13264 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13265   "OMIT_SCHEMA_VERSION_PRAGMAS",
13266 #endif
13267 #ifdef SQLITE_OMIT_SHARED_CACHE
13268   "OMIT_SHARED_CACHE",
13269 #endif
13270 #ifdef SQLITE_OMIT_SUBQUERY
13271   "OMIT_SUBQUERY",
13272 #endif
13273 #ifdef SQLITE_OMIT_TCL_VARIABLE
13274   "OMIT_TCL_VARIABLE",
13275 #endif
13276 #ifdef SQLITE_OMIT_TEMPDB
13277   "OMIT_TEMPDB",
13278 #endif
13279 #ifdef SQLITE_OMIT_TRACE
13280   "OMIT_TRACE",
13281 #endif
13282 #ifdef SQLITE_OMIT_TRIGGER
13283   "OMIT_TRIGGER",
13284 #endif
13285 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13286   "OMIT_TRUNCATE_OPTIMIZATION",
13287 #endif
13288 #ifdef SQLITE_OMIT_UTF16
13289   "OMIT_UTF16",
13290 #endif
13291 #ifdef SQLITE_OMIT_VACUUM
13292   "OMIT_VACUUM",
13293 #endif
13294 #ifdef SQLITE_OMIT_VIEW
13295   "OMIT_VIEW",
13296 #endif
13297 #ifdef SQLITE_OMIT_VIRTUALTABLE
13298   "OMIT_VIRTUALTABLE",
13299 #endif
13300 #ifdef SQLITE_OMIT_WAL
13301   "OMIT_WAL",
13302 #endif
13303 #ifdef SQLITE_OMIT_WSD
13304   "OMIT_WSD",
13305 #endif
13306 #ifdef SQLITE_OMIT_XFER_OPT
13307   "OMIT_XFER_OPT",
13308 #endif
13309 #ifdef SQLITE_PERFORMANCE_TRACE
13310   "PERFORMANCE_TRACE",
13311 #endif
13312 #ifdef SQLITE_PROXY_DEBUG
13313   "PROXY_DEBUG",
13314 #endif
13315 #ifdef SQLITE_RTREE_INT_ONLY
13316   "RTREE_INT_ONLY",
13317 #endif
13318 #ifdef SQLITE_SECURE_DELETE
13319   "SECURE_DELETE",
13320 #endif
13321 #ifdef SQLITE_SMALL_STACK
13322   "SMALL_STACK",
13323 #endif
13324 #ifdef SQLITE_SOUNDEX
13325   "SOUNDEX",
13326 #endif
13327 #ifdef SQLITE_SYSTEM_MALLOC
13328   "SYSTEM_MALLOC",
13329 #endif
13330 #ifdef SQLITE_TCL
13331   "TCL",
13332 #endif
13333 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13334   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13335 #endif
13336 #ifdef SQLITE_TEST
13337   "TEST",
13338 #endif
13339 #if defined(SQLITE_THREADSAFE)
13340   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13341 #endif
13342 #ifdef SQLITE_USE_ALLOCA
13343   "USE_ALLOCA",
13344 #endif
13345 #ifdef SQLITE_WIN32_MALLOC
13346   "WIN32_MALLOC",
13347 #endif
13348 #ifdef SQLITE_ZERO_MALLOC
13349   "ZERO_MALLOC"
13350 #endif
13351 };
13352 
13353 /*
13354 ** Given the name of a compile-time option, return true if that option
13355 ** was used and false if not.
13356 **
13357 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13358 ** is not required for a match.
13359 */
13360 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13361   int i, n;
13362   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13363   n = sqlite3Strlen30(zOptName);
13364 
13365   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13366   ** linear search is adequate.  No need for a binary search. */
13367   for(i=0; i<ArraySize(azCompileOpt); i++){
13368     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13369      && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13370     ){
13371       return 1;
13372     }
13373   }
13374   return 0;
13375 }
13376 
13377 /*
13378 ** Return the N-th compile-time option string.  If N is out of range,
13379 ** return a NULL pointer.
13380 */
13381 SQLITE_API const char *sqlite3_compileoption_get(int N){
13382   if( N>=0 && N<ArraySize(azCompileOpt) ){
13383     return azCompileOpt[N];
13384   }
13385   return 0;
13386 }
13387 
13388 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13389 
13390 /************** End of ctime.c ***********************************************/
13391 /************** Begin file status.c ******************************************/
13392 /*
13393 ** 2008 June 18
13394 **
13395 ** The author disclaims copyright to this source code.  In place of
13396 ** a legal notice, here is a blessing:
13397 **
13398 **    May you do good and not evil.
13399 **    May you find forgiveness for yourself and forgive others.
13400 **    May you share freely, never taking more than you give.
13401 **
13402 *************************************************************************
13403 **
13404 ** This module implements the sqlite3_status() interface and related
13405 ** functionality.
13406 */
13407 /************** Include vdbeInt.h in the middle of status.c ******************/
13408 /************** Begin file vdbeInt.h *****************************************/
13409 /*
13410 ** 2003 September 6
13411 **
13412 ** The author disclaims copyright to this source code.  In place of
13413 ** a legal notice, here is a blessing:
13414 **
13415 **    May you do good and not evil.
13416 **    May you find forgiveness for yourself and forgive others.
13417 **    May you share freely, never taking more than you give.
13418 **
13419 *************************************************************************
13420 ** This is the header file for information that is private to the
13421 ** VDBE.  This information used to all be at the top of the single
13422 ** source code file "vdbe.c".  When that file became too big (over
13423 ** 6000 lines long) it was split up into several smaller files and
13424 ** this header information was factored out.
13425 */
13426 #ifndef _VDBEINT_H_
13427 #define _VDBEINT_H_
13428 
13429 /*
13430 ** The maximum number of times that a statement will try to reparse
13431 ** itself before giving up and returning SQLITE_SCHEMA.
13432 */
13433 #ifndef SQLITE_MAX_SCHEMA_RETRY
13434 # define SQLITE_MAX_SCHEMA_RETRY 50
13435 #endif
13436 
13437 /*
13438 ** SQL is translated into a sequence of instructions to be
13439 ** executed by a virtual machine.  Each instruction is an instance
13440 ** of the following structure.
13441 */
13442 typedef struct VdbeOp Op;
13443 
13444 /*
13445 ** Boolean values
13446 */
13447 typedef unsigned Bool;
13448 
13449 /* Opaque type used by code in vdbesort.c */
13450 typedef struct VdbeSorter VdbeSorter;
13451 
13452 /* Opaque type used by the explainer */
13453 typedef struct Explain Explain;
13454 
13455 /* Elements of the linked list at Vdbe.pAuxData */
13456 typedef struct AuxData AuxData;
13457 
13458 /*
13459 ** A cursor is a pointer into a single BTree within a database file.
13460 ** The cursor can seek to a BTree entry with a particular key, or
13461 ** loop over all entries of the Btree.  You can also insert new BTree
13462 ** entries or retrieve the key or data from the entry that the cursor
13463 ** is currently pointing to.
13464 **
13465 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
13466 ** A pseudo-table is a single-row table implemented by registers.
13467 ** 
13468 ** Every cursor that the virtual machine has open is represented by an
13469 ** instance of the following structure.
13470 */
13471 struct VdbeCursor {
13472   BtCursor *pCursor;    /* The cursor structure of the backend */
13473   Btree *pBt;           /* Separate file holding temporary table */
13474   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13475   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
13476   int pseudoTableReg;   /* Register holding pseudotable content. */
13477   i16 nField;           /* Number of fields in the header */
13478   u16 nHdrParsed;       /* Number of header fields parsed so far */
13479   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
13480   u8 nullRow;           /* True if pointing to a row with no data */
13481   u8 rowidIsValid;      /* True if lastRowid is valid */
13482   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
13483   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
13484   Bool isTable:1;       /* True if a table requiring integer keys */
13485   Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
13486   Bool multiPseudo:1;   /* Multi-register pseudo-cursor */
13487   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13488   i64 seqCount;         /* Sequence counter */
13489   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13490   i64 lastRowid;        /* Rowid being deleted by OP_Delete */
13491   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13492 
13493   /* Cached information about the header for the data record that the
13494   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13495   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13496   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13497   ** the cache is out of date.
13498   **
13499   ** aRow might point to (ephemeral) data for the current row, or it might
13500   ** be NULL.
13501   */
13502   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13503   u32 payloadSize;      /* Total number of bytes in the record */
13504   u32 szRow;            /* Byte available in aRow */
13505   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
13506   const u8 *aRow;       /* Data for the current row, if all on one page */
13507   u32 aType[1];         /* Type values for all entries in the record */
13508   /* 2*nField extra array elements allocated for aType[], beyond the one
13509   ** static element declared in the structure.  nField total array slots for
13510   ** aType[] and nField+1 array slots for aOffset[] */
13511 };
13512 typedef struct VdbeCursor VdbeCursor;
13513 
13514 /*
13515 ** When a sub-program is executed (OP_Program), a structure of this type
13516 ** is allocated to store the current value of the program counter, as
13517 ** well as the current memory cell array and various other frame specific
13518 ** values stored in the Vdbe struct. When the sub-program is finished, 
13519 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13520 ** restoring the state of the VM to as it was before the sub-program
13521 ** began executing.
13522 **
13523 ** The memory for a VdbeFrame object is allocated and managed by a memory
13524 ** cell in the parent (calling) frame. When the memory cell is deleted or
13525 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13526 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13527 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13528 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13529 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13530 ** child frame are released.
13531 **
13532 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13533 ** set to NULL if the currently executing frame is the main program.
13534 */
13535 typedef struct VdbeFrame VdbeFrame;
13536 struct VdbeFrame {
13537   Vdbe *v;                /* VM this frame belongs to */
13538   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13539   Op *aOp;                /* Program instructions for parent frame */
13540   Mem *aMem;              /* Array of memory cells for parent frame */
13541   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13542   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13543   void *token;            /* Copy of SubProgram.token */
13544   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13545   int nCursor;            /* Number of entries in apCsr */
13546   int pc;                 /* Program Counter in parent (calling) frame */
13547   int nOp;                /* Size of aOp array */
13548   int nMem;               /* Number of entries in aMem */
13549   int nOnceFlag;          /* Number of entries in aOnceFlag */
13550   int nChildMem;          /* Number of memory cells for child frame */
13551   int nChildCsr;          /* Number of cursors for child frame */
13552   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13553 };
13554 
13555 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13556 
13557 /*
13558 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13559 */
13560 #define CACHE_STALE 0
13561 
13562 /*
13563 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13564 ** structures. Each Mem struct may cache multiple representations (string,
13565 ** integer etc.) of the same value.
13566 */
13567 struct Mem {
13568   sqlite3 *db;        /* The associated database connection */
13569   char *z;            /* String or BLOB value */
13570   double r;           /* Real value */
13571   union {
13572     i64 i;              /* Integer value used when MEM_Int is set in flags */
13573     int nZero;          /* Used when bit MEM_Zero is set in flags */
13574     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13575     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13576     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13577   } u;
13578   int n;              /* Number of characters in string value, excluding '\0' */
13579   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13580   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13581   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13582 #ifdef SQLITE_DEBUG
13583   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13584   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13585 #endif
13586   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13587   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13588 };
13589 
13590 /* One or more of the following flags are set to indicate the validOK
13591 ** representations of the value stored in the Mem struct.
13592 **
13593 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13594 ** No other flags may be set in this case.
13595 **
13596 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13597 ** Usually this is encoded in the same unicode encoding as the main
13598 ** database (see below for exceptions). If the MEM_Term flag is also
13599 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13600 ** flags may coexist with the MEM_Str flag.
13601 */
13602 #define MEM_Null      0x0001   /* Value is NULL */
13603 #define MEM_Str       0x0002   /* Value is a string */
13604 #define MEM_Int       0x0004   /* Value is an integer */
13605 #define MEM_Real      0x0008   /* Value is a real number */
13606 #define MEM_Blob      0x0010   /* Value is a BLOB */
13607 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13608 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13609 #define MEM_Invalid   0x0080   /* Value is undefined */
13610 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13611 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
13612 
13613 
13614 /* Whenever Mem contains a valid string or blob representation, one of
13615 ** the following flags must be set to determine the memory management
13616 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13617 ** string is \000 or \u0000 terminated
13618 */
13619 #define MEM_Term      0x0200   /* String rep is nul terminated */
13620 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13621 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13622 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13623 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13624 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13625 #ifdef SQLITE_OMIT_INCRBLOB
13626   #undef MEM_Zero
13627   #define MEM_Zero 0x0000
13628 #endif
13629 
13630 /*
13631 ** Clear any existing type flags from a Mem and replace them with f
13632 */
13633 #define MemSetTypeFlag(p, f) \
13634    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13635 
13636 /*
13637 ** Return true if a memory cell is not marked as invalid.  This macro
13638 ** is for use inside assert() statements only.
13639 */
13640 #ifdef SQLITE_DEBUG
13641 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13642 #endif
13643 
13644 /*
13645 ** Each auxilliary data pointer stored by a user defined function 
13646 ** implementation calling sqlite3_set_auxdata() is stored in an instance
13647 ** of this structure. All such structures associated with a single VM
13648 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
13649 ** when the VM is halted (if not before).
13650 */
13651 struct AuxData {
13652   int iOp;                        /* Instruction number of OP_Function opcode */
13653   int iArg;                       /* Index of function argument. */
13654   void *pAux;                     /* Aux data pointer */
13655   void (*xDelete)(void *);        /* Destructor for the aux data */
13656   AuxData *pNext;                 /* Next element in list */
13657 };
13658 
13659 /*
13660 ** The "context" argument for a installable function.  A pointer to an
13661 ** instance of this structure is the first argument to the routines used
13662 ** implement the SQL functions.
13663 **
13664 ** There is a typedef for this structure in sqlite.h.  So all routines,
13665 ** even the public interface to SQLite, can use a pointer to this structure.
13666 ** But this file is the only place where the internal details of this
13667 ** structure are known.
13668 **
13669 ** This structure is defined inside of vdbeInt.h because it uses substructures
13670 ** (Mem) which are only defined there.
13671 */
13672 struct sqlite3_context {
13673   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13674   Mem s;                /* The return value is stored here */
13675   Mem *pMem;            /* Memory cell used to store aggregate context */
13676   CollSeq *pColl;       /* Collating sequence */
13677   Vdbe *pVdbe;          /* The VM that owns this context */
13678   int iOp;              /* Instruction number of OP_Function */
13679   int isError;          /* Error code returned by the function. */
13680   u8 skipFlag;          /* Skip skip accumulator loading if true */
13681   u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
13682 };
13683 
13684 /*
13685 ** An Explain object accumulates indented output which is helpful
13686 ** in describing recursive data structures.
13687 */
13688 struct Explain {
13689   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13690   StrAccum str;      /* The string being accumulated */
13691   int nIndent;       /* Number of elements in aIndent */
13692   u16 aIndent[100];  /* Levels of indentation */
13693   char zBase[100];   /* Initial space */
13694 };
13695 
13696 /* A bitfield type for use inside of structures.  Always follow with :N where
13697 ** N is the number of bits.
13698 */
13699 typedef unsigned bft;  /* Bit Field Type */
13700 
13701 /*
13702 ** An instance of the virtual machine.  This structure contains the complete
13703 ** state of the virtual machine.
13704 **
13705 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13706 ** is really a pointer to an instance of this structure.
13707 **
13708 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13709 ** any virtual table method invocations made by the vdbe program. It is
13710 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13711 ** variable is used for two purposes: to allow xDestroy methods to execute
13712 ** "DROP TABLE" statements and to prevent some nasty side effects of
13713 ** malloc failure when SQLite is invoked recursively by a virtual table 
13714 ** method function.
13715 */
13716 struct Vdbe {
13717   sqlite3 *db;            /* The database connection that owns this statement */
13718   Op *aOp;                /* Space to hold the virtual machine's program */
13719   Mem *aMem;              /* The memory locations */
13720   Mem **apArg;            /* Arguments to currently executing user function */
13721   Mem *aColName;          /* Column names to return */
13722   Mem *pResultSet;        /* Pointer to an array of results */
13723   int nMem;               /* Number of memory locations currently allocated */
13724   int nOp;                /* Number of instructions in the program */
13725   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13726   int nLabel;             /* Number of labels used */
13727   int *aLabel;            /* Space to hold the labels */
13728   u16 nResColumn;         /* Number of columns in one row of the result set */
13729   int nCursor;            /* Number of slots in apCsr[] */
13730   u32 magic;              /* Magic number for sanity checking */
13731   char *zErrMsg;          /* Error message written here */
13732   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13733   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13734   Mem *aVar;              /* Values for the OP_Variable opcode. */
13735   char **azVar;           /* Name of variables */
13736   ynVar nVar;             /* Number of entries in aVar[] */
13737   ynVar nzVar;            /* Number of entries in azVar[] */
13738   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13739   int pc;                 /* The program counter */
13740   int rc;                 /* Value to return */
13741   u8 errorAction;         /* Recovery action to do in case of an error */
13742   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13743   bft explain:2;          /* True if EXPLAIN present on SQL command */
13744   bft inVtabMethod:2;     /* See comments above */
13745   bft changeCntOn:1;      /* True to update the change-counter */
13746   bft expired:1;          /* True if the VM needs to be recompiled */
13747   bft runOnlyOnce:1;      /* Automatically expire on reset */
13748   bft usesStmtJournal:1;  /* True if uses a statement journal */
13749   bft readOnly:1;         /* True for statements that do not write */
13750   bft bIsReader:1;        /* True for statements that read */
13751   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13752   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13753   int nChange;            /* Number of db changes made since last reset */
13754   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13755   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13756   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13757   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
13758 #ifndef SQLITE_OMIT_TRACE
13759   i64 startTime;          /* Time when query started - used for profiling */
13760 #endif
13761   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
13762   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13763   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13764   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
13765   char *zSql;             /* Text of the SQL statement that generated this */
13766   void *pFree;            /* Free this when deleting the vdbe */
13767 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13768   Explain *pExplain;      /* The explainer */
13769   char *zExplain;         /* Explanation of data structures */
13770 #endif
13771   VdbeFrame *pFrame;      /* Parent frame */
13772   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13773   int nFrame;             /* Number of frames in pFrame list */
13774   u32 expmask;            /* Binding to these vars invalidates VM */
13775   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13776   int nOnceFlag;          /* Size of array aOnceFlag[] */
13777   u8 *aOnceFlag;          /* Flags for OP_Once */
13778   AuxData *pAuxData;      /* Linked list of auxdata allocations */
13779 };
13780 
13781 /*
13782 ** The following are allowed values for Vdbe.magic
13783 */
13784 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13785 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13786 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13787 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13788 
13789 /*
13790 ** Function prototypes
13791 */
13792 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13793 void sqliteVdbePopStack(Vdbe*,int);
13794 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13795 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13796 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13797 #endif
13798 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13799 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13800 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13801 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13802 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
13803 
13804 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13805 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13806 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13807 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13808 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13809 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13810 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13811 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13812 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13813 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13814 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13815 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13816 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13817 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13818 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13819 #ifdef SQLITE_OMIT_FLOATING_POINT
13820 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13821 #else
13822 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13823 #endif
13824 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13825 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13826 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13827 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13828 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13829 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13830 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13831 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13832 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13833 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13834 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13835 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
13836 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13837 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13838 #define VdbeMemRelease(X)  \
13839   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13840     sqlite3VdbeMemReleaseExternal(X);
13841 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13842 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13843 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13844 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13845 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13846 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13847 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13848 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13849 
13850 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13851 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13852 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13853 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13854 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13855 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13856 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
13857 
13858 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13859 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13860 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13861 #else
13862 # define sqlite3VdbeEnter(X)
13863 # define sqlite3VdbeLeave(X)
13864 #endif
13865 
13866 #ifdef SQLITE_DEBUG
13867 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13868 #endif
13869 
13870 #ifndef SQLITE_OMIT_FOREIGN_KEY
13871 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13872 #else
13873 # define sqlite3VdbeCheckFk(p,i) 0
13874 #endif
13875 
13876 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13877 #ifdef SQLITE_DEBUG
13878 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13879 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13880 #endif
13881 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13882 
13883 #ifndef SQLITE_OMIT_INCRBLOB
13884 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13885   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13886 #else
13887   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13888   #define ExpandBlob(P) SQLITE_OK
13889 #endif
13890 
13891 #endif /* !defined(_VDBEINT_H_) */
13892 
13893 /************** End of vdbeInt.h *********************************************/
13894 /************** Continuing where we left off in status.c *********************/
13895 
13896 /*
13897 ** Variables in which to record status information.
13898 */
13899 typedef struct sqlite3StatType sqlite3StatType;
13900 static SQLITE_WSD struct sqlite3StatType {
13901   int nowValue[10];         /* Current value */
13902   int mxValue[10];          /* Maximum value */
13903 } sqlite3Stat = { {0,}, {0,} };
13904 
13905 
13906 /* The "wsdStat" macro will resolve to the status information
13907 ** state vector.  If writable static data is unsupported on the target,
13908 ** we have to locate the state vector at run-time.  In the more common
13909 ** case where writable static data is supported, wsdStat can refer directly
13910 ** to the "sqlite3Stat" state vector declared above.
13911 */
13912 #ifdef SQLITE_OMIT_WSD
13913 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13914 # define wsdStat x[0]
13915 #else
13916 # define wsdStatInit
13917 # define wsdStat sqlite3Stat
13918 #endif
13919 
13920 /*
13921 ** Return the current value of a status parameter.
13922 */
13923 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13924   wsdStatInit;
13925   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13926   return wsdStat.nowValue[op];
13927 }
13928 
13929 /*
13930 ** Add N to the value of a status record.  It is assumed that the
13931 ** caller holds appropriate locks.
13932 */
13933 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13934   wsdStatInit;
13935   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13936   wsdStat.nowValue[op] += N;
13937   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13938     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13939   }
13940 }
13941 
13942 /*
13943 ** Set the value of a status to X.
13944 */
13945 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13946   wsdStatInit;
13947   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13948   wsdStat.nowValue[op] = X;
13949   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13950     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13951   }
13952 }
13953 
13954 /*
13955 ** Query status information.
13956 **
13957 ** This implementation assumes that reading or writing an aligned
13958 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13959 ** then this routine is not threadsafe.
13960 */
13961 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13962   wsdStatInit;
13963   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13964     return SQLITE_MISUSE_BKPT;
13965   }
13966   *pCurrent = wsdStat.nowValue[op];
13967   *pHighwater = wsdStat.mxValue[op];
13968   if( resetFlag ){
13969     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13970   }
13971   return SQLITE_OK;
13972 }
13973 
13974 /*
13975 ** Query status information for a single database connection
13976 */
13977 SQLITE_API int sqlite3_db_status(
13978   sqlite3 *db,          /* The database connection whose status is desired */
13979   int op,               /* Status verb */
13980   int *pCurrent,        /* Write current value here */
13981   int *pHighwater,      /* Write high-water mark here */
13982   int resetFlag         /* Reset high-water mark if true */
13983 ){
13984   int rc = SQLITE_OK;   /* Return code */
13985   sqlite3_mutex_enter(db->mutex);
13986   switch( op ){
13987     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13988       *pCurrent = db->lookaside.nOut;
13989       *pHighwater = db->lookaside.mxOut;
13990       if( resetFlag ){
13991         db->lookaside.mxOut = db->lookaside.nOut;
13992       }
13993       break;
13994     }
13995 
13996     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13997     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13998     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13999       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14000       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14001       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14002       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14003       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14004       *pCurrent = 0;
14005       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14006       if( resetFlag ){
14007         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14008       }
14009       break;
14010     }
14011 
14012     /* 
14013     ** Return an approximation for the amount of memory currently used
14014     ** by all pagers associated with the given database connection.  The
14015     ** highwater mark is meaningless and is returned as zero.
14016     */
14017     case SQLITE_DBSTATUS_CACHE_USED: {
14018       int totalUsed = 0;
14019       int i;
14020       sqlite3BtreeEnterAll(db);
14021       for(i=0; i<db->nDb; i++){
14022         Btree *pBt = db->aDb[i].pBt;
14023         if( pBt ){
14024           Pager *pPager = sqlite3BtreePager(pBt);
14025           totalUsed += sqlite3PagerMemUsed(pPager);
14026         }
14027       }
14028       sqlite3BtreeLeaveAll(db);
14029       *pCurrent = totalUsed;
14030       *pHighwater = 0;
14031       break;
14032     }
14033 
14034     /*
14035     ** *pCurrent gets an accurate estimate of the amount of memory used
14036     ** to store the schema for all databases (main, temp, and any ATTACHed
14037     ** databases.  *pHighwater is set to zero.
14038     */
14039     case SQLITE_DBSTATUS_SCHEMA_USED: {
14040       int i;                      /* Used to iterate through schemas */
14041       int nByte = 0;              /* Used to accumulate return value */
14042 
14043       sqlite3BtreeEnterAll(db);
14044       db->pnBytesFreed = &nByte;
14045       for(i=0; i<db->nDb; i++){
14046         Schema *pSchema = db->aDb[i].pSchema;
14047         if( ALWAYS(pSchema!=0) ){
14048           HashElem *p;
14049 
14050           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14051               pSchema->tblHash.count 
14052             + pSchema->trigHash.count
14053             + pSchema->idxHash.count
14054             + pSchema->fkeyHash.count
14055           );
14056           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14057           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14058           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14059           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14060 
14061           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14062             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14063           }
14064           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14065             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14066           }
14067         }
14068       }
14069       db->pnBytesFreed = 0;
14070       sqlite3BtreeLeaveAll(db);
14071 
14072       *pHighwater = 0;
14073       *pCurrent = nByte;
14074       break;
14075     }
14076 
14077     /*
14078     ** *pCurrent gets an accurate estimate of the amount of memory used
14079     ** to store all prepared statements.
14080     ** *pHighwater is set to zero.
14081     */
14082     case SQLITE_DBSTATUS_STMT_USED: {
14083       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
14084       int nByte = 0;              /* Used to accumulate return value */
14085 
14086       db->pnBytesFreed = &nByte;
14087       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14088         sqlite3VdbeClearObject(db, pVdbe);
14089         sqlite3DbFree(db, pVdbe);
14090       }
14091       db->pnBytesFreed = 0;
14092 
14093       *pHighwater = 0;
14094       *pCurrent = nByte;
14095 
14096       break;
14097     }
14098 
14099     /*
14100     ** Set *pCurrent to the total cache hits or misses encountered by all
14101     ** pagers the database handle is connected to. *pHighwater is always set 
14102     ** to zero.
14103     */
14104     case SQLITE_DBSTATUS_CACHE_HIT:
14105     case SQLITE_DBSTATUS_CACHE_MISS:
14106     case SQLITE_DBSTATUS_CACHE_WRITE:{
14107       int i;
14108       int nRet = 0;
14109       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14110       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14111 
14112       for(i=0; i<db->nDb; i++){
14113         if( db->aDb[i].pBt ){
14114           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14115           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14116         }
14117       }
14118       *pHighwater = 0;
14119       *pCurrent = nRet;
14120       break;
14121     }
14122 
14123     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14124     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
14125     ** have been satisfied.  The *pHighwater is always set to zero.
14126     */
14127     case SQLITE_DBSTATUS_DEFERRED_FKS: {
14128       *pHighwater = 0;
14129       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14130       break;
14131     }
14132 
14133     default: {
14134       rc = SQLITE_ERROR;
14135     }
14136   }
14137   sqlite3_mutex_leave(db->mutex);
14138   return rc;
14139 }
14140 
14141 /************** End of status.c **********************************************/
14142 /************** Begin file date.c ********************************************/
14143 /*
14144 ** 2003 October 31
14145 **
14146 ** The author disclaims copyright to this source code.  In place of
14147 ** a legal notice, here is a blessing:
14148 **
14149 **    May you do good and not evil.
14150 **    May you find forgiveness for yourself and forgive others.
14151 **    May you share freely, never taking more than you give.
14152 **
14153 *************************************************************************
14154 ** This file contains the C functions that implement date and time
14155 ** functions for SQLite.  
14156 **
14157 ** There is only one exported symbol in this file - the function
14158 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14159 ** All other code has file scope.
14160 **
14161 ** SQLite processes all times and dates as Julian Day numbers.  The
14162 ** dates and times are stored as the number of days since noon
14163 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14164 ** calendar system. 
14165 **
14166 ** 1970-01-01 00:00:00 is JD 2440587.5
14167 ** 2000-01-01 00:00:00 is JD 2451544.5
14168 **
14169 ** This implemention requires years to be expressed as a 4-digit number
14170 ** which means that only dates between 0000-01-01 and 9999-12-31 can
14171 ** be represented, even though julian day numbers allow a much wider
14172 ** range of dates.
14173 **
14174 ** The Gregorian calendar system is used for all dates and times,
14175 ** even those that predate the Gregorian calendar.  Historians usually
14176 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14177 ** dates afterwards, depending on locale.  Beware of this difference.
14178 **
14179 ** The conversion algorithms are implemented based on descriptions
14180 ** in the following text:
14181 **
14182 **      Jean Meeus
14183 **      Astronomical Algorithms, 2nd Edition, 1998
14184 **      ISBM 0-943396-61-1
14185 **      Willmann-Bell, Inc
14186 **      Richmond, Virginia (USA)
14187 */
14188 /* #include <stdlib.h> */
14189 /* #include <assert.h> */
14190 #include <time.h>
14191 
14192 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14193 
14194 
14195 /*
14196 ** A structure for holding a single date and time.
14197 */
14198 typedef struct DateTime DateTime;
14199 struct DateTime {
14200   sqlite3_int64 iJD; /* The julian day number times 86400000 */
14201   int Y, M, D;       /* Year, month, and day */
14202   int h, m;          /* Hour and minutes */
14203   int tz;            /* Timezone offset in minutes */
14204   double s;          /* Seconds */
14205   char validYMD;     /* True (1) if Y,M,D are valid */
14206   char validHMS;     /* True (1) if h,m,s are valid */
14207   char validJD;      /* True (1) if iJD is valid */
14208   char validTZ;      /* True (1) if tz is valid */
14209 };
14210 
14211 
14212 /*
14213 ** Convert zDate into one or more integers.  Additional arguments
14214 ** come in groups of 5 as follows:
14215 **
14216 **       N       number of digits in the integer
14217 **       min     minimum allowed value of the integer
14218 **       max     maximum allowed value of the integer
14219 **       nextC   first character after the integer
14220 **       pVal    where to write the integers value.
14221 **
14222 ** Conversions continue until one with nextC==0 is encountered.
14223 ** The function returns the number of successful conversions.
14224 */
14225 static int getDigits(const char *zDate, ...){
14226   va_list ap;
14227   int val;
14228   int N;
14229   int min;
14230   int max;
14231   int nextC;
14232   int *pVal;
14233   int cnt = 0;
14234   va_start(ap, zDate);
14235   do{
14236     N = va_arg(ap, int);
14237     min = va_arg(ap, int);
14238     max = va_arg(ap, int);
14239     nextC = va_arg(ap, int);
14240     pVal = va_arg(ap, int*);
14241     val = 0;
14242     while( N-- ){
14243       if( !sqlite3Isdigit(*zDate) ){
14244         goto end_getDigits;
14245       }
14246       val = val*10 + *zDate - '0';
14247       zDate++;
14248     }
14249     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14250       goto end_getDigits;
14251     }
14252     *pVal = val;
14253     zDate++;
14254     cnt++;
14255   }while( nextC );
14256 end_getDigits:
14257   va_end(ap);
14258   return cnt;
14259 }
14260 
14261 /*
14262 ** Parse a timezone extension on the end of a date-time.
14263 ** The extension is of the form:
14264 **
14265 **        (+/-)HH:MM
14266 **
14267 ** Or the "zulu" notation:
14268 **
14269 **        Z
14270 **
14271 ** If the parse is successful, write the number of minutes
14272 ** of change in p->tz and return 0.  If a parser error occurs,
14273 ** return non-zero.
14274 **
14275 ** A missing specifier is not considered an error.
14276 */
14277 static int parseTimezone(const char *zDate, DateTime *p){
14278   int sgn = 0;
14279   int nHr, nMn;
14280   int c;
14281   while( sqlite3Isspace(*zDate) ){ zDate++; }
14282   p->tz = 0;
14283   c = *zDate;
14284   if( c=='-' ){
14285     sgn = -1;
14286   }else if( c=='+' ){
14287     sgn = +1;
14288   }else if( c=='Z' || c=='z' ){
14289     zDate++;
14290     goto zulu_time;
14291   }else{
14292     return c!=0;
14293   }
14294   zDate++;
14295   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14296     return 1;
14297   }
14298   zDate += 5;
14299   p->tz = sgn*(nMn + nHr*60);
14300 zulu_time:
14301   while( sqlite3Isspace(*zDate) ){ zDate++; }
14302   return *zDate!=0;
14303 }
14304 
14305 /*
14306 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14307 ** The HH, MM, and SS must each be exactly 2 digits.  The
14308 ** fractional seconds FFFF can be one or more digits.
14309 **
14310 ** Return 1 if there is a parsing error and 0 on success.
14311 */
14312 static int parseHhMmSs(const char *zDate, DateTime *p){
14313   int h, m, s;
14314   double ms = 0.0;
14315   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14316     return 1;
14317   }
14318   zDate += 5;
14319   if( *zDate==':' ){
14320     zDate++;
14321     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14322       return 1;
14323     }
14324     zDate += 2;
14325     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14326       double rScale = 1.0;
14327       zDate++;
14328       while( sqlite3Isdigit(*zDate) ){
14329         ms = ms*10.0 + *zDate - '0';
14330         rScale *= 10.0;
14331         zDate++;
14332       }
14333       ms /= rScale;
14334     }
14335   }else{
14336     s = 0;
14337   }
14338   p->validJD = 0;
14339   p->validHMS = 1;
14340   p->h = h;
14341   p->m = m;
14342   p->s = s + ms;
14343   if( parseTimezone(zDate, p) ) return 1;
14344   p->validTZ = (p->tz!=0)?1:0;
14345   return 0;
14346 }
14347 
14348 /*
14349 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14350 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14351 **
14352 ** Reference:  Meeus page 61
14353 */
14354 static void computeJD(DateTime *p){
14355   int Y, M, D, A, B, X1, X2;
14356 
14357   if( p->validJD ) return;
14358   if( p->validYMD ){
14359     Y = p->Y;
14360     M = p->M;
14361     D = p->D;
14362   }else{
14363     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14364     M = 1;
14365     D = 1;
14366   }
14367   if( M<=2 ){
14368     Y--;
14369     M += 12;
14370   }
14371   A = Y/100;
14372   B = 2 - A + (A/4);
14373   X1 = 36525*(Y+4716)/100;
14374   X2 = 306001*(M+1)/10000;
14375   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14376   p->validJD = 1;
14377   if( p->validHMS ){
14378     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14379     if( p->validTZ ){
14380       p->iJD -= p->tz*60000;
14381       p->validYMD = 0;
14382       p->validHMS = 0;
14383       p->validTZ = 0;
14384     }
14385   }
14386 }
14387 
14388 /*
14389 ** Parse dates of the form
14390 **
14391 **     YYYY-MM-DD HH:MM:SS.FFF
14392 **     YYYY-MM-DD HH:MM:SS
14393 **     YYYY-MM-DD HH:MM
14394 **     YYYY-MM-DD
14395 **
14396 ** Write the result into the DateTime structure and return 0
14397 ** on success and 1 if the input string is not a well-formed
14398 ** date.
14399 */
14400 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14401   int Y, M, D, neg;
14402 
14403   if( zDate[0]=='-' ){
14404     zDate++;
14405     neg = 1;
14406   }else{
14407     neg = 0;
14408   }
14409   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14410     return 1;
14411   }
14412   zDate += 10;
14413   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14414   if( parseHhMmSs(zDate, p)==0 ){
14415     /* We got the time */
14416   }else if( *zDate==0 ){
14417     p->validHMS = 0;
14418   }else{
14419     return 1;
14420   }
14421   p->validJD = 0;
14422   p->validYMD = 1;
14423   p->Y = neg ? -Y : Y;
14424   p->M = M;
14425   p->D = D;
14426   if( p->validTZ ){
14427     computeJD(p);
14428   }
14429   return 0;
14430 }
14431 
14432 /*
14433 ** Set the time to the current time reported by the VFS.
14434 **
14435 ** Return the number of errors.
14436 */
14437 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14438   p->iJD = sqlite3StmtCurrentTime(context);
14439   if( p->iJD>0 ){
14440     p->validJD = 1;
14441     return 0;
14442   }else{
14443     return 1;
14444   }
14445 }
14446 
14447 /*
14448 ** Attempt to parse the given string into a Julian Day Number.  Return
14449 ** the number of errors.
14450 **
14451 ** The following are acceptable forms for the input string:
14452 **
14453 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14454 **      DDDD.DD 
14455 **      now
14456 **
14457 ** In the first form, the +/-HH:MM is always optional.  The fractional
14458 ** seconds extension (the ".FFF") is optional.  The seconds portion
14459 ** (":SS.FFF") is option.  The year and date can be omitted as long
14460 ** as there is a time string.  The time string can be omitted as long
14461 ** as there is a year and date.
14462 */
14463 static int parseDateOrTime(
14464   sqlite3_context *context, 
14465   const char *zDate, 
14466   DateTime *p
14467 ){
14468   double r;
14469   if( parseYyyyMmDd(zDate,p)==0 ){
14470     return 0;
14471   }else if( parseHhMmSs(zDate, p)==0 ){
14472     return 0;
14473   }else if( sqlite3StrICmp(zDate,"now")==0){
14474     return setDateTimeToCurrent(context, p);
14475   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14476     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14477     p->validJD = 1;
14478     return 0;
14479   }
14480   return 1;
14481 }
14482 
14483 /*
14484 ** Compute the Year, Month, and Day from the julian day number.
14485 */
14486 static void computeYMD(DateTime *p){
14487   int Z, A, B, C, D, E, X1;
14488   if( p->validYMD ) return;
14489   if( !p->validJD ){
14490     p->Y = 2000;
14491     p->M = 1;
14492     p->D = 1;
14493   }else{
14494     Z = (int)((p->iJD + 43200000)/86400000);
14495     A = (int)((Z - 1867216.25)/36524.25);
14496     A = Z + 1 + A - (A/4);
14497     B = A + 1524;
14498     C = (int)((B - 122.1)/365.25);
14499     D = (36525*C)/100;
14500     E = (int)((B-D)/30.6001);
14501     X1 = (int)(30.6001*E);
14502     p->D = B - D - X1;
14503     p->M = E<14 ? E-1 : E-13;
14504     p->Y = p->M>2 ? C - 4716 : C - 4715;
14505   }
14506   p->validYMD = 1;
14507 }
14508 
14509 /*
14510 ** Compute the Hour, Minute, and Seconds from the julian day number.
14511 */
14512 static void computeHMS(DateTime *p){
14513   int s;
14514   if( p->validHMS ) return;
14515   computeJD(p);
14516   s = (int)((p->iJD + 43200000) % 86400000);
14517   p->s = s/1000.0;
14518   s = (int)p->s;
14519   p->s -= s;
14520   p->h = s/3600;
14521   s -= p->h*3600;
14522   p->m = s/60;
14523   p->s += s - p->m*60;
14524   p->validHMS = 1;
14525 }
14526 
14527 /*
14528 ** Compute both YMD and HMS
14529 */
14530 static void computeYMD_HMS(DateTime *p){
14531   computeYMD(p);
14532   computeHMS(p);
14533 }
14534 
14535 /*
14536 ** Clear the YMD and HMS and the TZ
14537 */
14538 static void clearYMD_HMS_TZ(DateTime *p){
14539   p->validYMD = 0;
14540   p->validHMS = 0;
14541   p->validTZ = 0;
14542 }
14543 
14544 /*
14545 ** On recent Windows platforms, the localtime_s() function is available
14546 ** as part of the "Secure CRT". It is essentially equivalent to 
14547 ** localtime_r() available under most POSIX platforms, except that the 
14548 ** order of the parameters is reversed.
14549 **
14550 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14551 **
14552 ** If the user has not indicated to use localtime_r() or localtime_s()
14553 ** already, check for an MSVC build environment that provides 
14554 ** localtime_s().
14555 */
14556 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14557      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14558 #define HAVE_LOCALTIME_S 1
14559 #endif
14560 
14561 #ifndef SQLITE_OMIT_LOCALTIME
14562 /*
14563 ** The following routine implements the rough equivalent of localtime_r()
14564 ** using whatever operating-system specific localtime facility that
14565 ** is available.  This routine returns 0 on success and
14566 ** non-zero on any kind of error.
14567 **
14568 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14569 ** routine will always fail.
14570 **
14571 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
14572 ** library function localtime_r() is used to assist in the calculation of
14573 ** local time.
14574 */
14575 static int osLocaltime(time_t *t, struct tm *pTm){
14576   int rc;
14577 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14578       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14579   struct tm *pX;
14580 #if SQLITE_THREADSAFE>0
14581   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14582 #endif
14583   sqlite3_mutex_enter(mutex);
14584   pX = localtime(t);
14585 #ifndef SQLITE_OMIT_BUILTIN_TEST
14586   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14587 #endif
14588   if( pX ) *pTm = *pX;
14589   sqlite3_mutex_leave(mutex);
14590   rc = pX==0;
14591 #else
14592 #ifndef SQLITE_OMIT_BUILTIN_TEST
14593   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14594 #endif
14595 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14596   rc = localtime_r(t, pTm)==0;
14597 #else
14598   rc = localtime_s(pTm, t);
14599 #endif /* HAVE_LOCALTIME_R */
14600 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14601   return rc;
14602 }
14603 #endif /* SQLITE_OMIT_LOCALTIME */
14604 
14605 
14606 #ifndef SQLITE_OMIT_LOCALTIME
14607 /*
14608 ** Compute the difference (in milliseconds) between localtime and UTC
14609 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14610 ** return this value and set *pRc to SQLITE_OK. 
14611 **
14612 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14613 ** is undefined in this case.
14614 */
14615 static sqlite3_int64 localtimeOffset(
14616   DateTime *p,                    /* Date at which to calculate offset */
14617   sqlite3_context *pCtx,          /* Write error here if one occurs */
14618   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14619 ){
14620   DateTime x, y;
14621   time_t t;
14622   struct tm sLocal;
14623 
14624   /* Initialize the contents of sLocal to avoid a compiler warning. */
14625   memset(&sLocal, 0, sizeof(sLocal));
14626 
14627   x = *p;
14628   computeYMD_HMS(&x);
14629   if( x.Y<1971 || x.Y>=2038 ){
14630     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
14631     ** works for years between 1970 and 2037. For dates outside this range,
14632     ** SQLite attempts to map the year into an equivalent year within this
14633     ** range, do the calculation, then map the year back.
14634     */
14635     x.Y = 2000;
14636     x.M = 1;
14637     x.D = 1;
14638     x.h = 0;
14639     x.m = 0;
14640     x.s = 0.0;
14641   } else {
14642     int s = (int)(x.s + 0.5);
14643     x.s = s;
14644   }
14645   x.tz = 0;
14646   x.validJD = 0;
14647   computeJD(&x);
14648   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14649   if( osLocaltime(&t, &sLocal) ){
14650     sqlite3_result_error(pCtx, "local time unavailable", -1);
14651     *pRc = SQLITE_ERROR;
14652     return 0;
14653   }
14654   y.Y = sLocal.tm_year + 1900;
14655   y.M = sLocal.tm_mon + 1;
14656   y.D = sLocal.tm_mday;
14657   y.h = sLocal.tm_hour;
14658   y.m = sLocal.tm_min;
14659   y.s = sLocal.tm_sec;
14660   y.validYMD = 1;
14661   y.validHMS = 1;
14662   y.validJD = 0;
14663   y.validTZ = 0;
14664   computeJD(&y);
14665   *pRc = SQLITE_OK;
14666   return y.iJD - x.iJD;
14667 }
14668 #endif /* SQLITE_OMIT_LOCALTIME */
14669 
14670 /*
14671 ** Process a modifier to a date-time stamp.  The modifiers are
14672 ** as follows:
14673 **
14674 **     NNN days
14675 **     NNN hours
14676 **     NNN minutes
14677 **     NNN.NNNN seconds
14678 **     NNN months
14679 **     NNN years
14680 **     start of month
14681 **     start of year
14682 **     start of week
14683 **     start of day
14684 **     weekday N
14685 **     unixepoch
14686 **     localtime
14687 **     utc
14688 **
14689 ** Return 0 on success and 1 if there is any kind of error. If the error
14690 ** is in a system call (i.e. localtime()), then an error message is written
14691 ** to context pCtx. If the error is an unrecognized modifier, no error is
14692 ** written to pCtx.
14693 */
14694 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14695   int rc = 1;
14696   int n;
14697   double r;
14698   char *z, zBuf[30];
14699   z = zBuf;
14700   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14701     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14702   }
14703   z[n] = 0;
14704   switch( z[0] ){
14705 #ifndef SQLITE_OMIT_LOCALTIME
14706     case 'l': {
14707       /*    localtime
14708       **
14709       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14710       ** show local time.
14711       */
14712       if( strcmp(z, "localtime")==0 ){
14713         computeJD(p);
14714         p->iJD += localtimeOffset(p, pCtx, &rc);
14715         clearYMD_HMS_TZ(p);
14716       }
14717       break;
14718     }
14719 #endif
14720     case 'u': {
14721       /*
14722       **    unixepoch
14723       **
14724       ** Treat the current value of p->iJD as the number of
14725       ** seconds since 1970.  Convert to a real julian day number.
14726       */
14727       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14728         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14729         clearYMD_HMS_TZ(p);
14730         rc = 0;
14731       }
14732 #ifndef SQLITE_OMIT_LOCALTIME
14733       else if( strcmp(z, "utc")==0 ){
14734         sqlite3_int64 c1;
14735         computeJD(p);
14736         c1 = localtimeOffset(p, pCtx, &rc);
14737         if( rc==SQLITE_OK ){
14738           p->iJD -= c1;
14739           clearYMD_HMS_TZ(p);
14740           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14741         }
14742       }
14743 #endif
14744       break;
14745     }
14746     case 'w': {
14747       /*
14748       **    weekday N
14749       **
14750       ** Move the date to the same time on the next occurrence of
14751       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14752       ** date is already on the appropriate weekday, this is a no-op.
14753       */
14754       if( strncmp(z, "weekday ", 8)==0
14755                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14756                && (n=(int)r)==r && n>=0 && r<7 ){
14757         sqlite3_int64 Z;
14758         computeYMD_HMS(p);
14759         p->validTZ = 0;
14760         p->validJD = 0;
14761         computeJD(p);
14762         Z = ((p->iJD + 129600000)/86400000) % 7;
14763         if( Z>n ) Z -= 7;
14764         p->iJD += (n - Z)*86400000;
14765         clearYMD_HMS_TZ(p);
14766         rc = 0;
14767       }
14768       break;
14769     }
14770     case 's': {
14771       /*
14772       **    start of TTTTT
14773       **
14774       ** Move the date backwards to the beginning of the current day,
14775       ** or month or year.
14776       */
14777       if( strncmp(z, "start of ", 9)!=0 ) break;
14778       z += 9;
14779       computeYMD(p);
14780       p->validHMS = 1;
14781       p->h = p->m = 0;
14782       p->s = 0.0;
14783       p->validTZ = 0;
14784       p->validJD = 0;
14785       if( strcmp(z,"month")==0 ){
14786         p->D = 1;
14787         rc = 0;
14788       }else if( strcmp(z,"year")==0 ){
14789         computeYMD(p);
14790         p->M = 1;
14791         p->D = 1;
14792         rc = 0;
14793       }else if( strcmp(z,"day")==0 ){
14794         rc = 0;
14795       }
14796       break;
14797     }
14798     case '+':
14799     case '-':
14800     case '0':
14801     case '1':
14802     case '2':
14803     case '3':
14804     case '4':
14805     case '5':
14806     case '6':
14807     case '7':
14808     case '8':
14809     case '9': {
14810       double rRounder;
14811       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14812       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14813         rc = 1;
14814         break;
14815       }
14816       if( z[n]==':' ){
14817         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14818         ** specified number of hours, minutes, seconds, and fractional seconds
14819         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14820         ** omitted.
14821         */
14822         const char *z2 = z;
14823         DateTime tx;
14824         sqlite3_int64 day;
14825         if( !sqlite3Isdigit(*z2) ) z2++;
14826         memset(&tx, 0, sizeof(tx));
14827         if( parseHhMmSs(z2, &tx) ) break;
14828         computeJD(&tx);
14829         tx.iJD -= 43200000;
14830         day = tx.iJD/86400000;
14831         tx.iJD -= day*86400000;
14832         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14833         computeJD(p);
14834         clearYMD_HMS_TZ(p);
14835         p->iJD += tx.iJD;
14836         rc = 0;
14837         break;
14838       }
14839       z += n;
14840       while( sqlite3Isspace(*z) ) z++;
14841       n = sqlite3Strlen30(z);
14842       if( n>10 || n<3 ) break;
14843       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14844       computeJD(p);
14845       rc = 0;
14846       rRounder = r<0 ? -0.5 : +0.5;
14847       if( n==3 && strcmp(z,"day")==0 ){
14848         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14849       }else if( n==4 && strcmp(z,"hour")==0 ){
14850         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14851       }else if( n==6 && strcmp(z,"minute")==0 ){
14852         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14853       }else if( n==6 && strcmp(z,"second")==0 ){
14854         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14855       }else if( n==5 && strcmp(z,"month")==0 ){
14856         int x, y;
14857         computeYMD_HMS(p);
14858         p->M += (int)r;
14859         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14860         p->Y += x;
14861         p->M -= x*12;
14862         p->validJD = 0;
14863         computeJD(p);
14864         y = (int)r;
14865         if( y!=r ){
14866           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14867         }
14868       }else if( n==4 && strcmp(z,"year")==0 ){
14869         int y = (int)r;
14870         computeYMD_HMS(p);
14871         p->Y += y;
14872         p->validJD = 0;
14873         computeJD(p);
14874         if( y!=r ){
14875           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14876         }
14877       }else{
14878         rc = 1;
14879       }
14880       clearYMD_HMS_TZ(p);
14881       break;
14882     }
14883     default: {
14884       break;
14885     }
14886   }
14887   return rc;
14888 }
14889 
14890 /*
14891 ** Process time function arguments.  argv[0] is a date-time stamp.
14892 ** argv[1] and following are modifiers.  Parse them all and write
14893 ** the resulting time into the DateTime structure p.  Return 0
14894 ** on success and 1 if there are any errors.
14895 **
14896 ** If there are zero parameters (if even argv[0] is undefined)
14897 ** then assume a default value of "now" for argv[0].
14898 */
14899 static int isDate(
14900   sqlite3_context *context, 
14901   int argc, 
14902   sqlite3_value **argv, 
14903   DateTime *p
14904 ){
14905   int i;
14906   const unsigned char *z;
14907   int eType;
14908   memset(p, 0, sizeof(*p));
14909   if( argc==0 ){
14910     return setDateTimeToCurrent(context, p);
14911   }
14912   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14913                    || eType==SQLITE_INTEGER ){
14914     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14915     p->validJD = 1;
14916   }else{
14917     z = sqlite3_value_text(argv[0]);
14918     if( !z || parseDateOrTime(context, (char*)z, p) ){
14919       return 1;
14920     }
14921   }
14922   for(i=1; i<argc; i++){
14923     z = sqlite3_value_text(argv[i]);
14924     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14925   }
14926   return 0;
14927 }
14928 
14929 
14930 /*
14931 ** The following routines implement the various date and time functions
14932 ** of SQLite.
14933 */
14934 
14935 /*
14936 **    julianday( TIMESTRING, MOD, MOD, ...)
14937 **
14938 ** Return the julian day number of the date specified in the arguments
14939 */
14940 static void juliandayFunc(
14941   sqlite3_context *context,
14942   int argc,
14943   sqlite3_value **argv
14944 ){
14945   DateTime x;
14946   if( isDate(context, argc, argv, &x)==0 ){
14947     computeJD(&x);
14948     sqlite3_result_double(context, x.iJD/86400000.0);
14949   }
14950 }
14951 
14952 /*
14953 **    datetime( TIMESTRING, MOD, MOD, ...)
14954 **
14955 ** Return YYYY-MM-DD HH:MM:SS
14956 */
14957 static void datetimeFunc(
14958   sqlite3_context *context,
14959   int argc,
14960   sqlite3_value **argv
14961 ){
14962   DateTime x;
14963   if( isDate(context, argc, argv, &x)==0 ){
14964     char zBuf[100];
14965     computeYMD_HMS(&x);
14966     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14967                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14968     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14969   }
14970 }
14971 
14972 /*
14973 **    time( TIMESTRING, MOD, MOD, ...)
14974 **
14975 ** Return HH:MM:SS
14976 */
14977 static void timeFunc(
14978   sqlite3_context *context,
14979   int argc,
14980   sqlite3_value **argv
14981 ){
14982   DateTime x;
14983   if( isDate(context, argc, argv, &x)==0 ){
14984     char zBuf[100];
14985     computeHMS(&x);
14986     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14987     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14988   }
14989 }
14990 
14991 /*
14992 **    date( TIMESTRING, MOD, MOD, ...)
14993 **
14994 ** Return YYYY-MM-DD
14995 */
14996 static void dateFunc(
14997   sqlite3_context *context,
14998   int argc,
14999   sqlite3_value **argv
15000 ){
15001   DateTime x;
15002   if( isDate(context, argc, argv, &x)==0 ){
15003     char zBuf[100];
15004     computeYMD(&x);
15005     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15006     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15007   }
15008 }
15009 
15010 /*
15011 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15012 **
15013 ** Return a string described by FORMAT.  Conversions as follows:
15014 **
15015 **   %d  day of month
15016 **   %f  ** fractional seconds  SS.SSS
15017 **   %H  hour 00-24
15018 **   %j  day of year 000-366
15019 **   %J  ** Julian day number
15020 **   %m  month 01-12
15021 **   %M  minute 00-59
15022 **   %s  seconds since 1970-01-01
15023 **   %S  seconds 00-59
15024 **   %w  day of week 0-6  sunday==0
15025 **   %W  week of year 00-53
15026 **   %Y  year 0000-9999
15027 **   %%  %
15028 */
15029 static void strftimeFunc(
15030   sqlite3_context *context,
15031   int argc,
15032   sqlite3_value **argv
15033 ){
15034   DateTime x;
15035   u64 n;
15036   size_t i,j;
15037   char *z;
15038   sqlite3 *db;
15039   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15040   char zBuf[100];
15041   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15042   db = sqlite3_context_db_handle(context);
15043   for(i=0, n=1; zFmt[i]; i++, n++){
15044     if( zFmt[i]=='%' ){
15045       switch( zFmt[i+1] ){
15046         case 'd':
15047         case 'H':
15048         case 'm':
15049         case 'M':
15050         case 'S':
15051         case 'W':
15052           n++;
15053           /* fall thru */
15054         case 'w':
15055         case '%':
15056           break;
15057         case 'f':
15058           n += 8;
15059           break;
15060         case 'j':
15061           n += 3;
15062           break;
15063         case 'Y':
15064           n += 8;
15065           break;
15066         case 's':
15067         case 'J':
15068           n += 50;
15069           break;
15070         default:
15071           return;  /* ERROR.  return a NULL */
15072       }
15073       i++;
15074     }
15075   }
15076   testcase( n==sizeof(zBuf)-1 );
15077   testcase( n==sizeof(zBuf) );
15078   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15079   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15080   if( n<sizeof(zBuf) ){
15081     z = zBuf;
15082   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15083     sqlite3_result_error_toobig(context);
15084     return;
15085   }else{
15086     z = sqlite3DbMallocRaw(db, (int)n);
15087     if( z==0 ){
15088       sqlite3_result_error_nomem(context);
15089       return;
15090     }
15091   }
15092   computeJD(&x);
15093   computeYMD_HMS(&x);
15094   for(i=j=0; zFmt[i]; i++){
15095     if( zFmt[i]!='%' ){
15096       z[j++] = zFmt[i];
15097     }else{
15098       i++;
15099       switch( zFmt[i] ){
15100         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15101         case 'f': {
15102           double s = x.s;
15103           if( s>59.999 ) s = 59.999;
15104           sqlite3_snprintf(7, &z[j],"%06.3f", s);
15105           j += sqlite3Strlen30(&z[j]);
15106           break;
15107         }
15108         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15109         case 'W': /* Fall thru */
15110         case 'j': {
15111           int nDay;             /* Number of days since 1st day of year */
15112           DateTime y = x;
15113           y.validJD = 0;
15114           y.M = 1;
15115           y.D = 1;
15116           computeJD(&y);
15117           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15118           if( zFmt[i]=='W' ){
15119             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15120             wd = (int)(((x.iJD+43200000)/86400000)%7);
15121             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15122             j += 2;
15123           }else{
15124             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15125             j += 3;
15126           }
15127           break;
15128         }
15129         case 'J': {
15130           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15131           j+=sqlite3Strlen30(&z[j]);
15132           break;
15133         }
15134         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15135         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15136         case 's': {
15137           sqlite3_snprintf(30,&z[j],"%lld",
15138                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
15139           j += sqlite3Strlen30(&z[j]);
15140           break;
15141         }
15142         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15143         case 'w': {
15144           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15145           break;
15146         }
15147         case 'Y': {
15148           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15149           break;
15150         }
15151         default:   z[j++] = '%'; break;
15152       }
15153     }
15154   }
15155   z[j] = 0;
15156   sqlite3_result_text(context, z, -1,
15157                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15158 }
15159 
15160 /*
15161 ** current_time()
15162 **
15163 ** This function returns the same value as time('now').
15164 */
15165 static void ctimeFunc(
15166   sqlite3_context *context,
15167   int NotUsed,
15168   sqlite3_value **NotUsed2
15169 ){
15170   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15171   timeFunc(context, 0, 0);
15172 }
15173 
15174 /*
15175 ** current_date()
15176 **
15177 ** This function returns the same value as date('now').
15178 */
15179 static void cdateFunc(
15180   sqlite3_context *context,
15181   int NotUsed,
15182   sqlite3_value **NotUsed2
15183 ){
15184   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15185   dateFunc(context, 0, 0);
15186 }
15187 
15188 /*
15189 ** current_timestamp()
15190 **
15191 ** This function returns the same value as datetime('now').
15192 */
15193 static void ctimestampFunc(
15194   sqlite3_context *context,
15195   int NotUsed,
15196   sqlite3_value **NotUsed2
15197 ){
15198   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15199   datetimeFunc(context, 0, 0);
15200 }
15201 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15202 
15203 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15204 /*
15205 ** If the library is compiled to omit the full-scale date and time
15206 ** handling (to get a smaller binary), the following minimal version
15207 ** of the functions current_time(), current_date() and current_timestamp()
15208 ** are included instead. This is to support column declarations that
15209 ** include "DEFAULT CURRENT_TIME" etc.
15210 **
15211 ** This function uses the C-library functions time(), gmtime()
15212 ** and strftime(). The format string to pass to strftime() is supplied
15213 ** as the user-data for the function.
15214 */
15215 static void currentTimeFunc(
15216   sqlite3_context *context,
15217   int argc,
15218   sqlite3_value **argv
15219 ){
15220   time_t t;
15221   char *zFormat = (char *)sqlite3_user_data(context);
15222   sqlite3 *db;
15223   sqlite3_int64 iT;
15224   struct tm *pTm;
15225   struct tm sNow;
15226   char zBuf[20];
15227 
15228   UNUSED_PARAMETER(argc);
15229   UNUSED_PARAMETER(argv);
15230 
15231   iT = sqlite3StmtCurrentTime(context);
15232   if( iT<=0 ) return;
15233   t = iT/1000 - 10000*(sqlite3_int64)21086676;
15234 #ifdef HAVE_GMTIME_R
15235   pTm = gmtime_r(&t, &sNow);
15236 #else
15237   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15238   pTm = gmtime(&t);
15239   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15240   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15241 #endif
15242   if( pTm ){
15243     strftime(zBuf, 20, zFormat, &sNow);
15244     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15245   }
15246 }
15247 #endif
15248 
15249 /*
15250 ** This function registered all of the above C functions as SQL
15251 ** functions.  This should be the only routine in this file with
15252 ** external linkage.
15253 */
15254 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15255   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15256 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15257     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
15258     FUNCTION(date,             -1, 0, 0, dateFunc      ),
15259     FUNCTION(time,             -1, 0, 0, timeFunc      ),
15260     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
15261     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
15262     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
15263     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15264     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
15265 #else
15266     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
15267     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
15268     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15269 #endif
15270   };
15271   int i;
15272   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15273   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15274 
15275   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15276     sqlite3FuncDefInsert(pHash, &aFunc[i]);
15277   }
15278 }
15279 
15280 /************** End of date.c ************************************************/
15281 /************** Begin file os.c **********************************************/
15282 /*
15283 ** 2005 November 29
15284 **
15285 ** The author disclaims copyright to this source code.  In place of
15286 ** a legal notice, here is a blessing:
15287 **
15288 **    May you do good and not evil.
15289 **    May you find forgiveness for yourself and forgive others.
15290 **    May you share freely, never taking more than you give.
15291 **
15292 ******************************************************************************
15293 **
15294 ** This file contains OS interface code that is common to all
15295 ** architectures.
15296 */
15297 #define _SQLITE_OS_C_ 1
15298 #undef _SQLITE_OS_C_
15299 
15300 /*
15301 ** The default SQLite sqlite3_vfs implementations do not allocate
15302 ** memory (actually, os_unix.c allocates a small amount of memory
15303 ** from within OsOpen()), but some third-party implementations may.
15304 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15305 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15306 **
15307 ** The following functions are instrumented for malloc() failure 
15308 ** testing:
15309 **
15310 **     sqlite3OsRead()
15311 **     sqlite3OsWrite()
15312 **     sqlite3OsSync()
15313 **     sqlite3OsFileSize()
15314 **     sqlite3OsLock()
15315 **     sqlite3OsCheckReservedLock()
15316 **     sqlite3OsFileControl()
15317 **     sqlite3OsShmMap()
15318 **     sqlite3OsOpen()
15319 **     sqlite3OsDelete()
15320 **     sqlite3OsAccess()
15321 **     sqlite3OsFullPathname()
15322 **
15323 */
15324 #if defined(SQLITE_TEST)
15325 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15326   #define DO_OS_MALLOC_TEST(x)                                       \
15327   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
15328     void *pTstAlloc = sqlite3Malloc(10);                             \
15329     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15330     sqlite3_free(pTstAlloc);                                         \
15331   }
15332 #else
15333   #define DO_OS_MALLOC_TEST(x)
15334 #endif
15335 
15336 /*
15337 ** The following routines are convenience wrappers around methods
15338 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15339 ** of this would be completely automatic if SQLite were coded using
15340 ** C++ instead of plain old C.
15341 */
15342 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15343   int rc = SQLITE_OK;
15344   if( pId->pMethods ){
15345     rc = pId->pMethods->xClose(pId);
15346     pId->pMethods = 0;
15347   }
15348   return rc;
15349 }
15350 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15351   DO_OS_MALLOC_TEST(id);
15352   return id->pMethods->xRead(id, pBuf, amt, offset);
15353 }
15354 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15355   DO_OS_MALLOC_TEST(id);
15356   return id->pMethods->xWrite(id, pBuf, amt, offset);
15357 }
15358 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15359   return id->pMethods->xTruncate(id, size);
15360 }
15361 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15362   DO_OS_MALLOC_TEST(id);
15363   return id->pMethods->xSync(id, flags);
15364 }
15365 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15366   DO_OS_MALLOC_TEST(id);
15367   return id->pMethods->xFileSize(id, pSize);
15368 }
15369 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15370   DO_OS_MALLOC_TEST(id);
15371   return id->pMethods->xLock(id, lockType);
15372 }
15373 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15374   return id->pMethods->xUnlock(id, lockType);
15375 }
15376 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15377   DO_OS_MALLOC_TEST(id);
15378   return id->pMethods->xCheckReservedLock(id, pResOut);
15379 }
15380 
15381 /*
15382 ** Use sqlite3OsFileControl() when we are doing something that might fail
15383 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15384 ** when simply tossing information over the wall to the VFS and we do not
15385 ** really care if the VFS receives and understands the information since it
15386 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15387 ** routine has no return value since the return value would be meaningless.
15388 */
15389 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15390   DO_OS_MALLOC_TEST(id);
15391   return id->pMethods->xFileControl(id, op, pArg);
15392 }
15393 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15394   (void)id->pMethods->xFileControl(id, op, pArg);
15395 }
15396 
15397 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15398   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15399   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15400 }
15401 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15402   return id->pMethods->xDeviceCharacteristics(id);
15403 }
15404 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15405   return id->pMethods->xShmLock(id, offset, n, flags);
15406 }
15407 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15408   id->pMethods->xShmBarrier(id);
15409 }
15410 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15411   return id->pMethods->xShmUnmap(id, deleteFlag);
15412 }
15413 SQLITE_PRIVATE int sqlite3OsShmMap(
15414   sqlite3_file *id,               /* Database file handle */
15415   int iPage,
15416   int pgsz,
15417   int bExtend,                    /* True to extend file if necessary */
15418   void volatile **pp              /* OUT: Pointer to mapping */
15419 ){
15420   DO_OS_MALLOC_TEST(id);
15421   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15422 }
15423 
15424 #if SQLITE_MAX_MMAP_SIZE>0
15425 /* The real implementation of xFetch and xUnfetch */
15426 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15427   DO_OS_MALLOC_TEST(id);
15428   return id->pMethods->xFetch(id, iOff, iAmt, pp);
15429 }
15430 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15431   return id->pMethods->xUnfetch(id, iOff, p);
15432 }
15433 #else
15434 /* No-op stubs to use when memory-mapped I/O is disabled */
15435 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15436   *pp = 0;
15437   return SQLITE_OK;
15438 }
15439 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15440   return SQLITE_OK;
15441 }
15442 #endif
15443 
15444 /*
15445 ** The next group of routines are convenience wrappers around the
15446 ** VFS methods.
15447 */
15448 SQLITE_PRIVATE int sqlite3OsOpen(
15449   sqlite3_vfs *pVfs, 
15450   const char *zPath, 
15451   sqlite3_file *pFile, 
15452   int flags, 
15453   int *pFlagsOut
15454 ){
15455   int rc;
15456   DO_OS_MALLOC_TEST(0);
15457   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15458   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15459   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15460   ** reaching the VFS. */
15461   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15462   assert( rc==SQLITE_OK || pFile->pMethods==0 );
15463   return rc;
15464 }
15465 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15466   DO_OS_MALLOC_TEST(0);
15467   assert( dirSync==0 || dirSync==1 );
15468   return pVfs->xDelete(pVfs, zPath, dirSync);
15469 }
15470 SQLITE_PRIVATE int sqlite3OsAccess(
15471   sqlite3_vfs *pVfs, 
15472   const char *zPath, 
15473   int flags, 
15474   int *pResOut
15475 ){
15476   DO_OS_MALLOC_TEST(0);
15477   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15478 }
15479 SQLITE_PRIVATE int sqlite3OsFullPathname(
15480   sqlite3_vfs *pVfs, 
15481   const char *zPath, 
15482   int nPathOut, 
15483   char *zPathOut
15484 ){
15485   DO_OS_MALLOC_TEST(0);
15486   zPathOut[0] = 0;
15487   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15488 }
15489 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15490 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15491   return pVfs->xDlOpen(pVfs, zPath);
15492 }
15493 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15494   pVfs->xDlError(pVfs, nByte, zBufOut);
15495 }
15496 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15497   return pVfs->xDlSym(pVfs, pHdle, zSym);
15498 }
15499 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15500   pVfs->xDlClose(pVfs, pHandle);
15501 }
15502 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15503 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15504   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15505 }
15506 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15507   return pVfs->xSleep(pVfs, nMicro);
15508 }
15509 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15510   int rc;
15511   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15512   ** method to get the current date and time if that method is available
15513   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15514   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15515   ** unavailable.
15516   */
15517   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15518     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15519   }else{
15520     double r;
15521     rc = pVfs->xCurrentTime(pVfs, &r);
15522     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15523   }
15524   return rc;
15525 }
15526 
15527 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15528   sqlite3_vfs *pVfs, 
15529   const char *zFile, 
15530   sqlite3_file **ppFile, 
15531   int flags,
15532   int *pOutFlags
15533 ){
15534   int rc = SQLITE_NOMEM;
15535   sqlite3_file *pFile;
15536   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15537   if( pFile ){
15538     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15539     if( rc!=SQLITE_OK ){
15540       sqlite3_free(pFile);
15541     }else{
15542       *ppFile = pFile;
15543     }
15544   }
15545   return rc;
15546 }
15547 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15548   int rc = SQLITE_OK;
15549   assert( pFile );
15550   rc = sqlite3OsClose(pFile);
15551   sqlite3_free(pFile);
15552   return rc;
15553 }
15554 
15555 /*
15556 ** This function is a wrapper around the OS specific implementation of
15557 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15558 ** ability to simulate a malloc failure, so that the handling of an
15559 ** error in sqlite3_os_init() by the upper layers can be tested.
15560 */
15561 SQLITE_PRIVATE int sqlite3OsInit(void){
15562   void *p = sqlite3_malloc(10);
15563   if( p==0 ) return SQLITE_NOMEM;
15564   sqlite3_free(p);
15565   return sqlite3_os_init();
15566 }
15567 
15568 /*
15569 ** The list of all registered VFS implementations.
15570 */
15571 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15572 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15573 
15574 /*
15575 ** Locate a VFS by name.  If no name is given, simply return the
15576 ** first VFS on the list.
15577 */
15578 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15579   sqlite3_vfs *pVfs = 0;
15580 #if SQLITE_THREADSAFE
15581   sqlite3_mutex *mutex;
15582 #endif
15583 #ifndef SQLITE_OMIT_AUTOINIT
15584   int rc = sqlite3_initialize();
15585   if( rc ) return 0;
15586 #endif
15587 #if SQLITE_THREADSAFE
15588   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15589 #endif
15590   sqlite3_mutex_enter(mutex);
15591   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15592     if( zVfs==0 ) break;
15593     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15594   }
15595   sqlite3_mutex_leave(mutex);
15596   return pVfs;
15597 }
15598 
15599 /*
15600 ** Unlink a VFS from the linked list
15601 */
15602 static void vfsUnlink(sqlite3_vfs *pVfs){
15603   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15604   if( pVfs==0 ){
15605     /* No-op */
15606   }else if( vfsList==pVfs ){
15607     vfsList = pVfs->pNext;
15608   }else if( vfsList ){
15609     sqlite3_vfs *p = vfsList;
15610     while( p->pNext && p->pNext!=pVfs ){
15611       p = p->pNext;
15612     }
15613     if( p->pNext==pVfs ){
15614       p->pNext = pVfs->pNext;
15615     }
15616   }
15617 }
15618 
15619 /*
15620 ** Register a VFS with the system.  It is harmless to register the same
15621 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15622 ** true.
15623 */
15624 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15625   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15626 #ifndef SQLITE_OMIT_AUTOINIT
15627   int rc = sqlite3_initialize();
15628   if( rc ) return rc;
15629 #endif
15630   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15631   sqlite3_mutex_enter(mutex);
15632   vfsUnlink(pVfs);
15633   if( makeDflt || vfsList==0 ){
15634     pVfs->pNext = vfsList;
15635     vfsList = pVfs;
15636   }else{
15637     pVfs->pNext = vfsList->pNext;
15638     vfsList->pNext = pVfs;
15639   }
15640   assert(vfsList);
15641   sqlite3_mutex_leave(mutex);
15642   return SQLITE_OK;
15643 }
15644 
15645 /*
15646 ** Unregister a VFS so that it is no longer accessible.
15647 */
15648 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15649 #if SQLITE_THREADSAFE
15650   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15651 #endif
15652   sqlite3_mutex_enter(mutex);
15653   vfsUnlink(pVfs);
15654   sqlite3_mutex_leave(mutex);
15655   return SQLITE_OK;
15656 }
15657 
15658 /************** End of os.c **************************************************/
15659 /************** Begin file fault.c *******************************************/
15660 /*
15661 ** 2008 Jan 22
15662 **
15663 ** The author disclaims copyright to this source code.  In place of
15664 ** a legal notice, here is a blessing:
15665 **
15666 **    May you do good and not evil.
15667 **    May you find forgiveness for yourself and forgive others.
15668 **    May you share freely, never taking more than you give.
15669 **
15670 *************************************************************************
15671 **
15672 ** This file contains code to support the concept of "benign" 
15673 ** malloc failures (when the xMalloc() or xRealloc() method of the
15674 ** sqlite3_mem_methods structure fails to allocate a block of memory
15675 ** and returns 0). 
15676 **
15677 ** Most malloc failures are non-benign. After they occur, SQLite
15678 ** abandons the current operation and returns an error code (usually
15679 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15680 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15681 ** is completely recoverable simply by not carrying out the resize. The 
15682 ** hash table will continue to function normally.  So a malloc failure 
15683 ** during a hash table resize is a benign fault.
15684 */
15685 
15686 
15687 #ifndef SQLITE_OMIT_BUILTIN_TEST
15688 
15689 /*
15690 ** Global variables.
15691 */
15692 typedef struct BenignMallocHooks BenignMallocHooks;
15693 static SQLITE_WSD struct BenignMallocHooks {
15694   void (*xBenignBegin)(void);
15695   void (*xBenignEnd)(void);
15696 } sqlite3Hooks = { 0, 0 };
15697 
15698 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15699 ** structure.  If writable static data is unsupported on the target,
15700 ** we have to locate the state vector at run-time.  In the more common
15701 ** case where writable static data is supported, wsdHooks can refer directly
15702 ** to the "sqlite3Hooks" state vector declared above.
15703 */
15704 #ifdef SQLITE_OMIT_WSD
15705 # define wsdHooksInit \
15706   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15707 # define wsdHooks x[0]
15708 #else
15709 # define wsdHooksInit
15710 # define wsdHooks sqlite3Hooks
15711 #endif
15712 
15713 
15714 /*
15715 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15716 ** sqlite3EndBenignMalloc() are called, respectively.
15717 */
15718 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15719   void (*xBenignBegin)(void),
15720   void (*xBenignEnd)(void)
15721 ){
15722   wsdHooksInit;
15723   wsdHooks.xBenignBegin = xBenignBegin;
15724   wsdHooks.xBenignEnd = xBenignEnd;
15725 }
15726 
15727 /*
15728 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15729 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15730 ** indicates that subsequent malloc failures are non-benign.
15731 */
15732 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15733   wsdHooksInit;
15734   if( wsdHooks.xBenignBegin ){
15735     wsdHooks.xBenignBegin();
15736   }
15737 }
15738 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15739   wsdHooksInit;
15740   if( wsdHooks.xBenignEnd ){
15741     wsdHooks.xBenignEnd();
15742   }
15743 }
15744 
15745 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15746 
15747 /************** End of fault.c ***********************************************/
15748 /************** Begin file mem0.c ********************************************/
15749 /*
15750 ** 2008 October 28
15751 **
15752 ** The author disclaims copyright to this source code.  In place of
15753 ** a legal notice, here is a blessing:
15754 **
15755 **    May you do good and not evil.
15756 **    May you find forgiveness for yourself and forgive others.
15757 **    May you share freely, never taking more than you give.
15758 **
15759 *************************************************************************
15760 **
15761 ** This file contains a no-op memory allocation drivers for use when
15762 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15763 ** here always fail.  SQLite will not operate with these drivers.  These
15764 ** are merely placeholders.  Real drivers must be substituted using
15765 ** sqlite3_config() before SQLite will operate.
15766 */
15767 
15768 /*
15769 ** This version of the memory allocator is the default.  It is
15770 ** used when no other memory allocator is specified using compile-time
15771 ** macros.
15772 */
15773 #ifdef SQLITE_ZERO_MALLOC
15774 
15775 /*
15776 ** No-op versions of all memory allocation routines
15777 */
15778 static void *sqlite3MemMalloc(int nByte){ return 0; }
15779 static void sqlite3MemFree(void *pPrior){ return; }
15780 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15781 static int sqlite3MemSize(void *pPrior){ return 0; }
15782 static int sqlite3MemRoundup(int n){ return n; }
15783 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15784 static void sqlite3MemShutdown(void *NotUsed){ return; }
15785 
15786 /*
15787 ** This routine is the only routine in this file with external linkage.
15788 **
15789 ** Populate the low-level memory allocation function pointers in
15790 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15791 */
15792 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15793   static const sqlite3_mem_methods defaultMethods = {
15794      sqlite3MemMalloc,
15795      sqlite3MemFree,
15796      sqlite3MemRealloc,
15797      sqlite3MemSize,
15798      sqlite3MemRoundup,
15799      sqlite3MemInit,
15800      sqlite3MemShutdown,
15801      0
15802   };
15803   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15804 }
15805 
15806 #endif /* SQLITE_ZERO_MALLOC */
15807 
15808 /************** End of mem0.c ************************************************/
15809 /************** Begin file mem1.c ********************************************/
15810 /*
15811 ** 2007 August 14
15812 **
15813 ** The author disclaims copyright to this source code.  In place of
15814 ** a legal notice, here is a blessing:
15815 **
15816 **    May you do good and not evil.
15817 **    May you find forgiveness for yourself and forgive others.
15818 **    May you share freely, never taking more than you give.
15819 **
15820 *************************************************************************
15821 **
15822 ** This file contains low-level memory allocation drivers for when
15823 ** SQLite will use the standard C-library malloc/realloc/free interface
15824 ** to obtain the memory it needs.
15825 **
15826 ** This file contains implementations of the low-level memory allocation
15827 ** routines specified in the sqlite3_mem_methods object.  The content of
15828 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15829 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15830 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15831 ** default configuration is to use memory allocation routines in this
15832 ** file.
15833 **
15834 ** C-preprocessor macro summary:
15835 **
15836 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15837 **                                the malloc_usable_size() interface exists
15838 **                                on the target platform.  Or, this symbol
15839 **                                can be set manually, if desired.
15840 **                                If an equivalent interface exists by
15841 **                                a different name, using a separate -D
15842 **                                option to rename it.
15843 **
15844 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15845 **                                memory allocator.  Set this symbol to enable
15846 **                                building on older macs.
15847 **
15848 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15849 **                                _msize() on windows systems.  This might
15850 **                                be necessary when compiling for Delphi,
15851 **                                for example.
15852 */
15853 
15854 /*
15855 ** This version of the memory allocator is the default.  It is
15856 ** used when no other memory allocator is specified using compile-time
15857 ** macros.
15858 */
15859 #ifdef SQLITE_SYSTEM_MALLOC
15860 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15861 
15862 /*
15863 ** Use the zone allocator available on apple products unless the
15864 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15865 */
15866 #include <sys/sysctl.h>
15867 #include <malloc/malloc.h>
15868 #include <libkern/OSAtomic.h>
15869 static malloc_zone_t* _sqliteZone_;
15870 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15871 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15872 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15873 #define SQLITE_MALLOCSIZE(x) \
15874         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15875 
15876 #else /* if not __APPLE__ */
15877 
15878 /*
15879 ** Use standard C library malloc and free on non-Apple systems.  
15880 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15881 */
15882 #define SQLITE_MALLOC(x)             malloc(x)
15883 #define SQLITE_FREE(x)               free(x)
15884 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
15885 
15886 /*
15887 ** The malloc.h header file is needed for malloc_usable_size() function
15888 ** on some systems (e.g. Linux).
15889 */
15890 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
15891 #  define SQLITE_USE_MALLOC_H
15892 #  define SQLITE_USE_MALLOC_USABLE_SIZE
15893 /*
15894 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
15895 ** use of _msize() is automatic, but can be disabled by compiling with
15896 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
15897 ** the malloc.h header file.
15898 */
15899 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15900 #  define SQLITE_USE_MALLOC_H
15901 #  define SQLITE_USE_MSIZE
15902 #endif
15903 
15904 /*
15905 ** Include the malloc.h header file, if necessary.  Also set define macro
15906 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
15907 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
15908 ** The memory size function can always be overridden manually by defining
15909 ** the macro SQLITE_MALLOCSIZE to the desired function name.
15910 */
15911 #if defined(SQLITE_USE_MALLOC_H)
15912 #  include <malloc.h>
15913 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
15914 #    if !defined(SQLITE_MALLOCSIZE)
15915 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
15916 #    endif
15917 #  elif defined(SQLITE_USE_MSIZE)
15918 #    if !defined(SQLITE_MALLOCSIZE)
15919 #      define SQLITE_MALLOCSIZE      _msize
15920 #    endif
15921 #  endif
15922 #endif /* defined(SQLITE_USE_MALLOC_H) */
15923 
15924 #endif /* __APPLE__ or not __APPLE__ */
15925 
15926 /*
15927 ** Like malloc(), but remember the size of the allocation
15928 ** so that we can find it later using sqlite3MemSize().
15929 **
15930 ** For this low-level routine, we are guaranteed that nByte>0 because
15931 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15932 ** routines.
15933 */
15934 static void *sqlite3MemMalloc(int nByte){
15935 #ifdef SQLITE_MALLOCSIZE
15936   void *p = SQLITE_MALLOC( nByte );
15937   if( p==0 ){
15938     testcase( sqlite3GlobalConfig.xLog!=0 );
15939     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15940   }
15941   return p;
15942 #else
15943   sqlite3_int64 *p;
15944   assert( nByte>0 );
15945   nByte = ROUND8(nByte);
15946   p = SQLITE_MALLOC( nByte+8 );
15947   if( p ){
15948     p[0] = nByte;
15949     p++;
15950   }else{
15951     testcase( sqlite3GlobalConfig.xLog!=0 );
15952     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15953   }
15954   return (void *)p;
15955 #endif
15956 }
15957 
15958 /*
15959 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15960 ** or sqlite3MemRealloc().
15961 **
15962 ** For this low-level routine, we already know that pPrior!=0 since
15963 ** cases where pPrior==0 will have been intecepted and dealt with
15964 ** by higher-level routines.
15965 */
15966 static void sqlite3MemFree(void *pPrior){
15967 #ifdef SQLITE_MALLOCSIZE
15968   SQLITE_FREE(pPrior);
15969 #else
15970   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15971   assert( pPrior!=0 );
15972   p--;
15973   SQLITE_FREE(p);
15974 #endif
15975 }
15976 
15977 /*
15978 ** Report the allocated size of a prior return from xMalloc()
15979 ** or xRealloc().
15980 */
15981 static int sqlite3MemSize(void *pPrior){
15982 #ifdef SQLITE_MALLOCSIZE
15983   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15984 #else
15985   sqlite3_int64 *p;
15986   if( pPrior==0 ) return 0;
15987   p = (sqlite3_int64*)pPrior;
15988   p--;
15989   return (int)p[0];
15990 #endif
15991 }
15992 
15993 /*
15994 ** Like realloc().  Resize an allocation previously obtained from
15995 ** sqlite3MemMalloc().
15996 **
15997 ** For this low-level interface, we know that pPrior!=0.  Cases where
15998 ** pPrior==0 while have been intercepted by higher-level routine and
15999 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
16000 ** cases where nByte<=0 will have been intercepted by higher-level
16001 ** routines and redirected to xFree.
16002 */
16003 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16004 #ifdef SQLITE_MALLOCSIZE
16005   void *p = SQLITE_REALLOC(pPrior, nByte);
16006   if( p==0 ){
16007     testcase( sqlite3GlobalConfig.xLog!=0 );
16008     sqlite3_log(SQLITE_NOMEM,
16009       "failed memory resize %u to %u bytes",
16010       SQLITE_MALLOCSIZE(pPrior), nByte);
16011   }
16012   return p;
16013 #else
16014   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16015   assert( pPrior!=0 && nByte>0 );
16016   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16017   p--;
16018   p = SQLITE_REALLOC(p, nByte+8 );
16019   if( p ){
16020     p[0] = nByte;
16021     p++;
16022   }else{
16023     testcase( sqlite3GlobalConfig.xLog!=0 );
16024     sqlite3_log(SQLITE_NOMEM,
16025       "failed memory resize %u to %u bytes",
16026       sqlite3MemSize(pPrior), nByte);
16027   }
16028   return (void*)p;
16029 #endif
16030 }
16031 
16032 /*
16033 ** Round up a request size to the next valid allocation size.
16034 */
16035 static int sqlite3MemRoundup(int n){
16036   return ROUND8(n);
16037 }
16038 
16039 /*
16040 ** Initialize this module.
16041 */
16042 static int sqlite3MemInit(void *NotUsed){
16043 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16044   int cpuCount;
16045   size_t len;
16046   if( _sqliteZone_ ){
16047     return SQLITE_OK;
16048   }
16049   len = sizeof(cpuCount);
16050   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16051   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16052   if( cpuCount>1 ){
16053     /* defer MT decisions to system malloc */
16054     _sqliteZone_ = malloc_default_zone();
16055   }else{
16056     /* only 1 core, use our own zone to contention over global locks, 
16057     ** e.g. we have our own dedicated locks */
16058     bool success;
16059     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16060     malloc_set_zone_name(newzone, "Sqlite_Heap");
16061     do{
16062       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
16063                                  (void * volatile *)&_sqliteZone_);
16064     }while(!_sqliteZone_);
16065     if( !success ){
16066       /* somebody registered a zone first */
16067       malloc_destroy_zone(newzone);
16068     }
16069   }
16070 #endif
16071   UNUSED_PARAMETER(NotUsed);
16072   return SQLITE_OK;
16073 }
16074 
16075 /*
16076 ** Deinitialize this module.
16077 */
16078 static void sqlite3MemShutdown(void *NotUsed){
16079   UNUSED_PARAMETER(NotUsed);
16080   return;
16081 }
16082 
16083 /*
16084 ** This routine is the only routine in this file with external linkage.
16085 **
16086 ** Populate the low-level memory allocation function pointers in
16087 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16088 */
16089 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16090   static const sqlite3_mem_methods defaultMethods = {
16091      sqlite3MemMalloc,
16092      sqlite3MemFree,
16093      sqlite3MemRealloc,
16094      sqlite3MemSize,
16095      sqlite3MemRoundup,
16096      sqlite3MemInit,
16097      sqlite3MemShutdown,
16098      0
16099   };
16100   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16101 }
16102 
16103 #endif /* SQLITE_SYSTEM_MALLOC */
16104 
16105 /************** End of mem1.c ************************************************/
16106 /************** Begin file mem2.c ********************************************/
16107 /*
16108 ** 2007 August 15
16109 **
16110 ** The author disclaims copyright to this source code.  In place of
16111 ** a legal notice, here is a blessing:
16112 **
16113 **    May you do good and not evil.
16114 **    May you find forgiveness for yourself and forgive others.
16115 **    May you share freely, never taking more than you give.
16116 **
16117 *************************************************************************
16118 **
16119 ** This file contains low-level memory allocation drivers for when
16120 ** SQLite will use the standard C-library malloc/realloc/free interface
16121 ** to obtain the memory it needs while adding lots of additional debugging
16122 ** information to each allocation in order to help detect and fix memory
16123 ** leaks and memory usage errors.
16124 **
16125 ** This file contains implementations of the low-level memory allocation
16126 ** routines specified in the sqlite3_mem_methods object.
16127 */
16128 
16129 /*
16130 ** This version of the memory allocator is used only if the
16131 ** SQLITE_MEMDEBUG macro is defined
16132 */
16133 #ifdef SQLITE_MEMDEBUG
16134 
16135 /*
16136 ** The backtrace functionality is only available with GLIBC
16137 */
16138 #ifdef __GLIBC__
16139   extern int backtrace(void**,int);
16140   extern void backtrace_symbols_fd(void*const*,int,int);
16141 #else
16142 # define backtrace(A,B) 1
16143 # define backtrace_symbols_fd(A,B,C)
16144 #endif
16145 /* #include <stdio.h> */
16146 
16147 /*
16148 ** Each memory allocation looks like this:
16149 **
16150 **  ------------------------------------------------------------------------
16151 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
16152 **  ------------------------------------------------------------------------
16153 **
16154 ** The application code sees only a pointer to the allocation.  We have
16155 ** to back up from the allocation pointer to find the MemBlockHdr.  The
16156 ** MemBlockHdr tells us the size of the allocation and the number of
16157 ** backtrace pointers.  There is also a guard word at the end of the
16158 ** MemBlockHdr.
16159 */
16160 struct MemBlockHdr {
16161   i64 iSize;                          /* Size of this allocation */
16162   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
16163   char nBacktrace;                    /* Number of backtraces on this alloc */
16164   char nBacktraceSlots;               /* Available backtrace slots */
16165   u8 nTitle;                          /* Bytes of title; includes '\0' */
16166   u8 eType;                           /* Allocation type code */
16167   int iForeGuard;                     /* Guard word for sanity */
16168 };
16169 
16170 /*
16171 ** Guard words
16172 */
16173 #define FOREGUARD 0x80F5E153
16174 #define REARGUARD 0xE4676B53
16175 
16176 /*
16177 ** Number of malloc size increments to track.
16178 */
16179 #define NCSIZE  1000
16180 
16181 /*
16182 ** All of the static variables used by this module are collected
16183 ** into a single structure named "mem".  This is to keep the
16184 ** static variables organized and to reduce namespace pollution
16185 ** when this module is combined with other in the amalgamation.
16186 */
16187 static struct {
16188   
16189   /*
16190   ** Mutex to control access to the memory allocation subsystem.
16191   */
16192   sqlite3_mutex *mutex;
16193 
16194   /*
16195   ** Head and tail of a linked list of all outstanding allocations
16196   */
16197   struct MemBlockHdr *pFirst;
16198   struct MemBlockHdr *pLast;
16199   
16200   /*
16201   ** The number of levels of backtrace to save in new allocations.
16202   */
16203   int nBacktrace;
16204   void (*xBacktrace)(int, int, void **);
16205 
16206   /*
16207   ** Title text to insert in front of each block
16208   */
16209   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
16210   char zTitle[100];  /* The title text */
16211 
16212   /* 
16213   ** sqlite3MallocDisallow() increments the following counter.
16214   ** sqlite3MallocAllow() decrements it.
16215   */
16216   int disallow; /* Do not allow memory allocation */
16217 
16218   /*
16219   ** Gather statistics on the sizes of memory allocations.
16220   ** nAlloc[i] is the number of allocation attempts of i*8
16221   ** bytes.  i==NCSIZE is the number of allocation attempts for
16222   ** sizes more than NCSIZE*8 bytes.
16223   */
16224   int nAlloc[NCSIZE];      /* Total number of allocations */
16225   int nCurrent[NCSIZE];    /* Current number of allocations */
16226   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
16227 
16228 } mem;
16229 
16230 
16231 /*
16232 ** Adjust memory usage statistics
16233 */
16234 static void adjustStats(int iSize, int increment){
16235   int i = ROUND8(iSize)/8;
16236   if( i>NCSIZE-1 ){
16237     i = NCSIZE - 1;
16238   }
16239   if( increment>0 ){
16240     mem.nAlloc[i]++;
16241     mem.nCurrent[i]++;
16242     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16243       mem.mxCurrent[i] = mem.nCurrent[i];
16244     }
16245   }else{
16246     mem.nCurrent[i]--;
16247     assert( mem.nCurrent[i]>=0 );
16248   }
16249 }
16250 
16251 /*
16252 ** Given an allocation, find the MemBlockHdr for that allocation.
16253 **
16254 ** This routine checks the guards at either end of the allocation and
16255 ** if they are incorrect it asserts.
16256 */
16257 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16258   struct MemBlockHdr *p;
16259   int *pInt;
16260   u8 *pU8;
16261   int nReserve;
16262 
16263   p = (struct MemBlockHdr*)pAllocation;
16264   p--;
16265   assert( p->iForeGuard==(int)FOREGUARD );
16266   nReserve = ROUND8(p->iSize);
16267   pInt = (int*)pAllocation;
16268   pU8 = (u8*)pAllocation;
16269   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16270   /* This checks any of the "extra" bytes allocated due
16271   ** to rounding up to an 8 byte boundary to ensure 
16272   ** they haven't been overwritten.
16273   */
16274   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16275   return p;
16276 }
16277 
16278 /*
16279 ** Return the number of bytes currently allocated at address p.
16280 */
16281 static int sqlite3MemSize(void *p){
16282   struct MemBlockHdr *pHdr;
16283   if( !p ){
16284     return 0;
16285   }
16286   pHdr = sqlite3MemsysGetHeader(p);
16287   return (int)pHdr->iSize;
16288 }
16289 
16290 /*
16291 ** Initialize the memory allocation subsystem.
16292 */
16293 static int sqlite3MemInit(void *NotUsed){
16294   UNUSED_PARAMETER(NotUsed);
16295   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16296   if( !sqlite3GlobalConfig.bMemstat ){
16297     /* If memory status is enabled, then the malloc.c wrapper will already
16298     ** hold the STATIC_MEM mutex when the routines here are invoked. */
16299     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16300   }
16301   return SQLITE_OK;
16302 }
16303 
16304 /*
16305 ** Deinitialize the memory allocation subsystem.
16306 */
16307 static void sqlite3MemShutdown(void *NotUsed){
16308   UNUSED_PARAMETER(NotUsed);
16309   mem.mutex = 0;
16310 }
16311 
16312 /*
16313 ** Round up a request size to the next valid allocation size.
16314 */
16315 static int sqlite3MemRoundup(int n){
16316   return ROUND8(n);
16317 }
16318 
16319 /*
16320 ** Fill a buffer with pseudo-random bytes.  This is used to preset
16321 ** the content of a new memory allocation to unpredictable values and
16322 ** to clear the content of a freed allocation to unpredictable values.
16323 */
16324 static void randomFill(char *pBuf, int nByte){
16325   unsigned int x, y, r;
16326   x = SQLITE_PTR_TO_INT(pBuf);
16327   y = nByte | 1;
16328   while( nByte >= 4 ){
16329     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16330     y = y*1103515245 + 12345;
16331     r = x ^ y;
16332     *(int*)pBuf = r;
16333     pBuf += 4;
16334     nByte -= 4;
16335   }
16336   while( nByte-- > 0 ){
16337     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16338     y = y*1103515245 + 12345;
16339     r = x ^ y;
16340     *(pBuf++) = r & 0xff;
16341   }
16342 }
16343 
16344 /*
16345 ** Allocate nByte bytes of memory.
16346 */
16347 static void *sqlite3MemMalloc(int nByte){
16348   struct MemBlockHdr *pHdr;
16349   void **pBt;
16350   char *z;
16351   int *pInt;
16352   void *p = 0;
16353   int totalSize;
16354   int nReserve;
16355   sqlite3_mutex_enter(mem.mutex);
16356   assert( mem.disallow==0 );
16357   nReserve = ROUND8(nByte);
16358   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16359                mem.nBacktrace*sizeof(void*) + mem.nTitle;
16360   p = malloc(totalSize);
16361   if( p ){
16362     z = p;
16363     pBt = (void**)&z[mem.nTitle];
16364     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16365     pHdr->pNext = 0;
16366     pHdr->pPrev = mem.pLast;
16367     if( mem.pLast ){
16368       mem.pLast->pNext = pHdr;
16369     }else{
16370       mem.pFirst = pHdr;
16371     }
16372     mem.pLast = pHdr;
16373     pHdr->iForeGuard = FOREGUARD;
16374     pHdr->eType = MEMTYPE_HEAP;
16375     pHdr->nBacktraceSlots = mem.nBacktrace;
16376     pHdr->nTitle = mem.nTitle;
16377     if( mem.nBacktrace ){
16378       void *aAddr[40];
16379       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16380       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16381       assert(pBt[0]);
16382       if( mem.xBacktrace ){
16383         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16384       }
16385     }else{
16386       pHdr->nBacktrace = 0;
16387     }
16388     if( mem.nTitle ){
16389       memcpy(z, mem.zTitle, mem.nTitle);
16390     }
16391     pHdr->iSize = nByte;
16392     adjustStats(nByte, +1);
16393     pInt = (int*)&pHdr[1];
16394     pInt[nReserve/sizeof(int)] = REARGUARD;
16395     randomFill((char*)pInt, nByte);
16396     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16397     p = (void*)pInt;
16398   }
16399   sqlite3_mutex_leave(mem.mutex);
16400   return p; 
16401 }
16402 
16403 /*
16404 ** Free memory.
16405 */
16406 static void sqlite3MemFree(void *pPrior){
16407   struct MemBlockHdr *pHdr;
16408   void **pBt;
16409   char *z;
16410   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
16411        || mem.mutex!=0 );
16412   pHdr = sqlite3MemsysGetHeader(pPrior);
16413   pBt = (void**)pHdr;
16414   pBt -= pHdr->nBacktraceSlots;
16415   sqlite3_mutex_enter(mem.mutex);
16416   if( pHdr->pPrev ){
16417     assert( pHdr->pPrev->pNext==pHdr );
16418     pHdr->pPrev->pNext = pHdr->pNext;
16419   }else{
16420     assert( mem.pFirst==pHdr );
16421     mem.pFirst = pHdr->pNext;
16422   }
16423   if( pHdr->pNext ){
16424     assert( pHdr->pNext->pPrev==pHdr );
16425     pHdr->pNext->pPrev = pHdr->pPrev;
16426   }else{
16427     assert( mem.pLast==pHdr );
16428     mem.pLast = pHdr->pPrev;
16429   }
16430   z = (char*)pBt;
16431   z -= pHdr->nTitle;
16432   adjustStats((int)pHdr->iSize, -1);
16433   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16434                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
16435   free(z);
16436   sqlite3_mutex_leave(mem.mutex);  
16437 }
16438 
16439 /*
16440 ** Change the size of an existing memory allocation.
16441 **
16442 ** For this debugging implementation, we *always* make a copy of the
16443 ** allocation into a new place in memory.  In this way, if the 
16444 ** higher level code is using pointer to the old allocation, it is 
16445 ** much more likely to break and we are much more liking to find
16446 ** the error.
16447 */
16448 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16449   struct MemBlockHdr *pOldHdr;
16450   void *pNew;
16451   assert( mem.disallow==0 );
16452   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16453   pOldHdr = sqlite3MemsysGetHeader(pPrior);
16454   pNew = sqlite3MemMalloc(nByte);
16455   if( pNew ){
16456     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
16457     if( nByte>pOldHdr->iSize ){
16458       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
16459     }
16460     sqlite3MemFree(pPrior);
16461   }
16462   return pNew;
16463 }
16464 
16465 /*
16466 ** Populate the low-level memory allocation function pointers in
16467 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16468 */
16469 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16470   static const sqlite3_mem_methods defaultMethods = {
16471      sqlite3MemMalloc,
16472      sqlite3MemFree,
16473      sqlite3MemRealloc,
16474      sqlite3MemSize,
16475      sqlite3MemRoundup,
16476      sqlite3MemInit,
16477      sqlite3MemShutdown,
16478      0
16479   };
16480   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16481 }
16482 
16483 /*
16484 ** Set the "type" of an allocation.
16485 */
16486 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16487   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16488     struct MemBlockHdr *pHdr;
16489     pHdr = sqlite3MemsysGetHeader(p);
16490     assert( pHdr->iForeGuard==FOREGUARD );
16491     pHdr->eType = eType;
16492   }
16493 }
16494 
16495 /*
16496 ** Return TRUE if the mask of type in eType matches the type of the
16497 ** allocation p.  Also return true if p==NULL.
16498 **
16499 ** This routine is designed for use within an assert() statement, to
16500 ** verify the type of an allocation.  For example:
16501 **
16502 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16503 */
16504 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16505   int rc = 1;
16506   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16507     struct MemBlockHdr *pHdr;
16508     pHdr = sqlite3MemsysGetHeader(p);
16509     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16510     if( (pHdr->eType&eType)==0 ){
16511       rc = 0;
16512     }
16513   }
16514   return rc;
16515 }
16516 
16517 /*
16518 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16519 ** allocation p.  Also return true if p==NULL.
16520 **
16521 ** This routine is designed for use within an assert() statement, to
16522 ** verify the type of an allocation.  For example:
16523 **
16524 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16525 */
16526 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16527   int rc = 1;
16528   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16529     struct MemBlockHdr *pHdr;
16530     pHdr = sqlite3MemsysGetHeader(p);
16531     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16532     if( (pHdr->eType&eType)!=0 ){
16533       rc = 0;
16534     }
16535   }
16536   return rc;
16537 }
16538 
16539 /*
16540 ** Set the number of backtrace levels kept for each allocation.
16541 ** A value of zero turns off backtracing.  The number is always rounded
16542 ** up to a multiple of 2.
16543 */
16544 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16545   if( depth<0 ){ depth = 0; }
16546   if( depth>20 ){ depth = 20; }
16547   depth = (depth+1)&0xfe;
16548   mem.nBacktrace = depth;
16549 }
16550 
16551 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16552   mem.xBacktrace = xBacktrace;
16553 }
16554 
16555 /*
16556 ** Set the title string for subsequent allocations.
16557 */
16558 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16559   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16560   sqlite3_mutex_enter(mem.mutex);
16561   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16562   memcpy(mem.zTitle, zTitle, n);
16563   mem.zTitle[n] = 0;
16564   mem.nTitle = ROUND8(n);
16565   sqlite3_mutex_leave(mem.mutex);
16566 }
16567 
16568 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16569   struct MemBlockHdr *pHdr;
16570   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16571     void **pBt = (void**)pHdr;
16572     pBt -= pHdr->nBacktraceSlots;
16573     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16574   }
16575 }
16576 
16577 /*
16578 ** Open the file indicated and write a log of all unfreed memory 
16579 ** allocations into that log.
16580 */
16581 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16582   FILE *out;
16583   struct MemBlockHdr *pHdr;
16584   void **pBt;
16585   int i;
16586   out = fopen(zFilename, "w");
16587   if( out==0 ){
16588     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16589                     zFilename);
16590     return;
16591   }
16592   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16593     char *z = (char*)pHdr;
16594     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16595     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16596             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16597     if( pHdr->nBacktrace ){
16598       fflush(out);
16599       pBt = (void**)pHdr;
16600       pBt -= pHdr->nBacktraceSlots;
16601       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16602       fprintf(out, "\n");
16603     }
16604   }
16605   fprintf(out, "COUNTS:\n");
16606   for(i=0; i<NCSIZE-1; i++){
16607     if( mem.nAlloc[i] ){
16608       fprintf(out, "   %5d: %10d %10d %10d\n", 
16609             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16610     }
16611   }
16612   if( mem.nAlloc[NCSIZE-1] ){
16613     fprintf(out, "   %5d: %10d %10d %10d\n",
16614              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16615              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16616   }
16617   fclose(out);
16618 }
16619 
16620 /*
16621 ** Return the number of times sqlite3MemMalloc() has been called.
16622 */
16623 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16624   int i;
16625   int nTotal = 0;
16626   for(i=0; i<NCSIZE; i++){
16627     nTotal += mem.nAlloc[i];
16628   }
16629   return nTotal;
16630 }
16631 
16632 
16633 #endif /* SQLITE_MEMDEBUG */
16634 
16635 /************** End of mem2.c ************************************************/
16636 /************** Begin file mem3.c ********************************************/
16637 /*
16638 ** 2007 October 14
16639 **
16640 ** The author disclaims copyright to this source code.  In place of
16641 ** a legal notice, here is a blessing:
16642 **
16643 **    May you do good and not evil.
16644 **    May you find forgiveness for yourself and forgive others.
16645 **    May you share freely, never taking more than you give.
16646 **
16647 *************************************************************************
16648 ** This file contains the C functions that implement a memory
16649 ** allocation subsystem for use by SQLite. 
16650 **
16651 ** This version of the memory allocation subsystem omits all
16652 ** use of malloc(). The SQLite user supplies a block of memory
16653 ** before calling sqlite3_initialize() from which allocations
16654 ** are made and returned by the xMalloc() and xRealloc() 
16655 ** implementations. Once sqlite3_initialize() has been called,
16656 ** the amount of memory available to SQLite is fixed and cannot
16657 ** be changed.
16658 **
16659 ** This version of the memory allocation subsystem is included
16660 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16661 */
16662 
16663 /*
16664 ** This version of the memory allocator is only built into the library
16665 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16666 ** mean that the library will use a memory-pool by default, just that
16667 ** it is available. The mempool allocator is activated by calling
16668 ** sqlite3_config().
16669 */
16670 #ifdef SQLITE_ENABLE_MEMSYS3
16671 
16672 /*
16673 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16674 */
16675 #define MX_SMALL 10
16676 
16677 
16678 /*
16679 ** Number of freelist hash slots
16680 */
16681 #define N_HASH  61
16682 
16683 /*
16684 ** A memory allocation (also called a "chunk") consists of two or 
16685 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16686 ** a header that is not returned to the user.
16687 **
16688 ** A chunk is two or more blocks that is either checked out or
16689 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16690 ** size of the allocation in blocks if the allocation is free.
16691 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16692 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16693 ** is true if the previous chunk is checked out and false if the
16694 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16695 ** the previous chunk in blocks if the previous chunk is on the
16696 ** freelist. If the previous chunk is checked out, then
16697 ** u.hdr.prevSize can be part of the data for that chunk and should
16698 ** not be read or written.
16699 **
16700 ** We often identify a chunk by its index in mem3.aPool[].  When
16701 ** this is done, the chunk index refers to the second block of
16702 ** the chunk.  In this way, the first chunk has an index of 1.
16703 ** A chunk index of 0 means "no such chunk" and is the equivalent
16704 ** of a NULL pointer.
16705 **
16706 ** The second block of free chunks is of the form u.list.  The
16707 ** two fields form a double-linked list of chunks of related sizes.
16708 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16709 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16710 **
16711 ** The second block of a chunk is user data if the chunk is checked 
16712 ** out.  If a chunk is checked out, the user data may extend into
16713 ** the u.hdr.prevSize value of the following chunk.
16714 */
16715 typedef struct Mem3Block Mem3Block;
16716 struct Mem3Block {
16717   union {
16718     struct {
16719       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16720       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16721     } hdr;
16722     struct {
16723       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16724       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16725     } list;
16726   } u;
16727 };
16728 
16729 /*
16730 ** All of the static variables used by this module are collected
16731 ** into a single structure named "mem3".  This is to keep the
16732 ** static variables organized and to reduce namespace pollution
16733 ** when this module is combined with other in the amalgamation.
16734 */
16735 static SQLITE_WSD struct Mem3Global {
16736   /*
16737   ** Memory available for allocation. nPool is the size of the array
16738   ** (in Mem3Blocks) pointed to by aPool less 2.
16739   */
16740   u32 nPool;
16741   Mem3Block *aPool;
16742 
16743   /*
16744   ** True if we are evaluating an out-of-memory callback.
16745   */
16746   int alarmBusy;
16747   
16748   /*
16749   ** Mutex to control access to the memory allocation subsystem.
16750   */
16751   sqlite3_mutex *mutex;
16752   
16753   /*
16754   ** The minimum amount of free space that we have seen.
16755   */
16756   u32 mnMaster;
16757 
16758   /*
16759   ** iMaster is the index of the master chunk.  Most new allocations
16760   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16761   ** of the current master.  iMaster is 0 if there is not master chunk.
16762   ** The master chunk is not in either the aiHash[] or aiSmall[].
16763   */
16764   u32 iMaster;
16765   u32 szMaster;
16766 
16767   /*
16768   ** Array of lists of free blocks according to the block size 
16769   ** for smaller chunks, or a hash on the block size for larger
16770   ** chunks.
16771   */
16772   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16773   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16774 } mem3 = { 97535575 };
16775 
16776 #define mem3 GLOBAL(struct Mem3Global, mem3)
16777 
16778 /*
16779 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16780 ** on.  *pRoot is the list that i is a member of.
16781 */
16782 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16783   u32 next = mem3.aPool[i].u.list.next;
16784   u32 prev = mem3.aPool[i].u.list.prev;
16785   assert( sqlite3_mutex_held(mem3.mutex) );
16786   if( prev==0 ){
16787     *pRoot = next;
16788   }else{
16789     mem3.aPool[prev].u.list.next = next;
16790   }
16791   if( next ){
16792     mem3.aPool[next].u.list.prev = prev;
16793   }
16794   mem3.aPool[i].u.list.next = 0;
16795   mem3.aPool[i].u.list.prev = 0;
16796 }
16797 
16798 /*
16799 ** Unlink the chunk at index i from 
16800 ** whatever list is currently a member of.
16801 */
16802 static void memsys3Unlink(u32 i){
16803   u32 size, hash;
16804   assert( sqlite3_mutex_held(mem3.mutex) );
16805   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16806   assert( i>=1 );
16807   size = mem3.aPool[i-1].u.hdr.size4x/4;
16808   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16809   assert( size>=2 );
16810   if( size <= MX_SMALL ){
16811     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16812   }else{
16813     hash = size % N_HASH;
16814     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16815   }
16816 }
16817 
16818 /*
16819 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16820 ** at *pRoot.
16821 */
16822 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16823   assert( sqlite3_mutex_held(mem3.mutex) );
16824   mem3.aPool[i].u.list.next = *pRoot;
16825   mem3.aPool[i].u.list.prev = 0;
16826   if( *pRoot ){
16827     mem3.aPool[*pRoot].u.list.prev = i;
16828   }
16829   *pRoot = i;
16830 }
16831 
16832 /*
16833 ** Link the chunk at index i into either the appropriate
16834 ** small chunk list, or into the large chunk hash table.
16835 */
16836 static void memsys3Link(u32 i){
16837   u32 size, hash;
16838   assert( sqlite3_mutex_held(mem3.mutex) );
16839   assert( i>=1 );
16840   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16841   size = mem3.aPool[i-1].u.hdr.size4x/4;
16842   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16843   assert( size>=2 );
16844   if( size <= MX_SMALL ){
16845     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16846   }else{
16847     hash = size % N_HASH;
16848     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16849   }
16850 }
16851 
16852 /*
16853 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16854 ** will already be held (obtained by code in malloc.c) if
16855 ** sqlite3GlobalConfig.bMemStat is true.
16856 */
16857 static void memsys3Enter(void){
16858   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16859     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16860   }
16861   sqlite3_mutex_enter(mem3.mutex);
16862 }
16863 static void memsys3Leave(void){
16864   sqlite3_mutex_leave(mem3.mutex);
16865 }
16866 
16867 /*
16868 ** Called when we are unable to satisfy an allocation of nBytes.
16869 */
16870 static void memsys3OutOfMemory(int nByte){
16871   if( !mem3.alarmBusy ){
16872     mem3.alarmBusy = 1;
16873     assert( sqlite3_mutex_held(mem3.mutex) );
16874     sqlite3_mutex_leave(mem3.mutex);
16875     sqlite3_release_memory(nByte);
16876     sqlite3_mutex_enter(mem3.mutex);
16877     mem3.alarmBusy = 0;
16878   }
16879 }
16880 
16881 
16882 /*
16883 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16884 ** size parameters for check-out and return a pointer to the 
16885 ** user portion of the chunk.
16886 */
16887 static void *memsys3Checkout(u32 i, u32 nBlock){
16888   u32 x;
16889   assert( sqlite3_mutex_held(mem3.mutex) );
16890   assert( i>=1 );
16891   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16892   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16893   x = mem3.aPool[i-1].u.hdr.size4x;
16894   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16895   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16896   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16897   return &mem3.aPool[i];
16898 }
16899 
16900 /*
16901 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16902 ** Return a pointer to the new allocation.  Or, if the master chunk
16903 ** is not large enough, return 0.
16904 */
16905 static void *memsys3FromMaster(u32 nBlock){
16906   assert( sqlite3_mutex_held(mem3.mutex) );
16907   assert( mem3.szMaster>=nBlock );
16908   if( nBlock>=mem3.szMaster-1 ){
16909     /* Use the entire master */
16910     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16911     mem3.iMaster = 0;
16912     mem3.szMaster = 0;
16913     mem3.mnMaster = 0;
16914     return p;
16915   }else{
16916     /* Split the master block.  Return the tail. */
16917     u32 newi, x;
16918     newi = mem3.iMaster + mem3.szMaster - nBlock;
16919     assert( newi > mem3.iMaster+1 );
16920     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16921     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16922     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16923     mem3.szMaster -= nBlock;
16924     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16925     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16926     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16927     if( mem3.szMaster < mem3.mnMaster ){
16928       mem3.mnMaster = mem3.szMaster;
16929     }
16930     return (void*)&mem3.aPool[newi];
16931   }
16932 }
16933 
16934 /*
16935 ** *pRoot is the head of a list of free chunks of the same size
16936 ** or same size hash.  In other words, *pRoot is an entry in either
16937 ** mem3.aiSmall[] or mem3.aiHash[].  
16938 **
16939 ** This routine examines all entries on the given list and tries
16940 ** to coalesce each entries with adjacent free chunks.  
16941 **
16942 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16943 ** the current mem3.iMaster with the new larger chunk.  In order for
16944 ** this mem3.iMaster replacement to work, the master chunk must be
16945 ** linked into the hash tables.  That is not the normal state of
16946 ** affairs, of course.  The calling routine must link the master
16947 ** chunk before invoking this routine, then must unlink the (possibly
16948 ** changed) master chunk once this routine has finished.
16949 */
16950 static void memsys3Merge(u32 *pRoot){
16951   u32 iNext, prev, size, i, x;
16952 
16953   assert( sqlite3_mutex_held(mem3.mutex) );
16954   for(i=*pRoot; i>0; i=iNext){
16955     iNext = mem3.aPool[i].u.list.next;
16956     size = mem3.aPool[i-1].u.hdr.size4x;
16957     assert( (size&1)==0 );
16958     if( (size&2)==0 ){
16959       memsys3UnlinkFromList(i, pRoot);
16960       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16961       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16962       if( prev==iNext ){
16963         iNext = mem3.aPool[prev].u.list.next;
16964       }
16965       memsys3Unlink(prev);
16966       size = i + size/4 - prev;
16967       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16968       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16969       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16970       memsys3Link(prev);
16971       i = prev;
16972     }else{
16973       size /= 4;
16974     }
16975     if( size>mem3.szMaster ){
16976       mem3.iMaster = i;
16977       mem3.szMaster = size;
16978     }
16979   }
16980 }
16981 
16982 /*
16983 ** Return a block of memory of at least nBytes in size.
16984 ** Return NULL if unable.
16985 **
16986 ** This function assumes that the necessary mutexes, if any, are
16987 ** already held by the caller. Hence "Unsafe".
16988 */
16989 static void *memsys3MallocUnsafe(int nByte){
16990   u32 i;
16991   u32 nBlock;
16992   u32 toFree;
16993 
16994   assert( sqlite3_mutex_held(mem3.mutex) );
16995   assert( sizeof(Mem3Block)==8 );
16996   if( nByte<=12 ){
16997     nBlock = 2;
16998   }else{
16999     nBlock = (nByte + 11)/8;
17000   }
17001   assert( nBlock>=2 );
17002 
17003   /* STEP 1:
17004   ** Look for an entry of the correct size in either the small
17005   ** chunk table or in the large chunk hash table.  This is
17006   ** successful most of the time (about 9 times out of 10).
17007   */
17008   if( nBlock <= MX_SMALL ){
17009     i = mem3.aiSmall[nBlock-2];
17010     if( i>0 ){
17011       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17012       return memsys3Checkout(i, nBlock);
17013     }
17014   }else{
17015     int hash = nBlock % N_HASH;
17016     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17017       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17018         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17019         return memsys3Checkout(i, nBlock);
17020       }
17021     }
17022   }
17023 
17024   /* STEP 2:
17025   ** Try to satisfy the allocation by carving a piece off of the end
17026   ** of the master chunk.  This step usually works if step 1 fails.
17027   */
17028   if( mem3.szMaster>=nBlock ){
17029     return memsys3FromMaster(nBlock);
17030   }
17031 
17032 
17033   /* STEP 3:  
17034   ** Loop through the entire memory pool.  Coalesce adjacent free
17035   ** chunks.  Recompute the master chunk as the largest free chunk.
17036   ** Then try again to satisfy the allocation by carving a piece off
17037   ** of the end of the master chunk.  This step happens very
17038   ** rarely (we hope!)
17039   */
17040   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17041     memsys3OutOfMemory(toFree);
17042     if( mem3.iMaster ){
17043       memsys3Link(mem3.iMaster);
17044       mem3.iMaster = 0;
17045       mem3.szMaster = 0;
17046     }
17047     for(i=0; i<N_HASH; i++){
17048       memsys3Merge(&mem3.aiHash[i]);
17049     }
17050     for(i=0; i<MX_SMALL-1; i++){
17051       memsys3Merge(&mem3.aiSmall[i]);
17052     }
17053     if( mem3.szMaster ){
17054       memsys3Unlink(mem3.iMaster);
17055       if( mem3.szMaster>=nBlock ){
17056         return memsys3FromMaster(nBlock);
17057       }
17058     }
17059   }
17060 
17061   /* If none of the above worked, then we fail. */
17062   return 0;
17063 }
17064 
17065 /*
17066 ** Free an outstanding memory allocation.
17067 **
17068 ** This function assumes that the necessary mutexes, if any, are
17069 ** already held by the caller. Hence "Unsafe".
17070 */
17071 static void memsys3FreeUnsafe(void *pOld){
17072   Mem3Block *p = (Mem3Block*)pOld;
17073   int i;
17074   u32 size, x;
17075   assert( sqlite3_mutex_held(mem3.mutex) );
17076   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17077   i = p - mem3.aPool;
17078   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17079   size = mem3.aPool[i-1].u.hdr.size4x/4;
17080   assert( i+size<=mem3.nPool+1 );
17081   mem3.aPool[i-1].u.hdr.size4x &= ~1;
17082   mem3.aPool[i+size-1].u.hdr.prevSize = size;
17083   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17084   memsys3Link(i);
17085 
17086   /* Try to expand the master using the newly freed chunk */
17087   if( mem3.iMaster ){
17088     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17089       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17090       mem3.iMaster -= size;
17091       mem3.szMaster += size;
17092       memsys3Unlink(mem3.iMaster);
17093       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17094       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17095       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17096     }
17097     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17098     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17099       memsys3Unlink(mem3.iMaster+mem3.szMaster);
17100       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17101       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17102       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17103     }
17104   }
17105 }
17106 
17107 /*
17108 ** Return the size of an outstanding allocation, in bytes.  The
17109 ** size returned omits the 8-byte header overhead.  This only
17110 ** works for chunks that are currently checked out.
17111 */
17112 static int memsys3Size(void *p){
17113   Mem3Block *pBlock;
17114   if( p==0 ) return 0;
17115   pBlock = (Mem3Block*)p;
17116   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17117   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17118 }
17119 
17120 /*
17121 ** Round up a request size to the next valid allocation size.
17122 */
17123 static int memsys3Roundup(int n){
17124   if( n<=12 ){
17125     return 12;
17126   }else{
17127     return ((n+11)&~7) - 4;
17128   }
17129 }
17130 
17131 /*
17132 ** Allocate nBytes of memory.
17133 */
17134 static void *memsys3Malloc(int nBytes){
17135   sqlite3_int64 *p;
17136   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
17137   memsys3Enter();
17138   p = memsys3MallocUnsafe(nBytes);
17139   memsys3Leave();
17140   return (void*)p; 
17141 }
17142 
17143 /*
17144 ** Free memory.
17145 */
17146 static void memsys3Free(void *pPrior){
17147   assert( pPrior );
17148   memsys3Enter();
17149   memsys3FreeUnsafe(pPrior);
17150   memsys3Leave();
17151 }
17152 
17153 /*
17154 ** Change the size of an existing memory allocation
17155 */
17156 static void *memsys3Realloc(void *pPrior, int nBytes){
17157   int nOld;
17158   void *p;
17159   if( pPrior==0 ){
17160     return sqlite3_malloc(nBytes);
17161   }
17162   if( nBytes<=0 ){
17163     sqlite3_free(pPrior);
17164     return 0;
17165   }
17166   nOld = memsys3Size(pPrior);
17167   if( nBytes<=nOld && nBytes>=nOld-128 ){
17168     return pPrior;
17169   }
17170   memsys3Enter();
17171   p = memsys3MallocUnsafe(nBytes);
17172   if( p ){
17173     if( nOld<nBytes ){
17174       memcpy(p, pPrior, nOld);
17175     }else{
17176       memcpy(p, pPrior, nBytes);
17177     }
17178     memsys3FreeUnsafe(pPrior);
17179   }
17180   memsys3Leave();
17181   return p;
17182 }
17183 
17184 /*
17185 ** Initialize this module.
17186 */
17187 static int memsys3Init(void *NotUsed){
17188   UNUSED_PARAMETER(NotUsed);
17189   if( !sqlite3GlobalConfig.pHeap ){
17190     return SQLITE_ERROR;
17191   }
17192 
17193   /* Store a pointer to the memory block in global structure mem3. */
17194   assert( sizeof(Mem3Block)==8 );
17195   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17196   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17197 
17198   /* Initialize the master block. */
17199   mem3.szMaster = mem3.nPool;
17200   mem3.mnMaster = mem3.szMaster;
17201   mem3.iMaster = 1;
17202   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17203   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17204   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17205 
17206   return SQLITE_OK;
17207 }
17208 
17209 /*
17210 ** Deinitialize this module.
17211 */
17212 static void memsys3Shutdown(void *NotUsed){
17213   UNUSED_PARAMETER(NotUsed);
17214   mem3.mutex = 0;
17215   return;
17216 }
17217 
17218 
17219 
17220 /*
17221 ** Open the file indicated and write a log of all unfreed memory 
17222 ** allocations into that log.
17223 */
17224 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17225 #ifdef SQLITE_DEBUG
17226   FILE *out;
17227   u32 i, j;
17228   u32 size;
17229   if( zFilename==0 || zFilename[0]==0 ){
17230     out = stdout;
17231   }else{
17232     out = fopen(zFilename, "w");
17233     if( out==0 ){
17234       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17235                       zFilename);
17236       return;
17237     }
17238   }
17239   memsys3Enter();
17240   fprintf(out, "CHUNKS:\n");
17241   for(i=1; i<=mem3.nPool; i+=size/4){
17242     size = mem3.aPool[i-1].u.hdr.size4x;
17243     if( size/4<=1 ){
17244       fprintf(out, "%p size error\n", &mem3.aPool[i]);
17245       assert( 0 );
17246       break;
17247     }
17248     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17249       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17250       assert( 0 );
17251       break;
17252     }
17253     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17254       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17255       assert( 0 );
17256       break;
17257     }
17258     if( size&1 ){
17259       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17260     }else{
17261       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17262                   i==mem3.iMaster ? " **master**" : "");
17263     }
17264   }
17265   for(i=0; i<MX_SMALL-1; i++){
17266     if( mem3.aiSmall[i]==0 ) continue;
17267     fprintf(out, "small(%2d):", i);
17268     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17269       fprintf(out, " %p(%d)", &mem3.aPool[j],
17270               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17271     }
17272     fprintf(out, "\n"); 
17273   }
17274   for(i=0; i<N_HASH; i++){
17275     if( mem3.aiHash[i]==0 ) continue;
17276     fprintf(out, "hash(%2d):", i);
17277     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17278       fprintf(out, " %p(%d)", &mem3.aPool[j],
17279               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17280     }
17281     fprintf(out, "\n"); 
17282   }
17283   fprintf(out, "master=%d\n", mem3.iMaster);
17284   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17285   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17286   sqlite3_mutex_leave(mem3.mutex);
17287   if( out==stdout ){
17288     fflush(stdout);
17289   }else{
17290     fclose(out);
17291   }
17292 #else
17293   UNUSED_PARAMETER(zFilename);
17294 #endif
17295 }
17296 
17297 /*
17298 ** This routine is the only routine in this file with external 
17299 ** linkage.
17300 **
17301 ** Populate the low-level memory allocation function pointers in
17302 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17303 ** arguments specify the block of memory to manage.
17304 **
17305 ** This routine is only called by sqlite3_config(), and therefore
17306 ** is not required to be threadsafe (it is not).
17307 */
17308 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17309   static const sqlite3_mem_methods mempoolMethods = {
17310      memsys3Malloc,
17311      memsys3Free,
17312      memsys3Realloc,
17313      memsys3Size,
17314      memsys3Roundup,
17315      memsys3Init,
17316      memsys3Shutdown,
17317      0
17318   };
17319   return &mempoolMethods;
17320 }
17321 
17322 #endif /* SQLITE_ENABLE_MEMSYS3 */
17323 
17324 /************** End of mem3.c ************************************************/
17325 /************** Begin file mem5.c ********************************************/
17326 /*
17327 ** 2007 October 14
17328 **
17329 ** The author disclaims copyright to this source code.  In place of
17330 ** a legal notice, here is a blessing:
17331 **
17332 **    May you do good and not evil.
17333 **    May you find forgiveness for yourself and forgive others.
17334 **    May you share freely, never taking more than you give.
17335 **
17336 *************************************************************************
17337 ** This file contains the C functions that implement a memory
17338 ** allocation subsystem for use by SQLite. 
17339 **
17340 ** This version of the memory allocation subsystem omits all
17341 ** use of malloc(). The application gives SQLite a block of memory
17342 ** before calling sqlite3_initialize() from which allocations
17343 ** are made and returned by the xMalloc() and xRealloc() 
17344 ** implementations. Once sqlite3_initialize() has been called,
17345 ** the amount of memory available to SQLite is fixed and cannot
17346 ** be changed.
17347 **
17348 ** This version of the memory allocation subsystem is included
17349 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17350 **
17351 ** This memory allocator uses the following algorithm:
17352 **
17353 **   1.  All memory allocations sizes are rounded up to a power of 2.
17354 **
17355 **   2.  If two adjacent free blocks are the halves of a larger block,
17356 **       then the two blocks are coalesed into the single larger block.
17357 **
17358 **   3.  New memory is allocated from the first available free block.
17359 **
17360 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17361 ** Concerning Dynamic Storage Allocation". Journal of the Association for
17362 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17363 ** 
17364 ** Let n be the size of the largest allocation divided by the minimum
17365 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
17366 ** be the maximum amount of memory ever outstanding at one time.  Let
17367 ** N be the total amount of memory available for allocation.  Robson
17368 ** proved that this memory allocator will never breakdown due to 
17369 ** fragmentation as long as the following constraint holds:
17370 **
17371 **      N >=  M*(1 + log2(n)/2) - n + 1
17372 **
17373 ** The sqlite3_status() logic tracks the maximum values of n and M so
17374 ** that an application can, at any time, verify this constraint.
17375 */
17376 
17377 /*
17378 ** This version of the memory allocator is used only when 
17379 ** SQLITE_ENABLE_MEMSYS5 is defined.
17380 */
17381 #ifdef SQLITE_ENABLE_MEMSYS5
17382 
17383 /*
17384 ** A minimum allocation is an instance of the following structure.
17385 ** Larger allocations are an array of these structures where the
17386 ** size of the array is a power of 2.
17387 **
17388 ** The size of this object must be a power of two.  That fact is
17389 ** verified in memsys5Init().
17390 */
17391 typedef struct Mem5Link Mem5Link;
17392 struct Mem5Link {
17393   int next;       /* Index of next free chunk */
17394   int prev;       /* Index of previous free chunk */
17395 };
17396 
17397 /*
17398 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17399 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17400 ** it is not actually possible to reach this limit.
17401 */
17402 #define LOGMAX 30
17403 
17404 /*
17405 ** Masks used for mem5.aCtrl[] elements.
17406 */
17407 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17408 #define CTRL_FREE     0x20    /* True if not checked out */
17409 
17410 /*
17411 ** All of the static variables used by this module are collected
17412 ** into a single structure named "mem5".  This is to keep the
17413 ** static variables organized and to reduce namespace pollution
17414 ** when this module is combined with other in the amalgamation.
17415 */
17416 static SQLITE_WSD struct Mem5Global {
17417   /*
17418   ** Memory available for allocation
17419   */
17420   int szAtom;      /* Smallest possible allocation in bytes */
17421   int nBlock;      /* Number of szAtom sized blocks in zPool */
17422   u8 *zPool;       /* Memory available to be allocated */
17423   
17424   /*
17425   ** Mutex to control access to the memory allocation subsystem.
17426   */
17427   sqlite3_mutex *mutex;
17428 
17429   /*
17430   ** Performance statistics
17431   */
17432   u64 nAlloc;         /* Total number of calls to malloc */
17433   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17434   u64 totalExcess;    /* Total internal fragmentation */
17435   u32 currentOut;     /* Current checkout, including internal fragmentation */
17436   u32 currentCount;   /* Current number of distinct checkouts */
17437   u32 maxOut;         /* Maximum instantaneous currentOut */
17438   u32 maxCount;       /* Maximum instantaneous currentCount */
17439   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17440   
17441   /*
17442   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17443   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17444   ** and so forth.
17445   */
17446   int aiFreelist[LOGMAX+1];
17447 
17448   /*
17449   ** Space for tracking which blocks are checked out and the size
17450   ** of each block.  One byte per block.
17451   */
17452   u8 *aCtrl;
17453 
17454 } mem5;
17455 
17456 /*
17457 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
17458 */
17459 #define mem5 GLOBAL(struct Mem5Global, mem5)
17460 
17461 /*
17462 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17463 ** structures, return a pointer to the idx-th such link.
17464 */
17465 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17466 
17467 /*
17468 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17469 ** on.  It should be found on mem5.aiFreelist[iLogsize].
17470 */
17471 static void memsys5Unlink(int i, int iLogsize){
17472   int next, prev;
17473   assert( i>=0 && i<mem5.nBlock );
17474   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17475   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17476 
17477   next = MEM5LINK(i)->next;
17478   prev = MEM5LINK(i)->prev;
17479   if( prev<0 ){
17480     mem5.aiFreelist[iLogsize] = next;
17481   }else{
17482     MEM5LINK(prev)->next = next;
17483   }
17484   if( next>=0 ){
17485     MEM5LINK(next)->prev = prev;
17486   }
17487 }
17488 
17489 /*
17490 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17491 ** free list.
17492 */
17493 static void memsys5Link(int i, int iLogsize){
17494   int x;
17495   assert( sqlite3_mutex_held(mem5.mutex) );
17496   assert( i>=0 && i<mem5.nBlock );
17497   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17498   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17499 
17500   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17501   MEM5LINK(i)->prev = -1;
17502   if( x>=0 ){
17503     assert( x<mem5.nBlock );
17504     MEM5LINK(x)->prev = i;
17505   }
17506   mem5.aiFreelist[iLogsize] = i;
17507 }
17508 
17509 /*
17510 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17511 ** will already be held (obtained by code in malloc.c) if
17512 ** sqlite3GlobalConfig.bMemStat is true.
17513 */
17514 static void memsys5Enter(void){
17515   sqlite3_mutex_enter(mem5.mutex);
17516 }
17517 static void memsys5Leave(void){
17518   sqlite3_mutex_leave(mem5.mutex);
17519 }
17520 
17521 /*
17522 ** Return the size of an outstanding allocation, in bytes.  The
17523 ** size returned omits the 8-byte header overhead.  This only
17524 ** works for chunks that are currently checked out.
17525 */
17526 static int memsys5Size(void *p){
17527   int iSize = 0;
17528   if( p ){
17529     int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
17530     assert( i>=0 && i<mem5.nBlock );
17531     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17532   }
17533   return iSize;
17534 }
17535 
17536 /*
17537 ** Return a block of memory of at least nBytes in size.
17538 ** Return NULL if unable.  Return NULL if nBytes==0.
17539 **
17540 ** The caller guarantees that nByte is positive.
17541 **
17542 ** The caller has obtained a mutex prior to invoking this
17543 ** routine so there is never any chance that two or more
17544 ** threads can be in this routine at the same time.
17545 */
17546 static void *memsys5MallocUnsafe(int nByte){
17547   int i;           /* Index of a mem5.aPool[] slot */
17548   int iBin;        /* Index into mem5.aiFreelist[] */
17549   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17550   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17551 
17552   /* nByte must be a positive */
17553   assert( nByte>0 );
17554 
17555   /* Keep track of the maximum allocation request.  Even unfulfilled
17556   ** requests are counted */
17557   if( (u32)nByte>mem5.maxRequest ){
17558     mem5.maxRequest = nByte;
17559   }
17560 
17561   /* Abort if the requested allocation size is larger than the largest
17562   ** power of two that we can represent using 32-bit signed integers.
17563   */
17564   if( nByte > 0x40000000 ){
17565     return 0;
17566   }
17567 
17568   /* Round nByte up to the next valid power of two */
17569   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17570 
17571   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17572   ** block.  If not, then split a block of the next larger power of
17573   ** two in order to create a new free block of size iLogsize.
17574   */
17575   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17576   if( iBin>LOGMAX ){
17577     testcase( sqlite3GlobalConfig.xLog!=0 );
17578     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17579     return 0;
17580   }
17581   i = mem5.aiFreelist[iBin];
17582   memsys5Unlink(i, iBin);
17583   while( iBin>iLogsize ){
17584     int newSize;
17585 
17586     iBin--;
17587     newSize = 1 << iBin;
17588     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17589     memsys5Link(i+newSize, iBin);
17590   }
17591   mem5.aCtrl[i] = iLogsize;
17592 
17593   /* Update allocator performance statistics. */
17594   mem5.nAlloc++;
17595   mem5.totalAlloc += iFullSz;
17596   mem5.totalExcess += iFullSz - nByte;
17597   mem5.currentCount++;
17598   mem5.currentOut += iFullSz;
17599   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17600   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17601 
17602   /* Return a pointer to the allocated memory. */
17603   return (void*)&mem5.zPool[i*mem5.szAtom];
17604 }
17605 
17606 /*
17607 ** Free an outstanding memory allocation.
17608 */
17609 static void memsys5FreeUnsafe(void *pOld){
17610   u32 size, iLogsize;
17611   int iBlock;
17612 
17613   /* Set iBlock to the index of the block pointed to by pOld in 
17614   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17615   */
17616   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
17617 
17618   /* Check that the pointer pOld points to a valid, non-free block. */
17619   assert( iBlock>=0 && iBlock<mem5.nBlock );
17620   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17621   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17622 
17623   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17624   size = 1<<iLogsize;
17625   assert( iBlock+size-1<(u32)mem5.nBlock );
17626 
17627   mem5.aCtrl[iBlock] |= CTRL_FREE;
17628   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17629   assert( mem5.currentCount>0 );
17630   assert( mem5.currentOut>=(size*mem5.szAtom) );
17631   mem5.currentCount--;
17632   mem5.currentOut -= size*mem5.szAtom;
17633   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17634   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17635 
17636   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17637   while( ALWAYS(iLogsize<LOGMAX) ){
17638     int iBuddy;
17639     if( (iBlock>>iLogsize) & 1 ){
17640       iBuddy = iBlock - size;
17641     }else{
17642       iBuddy = iBlock + size;
17643     }
17644     assert( iBuddy>=0 );
17645     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17646     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17647     memsys5Unlink(iBuddy, iLogsize);
17648     iLogsize++;
17649     if( iBuddy<iBlock ){
17650       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17651       mem5.aCtrl[iBlock] = 0;
17652       iBlock = iBuddy;
17653     }else{
17654       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17655       mem5.aCtrl[iBuddy] = 0;
17656     }
17657     size *= 2;
17658   }
17659   memsys5Link(iBlock, iLogsize);
17660 }
17661 
17662 /*
17663 ** Allocate nBytes of memory.
17664 */
17665 static void *memsys5Malloc(int nBytes){
17666   sqlite3_int64 *p = 0;
17667   if( nBytes>0 ){
17668     memsys5Enter();
17669     p = memsys5MallocUnsafe(nBytes);
17670     memsys5Leave();
17671   }
17672   return (void*)p; 
17673 }
17674 
17675 /*
17676 ** Free memory.
17677 **
17678 ** The outer layer memory allocator prevents this routine from
17679 ** being called with pPrior==0.
17680 */
17681 static void memsys5Free(void *pPrior){
17682   assert( pPrior!=0 );
17683   memsys5Enter();
17684   memsys5FreeUnsafe(pPrior);
17685   memsys5Leave();  
17686 }
17687 
17688 /*
17689 ** Change the size of an existing memory allocation.
17690 **
17691 ** The outer layer memory allocator prevents this routine from
17692 ** being called with pPrior==0.  
17693 **
17694 ** nBytes is always a value obtained from a prior call to
17695 ** memsys5Round().  Hence nBytes is always a non-negative power
17696 ** of two.  If nBytes==0 that means that an oversize allocation
17697 ** (an allocation larger than 0x40000000) was requested and this
17698 ** routine should return 0 without freeing pPrior.
17699 */
17700 static void *memsys5Realloc(void *pPrior, int nBytes){
17701   int nOld;
17702   void *p;
17703   assert( pPrior!=0 );
17704   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17705   assert( nBytes>=0 );
17706   if( nBytes==0 ){
17707     return 0;
17708   }
17709   nOld = memsys5Size(pPrior);
17710   if( nBytes<=nOld ){
17711     return pPrior;
17712   }
17713   memsys5Enter();
17714   p = memsys5MallocUnsafe(nBytes);
17715   if( p ){
17716     memcpy(p, pPrior, nOld);
17717     memsys5FreeUnsafe(pPrior);
17718   }
17719   memsys5Leave();
17720   return p;
17721 }
17722 
17723 /*
17724 ** Round up a request size to the next valid allocation size.  If
17725 ** the allocation is too large to be handled by this allocation system,
17726 ** return 0.
17727 **
17728 ** All allocations must be a power of two and must be expressed by a
17729 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17730 ** or 1073741824 bytes.
17731 */
17732 static int memsys5Roundup(int n){
17733   int iFullSz;
17734   if( n > 0x40000000 ) return 0;
17735   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17736   return iFullSz;
17737 }
17738 
17739 /*
17740 ** Return the ceiling of the logarithm base 2 of iValue.
17741 **
17742 ** Examples:   memsys5Log(1) -> 0
17743 **             memsys5Log(2) -> 1
17744 **             memsys5Log(4) -> 2
17745 **             memsys5Log(5) -> 3
17746 **             memsys5Log(8) -> 3
17747 **             memsys5Log(9) -> 4
17748 */
17749 static int memsys5Log(int iValue){
17750   int iLog;
17751   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17752   return iLog;
17753 }
17754 
17755 /*
17756 ** Initialize the memory allocator.
17757 **
17758 ** This routine is not threadsafe.  The caller must be holding a mutex
17759 ** to prevent multiple threads from entering at the same time.
17760 */
17761 static int memsys5Init(void *NotUsed){
17762   int ii;            /* Loop counter */
17763   int nByte;         /* Number of bytes of memory available to this allocator */
17764   u8 *zByte;         /* Memory usable by this allocator */
17765   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17766   int iOffset;       /* An offset into mem5.aCtrl[] */
17767 
17768   UNUSED_PARAMETER(NotUsed);
17769 
17770   /* For the purposes of this routine, disable the mutex */
17771   mem5.mutex = 0;
17772 
17773   /* The size of a Mem5Link object must be a power of two.  Verify that
17774   ** this is case.
17775   */
17776   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17777 
17778   nByte = sqlite3GlobalConfig.nHeap;
17779   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17780   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17781 
17782   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17783   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17784   mem5.szAtom = (1<<nMinLog);
17785   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17786     mem5.szAtom = mem5.szAtom << 1;
17787   }
17788 
17789   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17790   mem5.zPool = zByte;
17791   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17792 
17793   for(ii=0; ii<=LOGMAX; ii++){
17794     mem5.aiFreelist[ii] = -1;
17795   }
17796 
17797   iOffset = 0;
17798   for(ii=LOGMAX; ii>=0; ii--){
17799     int nAlloc = (1<<ii);
17800     if( (iOffset+nAlloc)<=mem5.nBlock ){
17801       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17802       memsys5Link(iOffset, ii);
17803       iOffset += nAlloc;
17804     }
17805     assert((iOffset+nAlloc)>mem5.nBlock);
17806   }
17807 
17808   /* If a mutex is required for normal operation, allocate one */
17809   if( sqlite3GlobalConfig.bMemstat==0 ){
17810     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17811   }
17812 
17813   return SQLITE_OK;
17814 }
17815 
17816 /*
17817 ** Deinitialize this module.
17818 */
17819 static void memsys5Shutdown(void *NotUsed){
17820   UNUSED_PARAMETER(NotUsed);
17821   mem5.mutex = 0;
17822   return;
17823 }
17824 
17825 #ifdef SQLITE_TEST
17826 /*
17827 ** Open the file indicated and write a log of all unfreed memory 
17828 ** allocations into that log.
17829 */
17830 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17831   FILE *out;
17832   int i, j, n;
17833   int nMinLog;
17834 
17835   if( zFilename==0 || zFilename[0]==0 ){
17836     out = stdout;
17837   }else{
17838     out = fopen(zFilename, "w");
17839     if( out==0 ){
17840       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17841                       zFilename);
17842       return;
17843     }
17844   }
17845   memsys5Enter();
17846   nMinLog = memsys5Log(mem5.szAtom);
17847   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17848     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17849     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17850   }
17851   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17852   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17853   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17854   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17855   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17856   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17857   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17858   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17859   memsys5Leave();
17860   if( out==stdout ){
17861     fflush(stdout);
17862   }else{
17863     fclose(out);
17864   }
17865 }
17866 #endif
17867 
17868 /*
17869 ** This routine is the only routine in this file with external 
17870 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17871 ** struct populated with the memsys5 methods.
17872 */
17873 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17874   static const sqlite3_mem_methods memsys5Methods = {
17875      memsys5Malloc,
17876      memsys5Free,
17877      memsys5Realloc,
17878      memsys5Size,
17879      memsys5Roundup,
17880      memsys5Init,
17881      memsys5Shutdown,
17882      0
17883   };
17884   return &memsys5Methods;
17885 }
17886 
17887 #endif /* SQLITE_ENABLE_MEMSYS5 */
17888 
17889 /************** End of mem5.c ************************************************/
17890 /************** Begin file mutex.c *******************************************/
17891 /*
17892 ** 2007 August 14
17893 **
17894 ** The author disclaims copyright to this source code.  In place of
17895 ** a legal notice, here is a blessing:
17896 **
17897 **    May you do good and not evil.
17898 **    May you find forgiveness for yourself and forgive others.
17899 **    May you share freely, never taking more than you give.
17900 **
17901 *************************************************************************
17902 ** This file contains the C functions that implement mutexes.
17903 **
17904 ** This file contains code that is common across all mutex implementations.
17905 */
17906 
17907 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17908 /*
17909 ** For debugging purposes, record when the mutex subsystem is initialized
17910 ** and uninitialized so that we can assert() if there is an attempt to
17911 ** allocate a mutex while the system is uninitialized.
17912 */
17913 static SQLITE_WSD int mutexIsInit = 0;
17914 #endif /* SQLITE_DEBUG */
17915 
17916 
17917 #ifndef SQLITE_MUTEX_OMIT
17918 /*
17919 ** Initialize the mutex system.
17920 */
17921 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17922   int rc = SQLITE_OK;
17923   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17924     /* If the xMutexAlloc method has not been set, then the user did not
17925     ** install a mutex implementation via sqlite3_config() prior to 
17926     ** sqlite3_initialize() being called. This block copies pointers to
17927     ** the default implementation into the sqlite3GlobalConfig structure.
17928     */
17929     sqlite3_mutex_methods const *pFrom;
17930     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17931 
17932     if( sqlite3GlobalConfig.bCoreMutex ){
17933       pFrom = sqlite3DefaultMutex();
17934     }else{
17935       pFrom = sqlite3NoopMutex();
17936     }
17937     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17938     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17939            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17940     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17941   }
17942   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17943 
17944 #ifdef SQLITE_DEBUG
17945   GLOBAL(int, mutexIsInit) = 1;
17946 #endif
17947 
17948   return rc;
17949 }
17950 
17951 /*
17952 ** Shutdown the mutex system. This call frees resources allocated by
17953 ** sqlite3MutexInit().
17954 */
17955 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17956   int rc = SQLITE_OK;
17957   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17958     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17959   }
17960 
17961 #ifdef SQLITE_DEBUG
17962   GLOBAL(int, mutexIsInit) = 0;
17963 #endif
17964 
17965   return rc;
17966 }
17967 
17968 /*
17969 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17970 */
17971 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17972 #ifndef SQLITE_OMIT_AUTOINIT
17973   if( sqlite3_initialize() ) return 0;
17974 #endif
17975   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17976 }
17977 
17978 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17979   if( !sqlite3GlobalConfig.bCoreMutex ){
17980     return 0;
17981   }
17982   assert( GLOBAL(int, mutexIsInit) );
17983   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17984 }
17985 
17986 /*
17987 ** Free a dynamic mutex.
17988 */
17989 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17990   if( p ){
17991     sqlite3GlobalConfig.mutex.xMutexFree(p);
17992   }
17993 }
17994 
17995 /*
17996 ** Obtain the mutex p. If some other thread already has the mutex, block
17997 ** until it can be obtained.
17998 */
17999 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18000   if( p ){
18001     sqlite3GlobalConfig.mutex.xMutexEnter(p);
18002   }
18003 }
18004 
18005 /*
18006 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18007 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18008 */
18009 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18010   int rc = SQLITE_OK;
18011   if( p ){
18012     return sqlite3GlobalConfig.mutex.xMutexTry(p);
18013   }
18014   return rc;
18015 }
18016 
18017 /*
18018 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
18019 ** entered by the same thread.  The behavior is undefined if the mutex 
18020 ** is not currently entered. If a NULL pointer is passed as an argument
18021 ** this function is a no-op.
18022 */
18023 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18024   if( p ){
18025     sqlite3GlobalConfig.mutex.xMutexLeave(p);
18026   }
18027 }
18028 
18029 #ifndef NDEBUG
18030 /*
18031 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18032 ** intended for use inside assert() statements.
18033 */
18034 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18035   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18036 }
18037 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18038   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18039 }
18040 #endif
18041 
18042 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18043 
18044 /************** End of mutex.c ***********************************************/
18045 /************** Begin file mutex_noop.c **************************************/
18046 /*
18047 ** 2008 October 07
18048 **
18049 ** The author disclaims copyright to this source code.  In place of
18050 ** a legal notice, here is a blessing:
18051 **
18052 **    May you do good and not evil.
18053 **    May you find forgiveness for yourself and forgive others.
18054 **    May you share freely, never taking more than you give.
18055 **
18056 *************************************************************************
18057 ** This file contains the C functions that implement mutexes.
18058 **
18059 ** This implementation in this file does not provide any mutual
18060 ** exclusion and is thus suitable for use only in applications
18061 ** that use SQLite in a single thread.  The routines defined
18062 ** here are place-holders.  Applications can substitute working
18063 ** mutex routines at start-time using the
18064 **
18065 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18066 **
18067 ** interface.
18068 **
18069 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
18070 ** that does error checking on mutexes to make sure they are being
18071 ** called correctly.
18072 */
18073 
18074 #ifndef SQLITE_MUTEX_OMIT
18075 
18076 #ifndef SQLITE_DEBUG
18077 /*
18078 ** Stub routines for all mutex methods.
18079 **
18080 ** This routines provide no mutual exclusion or error checking.
18081 */
18082 static int noopMutexInit(void){ return SQLITE_OK; }
18083 static int noopMutexEnd(void){ return SQLITE_OK; }
18084 static sqlite3_mutex *noopMutexAlloc(int id){ 
18085   UNUSED_PARAMETER(id);
18086   return (sqlite3_mutex*)8; 
18087 }
18088 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18089 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18090 static int noopMutexTry(sqlite3_mutex *p){
18091   UNUSED_PARAMETER(p);
18092   return SQLITE_OK;
18093 }
18094 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18095 
18096 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18097   static const sqlite3_mutex_methods sMutex = {
18098     noopMutexInit,
18099     noopMutexEnd,
18100     noopMutexAlloc,
18101     noopMutexFree,
18102     noopMutexEnter,
18103     noopMutexTry,
18104     noopMutexLeave,
18105 
18106     0,
18107     0,
18108   };
18109 
18110   return &sMutex;
18111 }
18112 #endif /* !SQLITE_DEBUG */
18113 
18114 #ifdef SQLITE_DEBUG
18115 /*
18116 ** In this implementation, error checking is provided for testing
18117 ** and debugging purposes.  The mutexes still do not provide any
18118 ** mutual exclusion.
18119 */
18120 
18121 /*
18122 ** The mutex object
18123 */
18124 typedef struct sqlite3_debug_mutex {
18125   int id;     /* The mutex type */
18126   int cnt;    /* Number of entries without a matching leave */
18127 } sqlite3_debug_mutex;
18128 
18129 /*
18130 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18131 ** intended for use inside assert() statements.
18132 */
18133 static int debugMutexHeld(sqlite3_mutex *pX){
18134   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18135   return p==0 || p->cnt>0;
18136 }
18137 static int debugMutexNotheld(sqlite3_mutex *pX){
18138   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18139   return p==0 || p->cnt==0;
18140 }
18141 
18142 /*
18143 ** Initialize and deinitialize the mutex subsystem.
18144 */
18145 static int debugMutexInit(void){ return SQLITE_OK; }
18146 static int debugMutexEnd(void){ return SQLITE_OK; }
18147 
18148 /*
18149 ** The sqlite3_mutex_alloc() routine allocates a new
18150 ** mutex and returns a pointer to it.  If it returns NULL
18151 ** that means that a mutex could not be allocated. 
18152 */
18153 static sqlite3_mutex *debugMutexAlloc(int id){
18154   static sqlite3_debug_mutex aStatic[6];
18155   sqlite3_debug_mutex *pNew = 0;
18156   switch( id ){
18157     case SQLITE_MUTEX_FAST:
18158     case SQLITE_MUTEX_RECURSIVE: {
18159       pNew = sqlite3Malloc(sizeof(*pNew));
18160       if( pNew ){
18161         pNew->id = id;
18162         pNew->cnt = 0;
18163       }
18164       break;
18165     }
18166     default: {
18167       assert( id-2 >= 0 );
18168       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18169       pNew = &aStatic[id-2];
18170       pNew->id = id;
18171       break;
18172     }
18173   }
18174   return (sqlite3_mutex*)pNew;
18175 }
18176 
18177 /*
18178 ** This routine deallocates a previously allocated mutex.
18179 */
18180 static void debugMutexFree(sqlite3_mutex *pX){
18181   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18182   assert( p->cnt==0 );
18183   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18184   sqlite3_free(p);
18185 }
18186 
18187 /*
18188 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18189 ** to enter a mutex.  If another thread is already within the mutex,
18190 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18191 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18192 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18193 ** be entered multiple times by the same thread.  In such cases the,
18194 ** mutex must be exited an equal number of times before another thread
18195 ** can enter.  If the same thread tries to enter any other kind of mutex
18196 ** more than once, the behavior is undefined.
18197 */
18198 static void debugMutexEnter(sqlite3_mutex *pX){
18199   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18200   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18201   p->cnt++;
18202 }
18203 static int debugMutexTry(sqlite3_mutex *pX){
18204   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18205   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18206   p->cnt++;
18207   return SQLITE_OK;
18208 }
18209 
18210 /*
18211 ** The sqlite3_mutex_leave() routine exits a mutex that was
18212 ** previously entered by the same thread.  The behavior
18213 ** is undefined if the mutex is not currently entered or
18214 ** is not currently allocated.  SQLite will never do either.
18215 */
18216 static void debugMutexLeave(sqlite3_mutex *pX){
18217   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18218   assert( debugMutexHeld(pX) );
18219   p->cnt--;
18220   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18221 }
18222 
18223 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18224   static const sqlite3_mutex_methods sMutex = {
18225     debugMutexInit,
18226     debugMutexEnd,
18227     debugMutexAlloc,
18228     debugMutexFree,
18229     debugMutexEnter,
18230     debugMutexTry,
18231     debugMutexLeave,
18232 
18233     debugMutexHeld,
18234     debugMutexNotheld
18235   };
18236 
18237   return &sMutex;
18238 }
18239 #endif /* SQLITE_DEBUG */
18240 
18241 /*
18242 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18243 ** is used regardless of the run-time threadsafety setting.
18244 */
18245 #ifdef SQLITE_MUTEX_NOOP
18246 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18247   return sqlite3NoopMutex();
18248 }
18249 #endif /* defined(SQLITE_MUTEX_NOOP) */
18250 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18251 
18252 /************** End of mutex_noop.c ******************************************/
18253 /************** Begin file mutex_unix.c **************************************/
18254 /*
18255 ** 2007 August 28
18256 **
18257 ** The author disclaims copyright to this source code.  In place of
18258 ** a legal notice, here is a blessing:
18259 **
18260 **    May you do good and not evil.
18261 **    May you find forgiveness for yourself and forgive others.
18262 **    May you share freely, never taking more than you give.
18263 **
18264 *************************************************************************
18265 ** This file contains the C functions that implement mutexes for pthreads
18266 */
18267 
18268 /*
18269 ** The code in this file is only used if we are compiling threadsafe
18270 ** under unix with pthreads.
18271 **
18272 ** Note that this implementation requires a version of pthreads that
18273 ** supports recursive mutexes.
18274 */
18275 #ifdef SQLITE_MUTEX_PTHREADS
18276 
18277 #include <pthread.h>
18278 
18279 /*
18280 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18281 ** are necessary under two condidtions:  (1) Debug builds and (2) using
18282 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
18283 */
18284 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18285 # define SQLITE_MUTEX_NREF 1
18286 #else
18287 # define SQLITE_MUTEX_NREF 0
18288 #endif
18289 
18290 /*
18291 ** Each recursive mutex is an instance of the following structure.
18292 */
18293 struct sqlite3_mutex {
18294   pthread_mutex_t mutex;     /* Mutex controlling the lock */
18295 #if SQLITE_MUTEX_NREF
18296   int id;                    /* Mutex type */
18297   volatile int nRef;         /* Number of entrances */
18298   volatile pthread_t owner;  /* Thread that is within this mutex */
18299   int trace;                 /* True to trace changes */
18300 #endif
18301 };
18302 #if SQLITE_MUTEX_NREF
18303 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18304 #else
18305 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18306 #endif
18307 
18308 /*
18309 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18310 ** intended for use only inside assert() statements.  On some platforms,
18311 ** there might be race conditions that can cause these routines to
18312 ** deliver incorrect results.  In particular, if pthread_equal() is
18313 ** not an atomic operation, then these routines might delivery
18314 ** incorrect results.  On most platforms, pthread_equal() is a 
18315 ** comparison of two integers and is therefore atomic.  But we are
18316 ** told that HPUX is not such a platform.  If so, then these routines
18317 ** will not always work correctly on HPUX.
18318 **
18319 ** On those platforms where pthread_equal() is not atomic, SQLite
18320 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18321 ** make sure no assert() statements are evaluated and hence these
18322 ** routines are never called.
18323 */
18324 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18325 static int pthreadMutexHeld(sqlite3_mutex *p){
18326   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18327 }
18328 static int pthreadMutexNotheld(sqlite3_mutex *p){
18329   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18330 }
18331 #endif
18332 
18333 /*
18334 ** Initialize and deinitialize the mutex subsystem.
18335 */
18336 static int pthreadMutexInit(void){ return SQLITE_OK; }
18337 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18338 
18339 /*
18340 ** The sqlite3_mutex_alloc() routine allocates a new
18341 ** mutex and returns a pointer to it.  If it returns NULL
18342 ** that means that a mutex could not be allocated.  SQLite
18343 ** will unwind its stack and return an error.  The argument
18344 ** to sqlite3_mutex_alloc() is one of these integer constants:
18345 **
18346 ** <ul>
18347 ** <li>  SQLITE_MUTEX_FAST
18348 ** <li>  SQLITE_MUTEX_RECURSIVE
18349 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18350 ** <li>  SQLITE_MUTEX_STATIC_MEM
18351 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18352 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18353 ** <li>  SQLITE_MUTEX_STATIC_LRU
18354 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18355 ** </ul>
18356 **
18357 ** The first two constants cause sqlite3_mutex_alloc() to create
18358 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18359 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18360 ** The mutex implementation does not need to make a distinction
18361 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18362 ** not want to.  But SQLite will only request a recursive mutex in
18363 ** cases where it really needs one.  If a faster non-recursive mutex
18364 ** implementation is available on the host platform, the mutex subsystem
18365 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18366 **
18367 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18368 ** a pointer to a static preexisting mutex.  Six static mutexes are
18369 ** used by the current version of SQLite.  Future versions of SQLite
18370 ** may add additional static mutexes.  Static mutexes are for internal
18371 ** use by SQLite only.  Applications that use SQLite mutexes should
18372 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18373 ** SQLITE_MUTEX_RECURSIVE.
18374 **
18375 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18376 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18377 ** returns a different mutex on every call.  But for the static 
18378 ** mutex types, the same mutex is returned on every call that has
18379 ** the same type number.
18380 */
18381 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18382   static sqlite3_mutex staticMutexes[] = {
18383     SQLITE3_MUTEX_INITIALIZER,
18384     SQLITE3_MUTEX_INITIALIZER,
18385     SQLITE3_MUTEX_INITIALIZER,
18386     SQLITE3_MUTEX_INITIALIZER,
18387     SQLITE3_MUTEX_INITIALIZER,
18388     SQLITE3_MUTEX_INITIALIZER
18389   };
18390   sqlite3_mutex *p;
18391   switch( iType ){
18392     case SQLITE_MUTEX_RECURSIVE: {
18393       p = sqlite3MallocZero( sizeof(*p) );
18394       if( p ){
18395 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18396         /* If recursive mutexes are not available, we will have to
18397         ** build our own.  See below. */
18398         pthread_mutex_init(&p->mutex, 0);
18399 #else
18400         /* Use a recursive mutex if it is available */
18401         pthread_mutexattr_t recursiveAttr;
18402         pthread_mutexattr_init(&recursiveAttr);
18403         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18404         pthread_mutex_init(&p->mutex, &recursiveAttr);
18405         pthread_mutexattr_destroy(&recursiveAttr);
18406 #endif
18407 #if SQLITE_MUTEX_NREF
18408         p->id = iType;
18409 #endif
18410       }
18411       break;
18412     }
18413     case SQLITE_MUTEX_FAST: {
18414       p = sqlite3MallocZero( sizeof(*p) );
18415       if( p ){
18416 #if SQLITE_MUTEX_NREF
18417         p->id = iType;
18418 #endif
18419         pthread_mutex_init(&p->mutex, 0);
18420       }
18421       break;
18422     }
18423     default: {
18424       assert( iType-2 >= 0 );
18425       assert( iType-2 < ArraySize(staticMutexes) );
18426       p = &staticMutexes[iType-2];
18427 #if SQLITE_MUTEX_NREF
18428       p->id = iType;
18429 #endif
18430       break;
18431     }
18432   }
18433   return p;
18434 }
18435 
18436 
18437 /*
18438 ** This routine deallocates a previously
18439 ** allocated mutex.  SQLite is careful to deallocate every
18440 ** mutex that it allocates.
18441 */
18442 static void pthreadMutexFree(sqlite3_mutex *p){
18443   assert( p->nRef==0 );
18444   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18445   pthread_mutex_destroy(&p->mutex);
18446   sqlite3_free(p);
18447 }
18448 
18449 /*
18450 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18451 ** to enter a mutex.  If another thread is already within the mutex,
18452 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18453 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18454 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18455 ** be entered multiple times by the same thread.  In such cases the,
18456 ** mutex must be exited an equal number of times before another thread
18457 ** can enter.  If the same thread tries to enter any other kind of mutex
18458 ** more than once, the behavior is undefined.
18459 */
18460 static void pthreadMutexEnter(sqlite3_mutex *p){
18461   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18462 
18463 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18464   /* If recursive mutexes are not available, then we have to grow
18465   ** our own.  This implementation assumes that pthread_equal()
18466   ** is atomic - that it cannot be deceived into thinking self
18467   ** and p->owner are equal if p->owner changes between two values
18468   ** that are not equal to self while the comparison is taking place.
18469   ** This implementation also assumes a coherent cache - that 
18470   ** separate processes cannot read different values from the same
18471   ** address at the same time.  If either of these two conditions
18472   ** are not met, then the mutexes will fail and problems will result.
18473   */
18474   {
18475     pthread_t self = pthread_self();
18476     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18477       p->nRef++;
18478     }else{
18479       pthread_mutex_lock(&p->mutex);
18480       assert( p->nRef==0 );
18481       p->owner = self;
18482       p->nRef = 1;
18483     }
18484   }
18485 #else
18486   /* Use the built-in recursive mutexes if they are available.
18487   */
18488   pthread_mutex_lock(&p->mutex);
18489 #if SQLITE_MUTEX_NREF
18490   assert( p->nRef>0 || p->owner==0 );
18491   p->owner = pthread_self();
18492   p->nRef++;
18493 #endif
18494 #endif
18495 
18496 #ifdef SQLITE_DEBUG
18497   if( p->trace ){
18498     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18499   }
18500 #endif
18501 }
18502 static int pthreadMutexTry(sqlite3_mutex *p){
18503   int rc;
18504   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18505 
18506 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18507   /* If recursive mutexes are not available, then we have to grow
18508   ** our own.  This implementation assumes that pthread_equal()
18509   ** is atomic - that it cannot be deceived into thinking self
18510   ** and p->owner are equal if p->owner changes between two values
18511   ** that are not equal to self while the comparison is taking place.
18512   ** This implementation also assumes a coherent cache - that 
18513   ** separate processes cannot read different values from the same
18514   ** address at the same time.  If either of these two conditions
18515   ** are not met, then the mutexes will fail and problems will result.
18516   */
18517   {
18518     pthread_t self = pthread_self();
18519     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18520       p->nRef++;
18521       rc = SQLITE_OK;
18522     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18523       assert( p->nRef==0 );
18524       p->owner = self;
18525       p->nRef = 1;
18526       rc = SQLITE_OK;
18527     }else{
18528       rc = SQLITE_BUSY;
18529     }
18530   }
18531 #else
18532   /* Use the built-in recursive mutexes if they are available.
18533   */
18534   if( pthread_mutex_trylock(&p->mutex)==0 ){
18535 #if SQLITE_MUTEX_NREF
18536     p->owner = pthread_self();
18537     p->nRef++;
18538 #endif
18539     rc = SQLITE_OK;
18540   }else{
18541     rc = SQLITE_BUSY;
18542   }
18543 #endif
18544 
18545 #ifdef SQLITE_DEBUG
18546   if( rc==SQLITE_OK && p->trace ){
18547     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18548   }
18549 #endif
18550   return rc;
18551 }
18552 
18553 /*
18554 ** The sqlite3_mutex_leave() routine exits a mutex that was
18555 ** previously entered by the same thread.  The behavior
18556 ** is undefined if the mutex is not currently entered or
18557 ** is not currently allocated.  SQLite will never do either.
18558 */
18559 static void pthreadMutexLeave(sqlite3_mutex *p){
18560   assert( pthreadMutexHeld(p) );
18561 #if SQLITE_MUTEX_NREF
18562   p->nRef--;
18563   if( p->nRef==0 ) p->owner = 0;
18564 #endif
18565   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18566 
18567 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18568   if( p->nRef==0 ){
18569     pthread_mutex_unlock(&p->mutex);
18570   }
18571 #else
18572   pthread_mutex_unlock(&p->mutex);
18573 #endif
18574 
18575 #ifdef SQLITE_DEBUG
18576   if( p->trace ){
18577     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18578   }
18579 #endif
18580 }
18581 
18582 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18583   static const sqlite3_mutex_methods sMutex = {
18584     pthreadMutexInit,
18585     pthreadMutexEnd,
18586     pthreadMutexAlloc,
18587     pthreadMutexFree,
18588     pthreadMutexEnter,
18589     pthreadMutexTry,
18590     pthreadMutexLeave,
18591 #ifdef SQLITE_DEBUG
18592     pthreadMutexHeld,
18593     pthreadMutexNotheld
18594 #else
18595     0,
18596     0
18597 #endif
18598   };
18599 
18600   return &sMutex;
18601 }
18602 
18603 #endif /* SQLITE_MUTEX_PTHREADS */
18604 
18605 /************** End of mutex_unix.c ******************************************/
18606 /************** Begin file mutex_w32.c ***************************************/
18607 /*
18608 ** 2007 August 14
18609 **
18610 ** The author disclaims copyright to this source code.  In place of
18611 ** a legal notice, here is a blessing:
18612 **
18613 **    May you do good and not evil.
18614 **    May you find forgiveness for yourself and forgive others.
18615 **    May you share freely, never taking more than you give.
18616 **
18617 *************************************************************************
18618 ** This file contains the C functions that implement mutexes for win32
18619 */
18620 
18621 /*
18622 ** The code in this file is only used if we are compiling multithreaded
18623 ** on a win32 system.
18624 */
18625 #ifdef SQLITE_MUTEX_W32
18626 
18627 /*
18628 ** Each recursive mutex is an instance of the following structure.
18629 */
18630 struct sqlite3_mutex {
18631   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18632   int id;                    /* Mutex type */
18633 #ifdef SQLITE_DEBUG
18634   volatile int nRef;         /* Number of enterances */
18635   volatile DWORD owner;      /* Thread holding this mutex */
18636   int trace;                 /* True to trace changes */
18637 #endif
18638 };
18639 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18640 #ifdef SQLITE_DEBUG
18641 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18642 #else
18643 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18644 #endif
18645 
18646 /*
18647 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18648 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18649 **
18650 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18651 ** the LockFileEx() API.  But we can still statically link against that
18652 ** API as long as we don't call it win running Win95/98/ME.  A call to
18653 ** this routine is used to determine if the host is Win95/98/ME or
18654 ** WinNT/2K/XP so that we will know whether or not we can safely call
18655 ** the LockFileEx() API.
18656 **
18657 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18658 ** which is only available if your application was compiled with 
18659 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18660 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18661 ** this out as well.
18662 */
18663 #if 0
18664 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18665 # define mutexIsNT()  (1)
18666 #else
18667   static int mutexIsNT(void){
18668     static int osType = 0;
18669     if( osType==0 ){
18670       OSVERSIONINFO sInfo;
18671       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18672       GetVersionEx(&sInfo);
18673       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18674     }
18675     return osType==2;
18676   }
18677 #endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
18678 #endif
18679 
18680 #ifdef SQLITE_DEBUG
18681 /*
18682 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18683 ** intended for use only inside assert() statements.
18684 */
18685 static int winMutexHeld(sqlite3_mutex *p){
18686   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18687 }
18688 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18689   return p->nRef==0 || p->owner!=tid;
18690 }
18691 static int winMutexNotheld(sqlite3_mutex *p){
18692   DWORD tid = GetCurrentThreadId(); 
18693   return winMutexNotheld2(p, tid);
18694 }
18695 #endif
18696 
18697 
18698 /*
18699 ** Initialize and deinitialize the mutex subsystem.
18700 */
18701 static sqlite3_mutex winMutex_staticMutexes[6] = {
18702   SQLITE3_MUTEX_INITIALIZER,
18703   SQLITE3_MUTEX_INITIALIZER,
18704   SQLITE3_MUTEX_INITIALIZER,
18705   SQLITE3_MUTEX_INITIALIZER,
18706   SQLITE3_MUTEX_INITIALIZER,
18707   SQLITE3_MUTEX_INITIALIZER
18708 };
18709 static int winMutex_isInit = 0;
18710 /* As winMutexInit() and winMutexEnd() are called as part
18711 ** of the sqlite3_initialize and sqlite3_shutdown()
18712 ** processing, the "interlocked" magic is probably not
18713 ** strictly necessary.
18714 */
18715 static LONG winMutex_lock = 0;
18716 
18717 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18718 
18719 static int winMutexInit(void){ 
18720   /* The first to increment to 1 does actual initialization */
18721   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18722     int i;
18723     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18724 #if SQLITE_OS_WINRT
18725       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18726 #else
18727       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18728 #endif
18729     }
18730     winMutex_isInit = 1;
18731   }else{
18732     /* Someone else is in the process of initing the static mutexes */
18733     while( !winMutex_isInit ){
18734       sqlite3_win32_sleep(1);
18735     }
18736   }
18737   return SQLITE_OK; 
18738 }
18739 
18740 static int winMutexEnd(void){ 
18741   /* The first to decrement to 0 does actual shutdown 
18742   ** (which should be the last to shutdown.) */
18743   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18744     if( winMutex_isInit==1 ){
18745       int i;
18746       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18747         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18748       }
18749       winMutex_isInit = 0;
18750     }
18751   }
18752   return SQLITE_OK; 
18753 }
18754 
18755 /*
18756 ** The sqlite3_mutex_alloc() routine allocates a new
18757 ** mutex and returns a pointer to it.  If it returns NULL
18758 ** that means that a mutex could not be allocated.  SQLite
18759 ** will unwind its stack and return an error.  The argument
18760 ** to sqlite3_mutex_alloc() is one of these integer constants:
18761 **
18762 ** <ul>
18763 ** <li>  SQLITE_MUTEX_FAST
18764 ** <li>  SQLITE_MUTEX_RECURSIVE
18765 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18766 ** <li>  SQLITE_MUTEX_STATIC_MEM
18767 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18768 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18769 ** <li>  SQLITE_MUTEX_STATIC_LRU
18770 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18771 ** </ul>
18772 **
18773 ** The first two constants cause sqlite3_mutex_alloc() to create
18774 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18775 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18776 ** The mutex implementation does not need to make a distinction
18777 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18778 ** not want to.  But SQLite will only request a recursive mutex in
18779 ** cases where it really needs one.  If a faster non-recursive mutex
18780 ** implementation is available on the host platform, the mutex subsystem
18781 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18782 **
18783 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18784 ** a pointer to a static preexisting mutex.  Six static mutexes are
18785 ** used by the current version of SQLite.  Future versions of SQLite
18786 ** may add additional static mutexes.  Static mutexes are for internal
18787 ** use by SQLite only.  Applications that use SQLite mutexes should
18788 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18789 ** SQLITE_MUTEX_RECURSIVE.
18790 **
18791 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18792 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18793 ** returns a different mutex on every call.  But for the static 
18794 ** mutex types, the same mutex is returned on every call that has
18795 ** the same type number.
18796 */
18797 static sqlite3_mutex *winMutexAlloc(int iType){
18798   sqlite3_mutex *p;
18799 
18800   switch( iType ){
18801     case SQLITE_MUTEX_FAST:
18802     case SQLITE_MUTEX_RECURSIVE: {
18803       p = sqlite3MallocZero( sizeof(*p) );
18804       if( p ){  
18805 #ifdef SQLITE_DEBUG
18806         p->id = iType;
18807 #endif
18808 #if SQLITE_OS_WINRT
18809         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18810 #else
18811         InitializeCriticalSection(&p->mutex);
18812 #endif
18813       }
18814       break;
18815     }
18816     default: {
18817       assert( winMutex_isInit==1 );
18818       assert( iType-2 >= 0 );
18819       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18820       p = &winMutex_staticMutexes[iType-2];
18821 #ifdef SQLITE_DEBUG
18822       p->id = iType;
18823 #endif
18824       break;
18825     }
18826   }
18827   return p;
18828 }
18829 
18830 
18831 /*
18832 ** This routine deallocates a previously
18833 ** allocated mutex.  SQLite is careful to deallocate every
18834 ** mutex that it allocates.
18835 */
18836 static void winMutexFree(sqlite3_mutex *p){
18837   assert( p );
18838   assert( p->nRef==0 && p->owner==0 );
18839   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18840   DeleteCriticalSection(&p->mutex);
18841   sqlite3_free(p);
18842 }
18843 
18844 /*
18845 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18846 ** to enter a mutex.  If another thread is already within the mutex,
18847 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18848 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18849 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18850 ** be entered multiple times by the same thread.  In such cases the,
18851 ** mutex must be exited an equal number of times before another thread
18852 ** can enter.  If the same thread tries to enter any other kind of mutex
18853 ** more than once, the behavior is undefined.
18854 */
18855 static void winMutexEnter(sqlite3_mutex *p){
18856 #ifdef SQLITE_DEBUG
18857   DWORD tid = GetCurrentThreadId(); 
18858   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18859 #endif
18860   EnterCriticalSection(&p->mutex);
18861 #ifdef SQLITE_DEBUG
18862   assert( p->nRef>0 || p->owner==0 );
18863   p->owner = tid; 
18864   p->nRef++;
18865   if( p->trace ){
18866     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18867   }
18868 #endif
18869 }
18870 static int winMutexTry(sqlite3_mutex *p){
18871 #ifndef NDEBUG
18872   DWORD tid = GetCurrentThreadId(); 
18873 #endif
18874   int rc = SQLITE_BUSY;
18875   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18876   /*
18877   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18878   ** is used it is merely an optimization.  So it is OK for it to always
18879   ** fail.  
18880   **
18881   ** The TryEnterCriticalSection() interface is only available on WinNT.
18882   ** And some windows compilers complain if you try to use it without
18883   ** first doing some #defines that prevent SQLite from building on Win98.
18884   ** For that reason, we will omit this optimization for now.  See
18885   ** ticket #2685.
18886   */
18887 #if 0
18888   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18889     p->owner = tid;
18890     p->nRef++;
18891     rc = SQLITE_OK;
18892   }
18893 #else
18894   UNUSED_PARAMETER(p);
18895 #endif
18896 #ifdef SQLITE_DEBUG
18897   if( rc==SQLITE_OK && p->trace ){
18898     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18899   }
18900 #endif
18901   return rc;
18902 }
18903 
18904 /*
18905 ** The sqlite3_mutex_leave() routine exits a mutex that was
18906 ** previously entered by the same thread.  The behavior
18907 ** is undefined if the mutex is not currently entered or
18908 ** is not currently allocated.  SQLite will never do either.
18909 */
18910 static void winMutexLeave(sqlite3_mutex *p){
18911 #ifndef NDEBUG
18912   DWORD tid = GetCurrentThreadId();
18913   assert( p->nRef>0 );
18914   assert( p->owner==tid );
18915   p->nRef--;
18916   if( p->nRef==0 ) p->owner = 0;
18917   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18918 #endif
18919   LeaveCriticalSection(&p->mutex);
18920 #ifdef SQLITE_DEBUG
18921   if( p->trace ){
18922     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18923   }
18924 #endif
18925 }
18926 
18927 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18928   static const sqlite3_mutex_methods sMutex = {
18929     winMutexInit,
18930     winMutexEnd,
18931     winMutexAlloc,
18932     winMutexFree,
18933     winMutexEnter,
18934     winMutexTry,
18935     winMutexLeave,
18936 #ifdef SQLITE_DEBUG
18937     winMutexHeld,
18938     winMutexNotheld
18939 #else
18940     0,
18941     0
18942 #endif
18943   };
18944 
18945   return &sMutex;
18946 }
18947 #endif /* SQLITE_MUTEX_W32 */
18948 
18949 /************** End of mutex_w32.c *******************************************/
18950 /************** Begin file malloc.c ******************************************/
18951 /*
18952 ** 2001 September 15
18953 **
18954 ** The author disclaims copyright to this source code.  In place of
18955 ** a legal notice, here is a blessing:
18956 **
18957 **    May you do good and not evil.
18958 **    May you find forgiveness for yourself and forgive others.
18959 **    May you share freely, never taking more than you give.
18960 **
18961 *************************************************************************
18962 **
18963 ** Memory allocation functions used throughout sqlite.
18964 */
18965 /* #include <stdarg.h> */
18966 
18967 /*
18968 ** Attempt to release up to n bytes of non-essential memory currently
18969 ** held by SQLite. An example of non-essential memory is memory used to
18970 ** cache database pages that are not currently in use.
18971 */
18972 SQLITE_API int sqlite3_release_memory(int n){
18973 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18974   return sqlite3PcacheReleaseMemory(n);
18975 #else
18976   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18977   ** is a no-op returning zero if SQLite is not compiled with
18978   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18979   UNUSED_PARAMETER(n);
18980   return 0;
18981 #endif
18982 }
18983 
18984 /*
18985 ** An instance of the following object records the location of
18986 ** each unused scratch buffer.
18987 */
18988 typedef struct ScratchFreeslot {
18989   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18990 } ScratchFreeslot;
18991 
18992 /*
18993 ** State information local to the memory allocation subsystem.
18994 */
18995 static SQLITE_WSD struct Mem0Global {
18996   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18997 
18998   /*
18999   ** The alarm callback and its arguments.  The mem0.mutex lock will
19000   ** be held while the callback is running.  Recursive calls into
19001   ** the memory subsystem are allowed, but no new callbacks will be
19002   ** issued.
19003   */
19004   sqlite3_int64 alarmThreshold;
19005   void (*alarmCallback)(void*, sqlite3_int64,int);
19006   void *alarmArg;
19007 
19008   /*
19009   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
19010   ** (so that a range test can be used to determine if an allocation
19011   ** being freed came from pScratch) and a pointer to the list of
19012   ** unused scratch allocations.
19013   */
19014   void *pScratchEnd;
19015   ScratchFreeslot *pScratchFree;
19016   u32 nScratchFree;
19017 
19018   /*
19019   ** True if heap is nearly "full" where "full" is defined by the
19020   ** sqlite3_soft_heap_limit() setting.
19021   */
19022   int nearlyFull;
19023 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
19024 
19025 #define mem0 GLOBAL(struct Mem0Global, mem0)
19026 
19027 /*
19028 ** This routine runs when the memory allocator sees that the
19029 ** total memory allocation is about to exceed the soft heap
19030 ** limit.
19031 */
19032 static void softHeapLimitEnforcer(
19033   void *NotUsed, 
19034   sqlite3_int64 NotUsed2,
19035   int allocSize
19036 ){
19037   UNUSED_PARAMETER2(NotUsed, NotUsed2);
19038   sqlite3_release_memory(allocSize);
19039 }
19040 
19041 /*
19042 ** Change the alarm callback
19043 */
19044 static int sqlite3MemoryAlarm(
19045   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19046   void *pArg,
19047   sqlite3_int64 iThreshold
19048 ){
19049   int nUsed;
19050   sqlite3_mutex_enter(mem0.mutex);
19051   mem0.alarmCallback = xCallback;
19052   mem0.alarmArg = pArg;
19053   mem0.alarmThreshold = iThreshold;
19054   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19055   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
19056   sqlite3_mutex_leave(mem0.mutex);
19057   return SQLITE_OK;
19058 }
19059 
19060 #ifndef SQLITE_OMIT_DEPRECATED
19061 /*
19062 ** Deprecated external interface.  Internal/core SQLite code
19063 ** should call sqlite3MemoryAlarm.
19064 */
19065 SQLITE_API int sqlite3_memory_alarm(
19066   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19067   void *pArg,
19068   sqlite3_int64 iThreshold
19069 ){
19070   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
19071 }
19072 #endif
19073 
19074 /*
19075 ** Set the soft heap-size limit for the library. Passing a zero or 
19076 ** negative value indicates no limit.
19077 */
19078 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
19079   sqlite3_int64 priorLimit;
19080   sqlite3_int64 excess;
19081 #ifndef SQLITE_OMIT_AUTOINIT
19082   int rc = sqlite3_initialize();
19083   if( rc ) return -1;
19084 #endif
19085   sqlite3_mutex_enter(mem0.mutex);
19086   priorLimit = mem0.alarmThreshold;
19087   sqlite3_mutex_leave(mem0.mutex);
19088   if( n<0 ) return priorLimit;
19089   if( n>0 ){
19090     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
19091   }else{
19092     sqlite3MemoryAlarm(0, 0, 0);
19093   }
19094   excess = sqlite3_memory_used() - n;
19095   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
19096   return priorLimit;
19097 }
19098 SQLITE_API void sqlite3_soft_heap_limit(int n){
19099   if( n<0 ) n = 0;
19100   sqlite3_soft_heap_limit64(n);
19101 }
19102 
19103 /*
19104 ** Initialize the memory allocation subsystem.
19105 */
19106 SQLITE_PRIVATE int sqlite3MallocInit(void){
19107   if( sqlite3GlobalConfig.m.xMalloc==0 ){
19108     sqlite3MemSetDefault();
19109   }
19110   memset(&mem0, 0, sizeof(mem0));
19111   if( sqlite3GlobalConfig.bCoreMutex ){
19112     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19113   }
19114   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
19115       && sqlite3GlobalConfig.nScratch>0 ){
19116     int i, n, sz;
19117     ScratchFreeslot *pSlot;
19118     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
19119     sqlite3GlobalConfig.szScratch = sz;
19120     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
19121     n = sqlite3GlobalConfig.nScratch;
19122     mem0.pScratchFree = pSlot;
19123     mem0.nScratchFree = n;
19124     for(i=0; i<n-1; i++){
19125       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
19126       pSlot = pSlot->pNext;
19127     }
19128     pSlot->pNext = 0;
19129     mem0.pScratchEnd = (void*)&pSlot[1];
19130   }else{
19131     mem0.pScratchEnd = 0;
19132     sqlite3GlobalConfig.pScratch = 0;
19133     sqlite3GlobalConfig.szScratch = 0;
19134     sqlite3GlobalConfig.nScratch = 0;
19135   }
19136   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
19137       || sqlite3GlobalConfig.nPage<1 ){
19138     sqlite3GlobalConfig.pPage = 0;
19139     sqlite3GlobalConfig.szPage = 0;
19140     sqlite3GlobalConfig.nPage = 0;
19141   }
19142   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
19143 }
19144 
19145 /*
19146 ** Return true if the heap is currently under memory pressure - in other
19147 ** words if the amount of heap used is close to the limit set by
19148 ** sqlite3_soft_heap_limit().
19149 */
19150 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
19151   return mem0.nearlyFull;
19152 }
19153 
19154 /*
19155 ** Deinitialize the memory allocation subsystem.
19156 */
19157 SQLITE_PRIVATE void sqlite3MallocEnd(void){
19158   if( sqlite3GlobalConfig.m.xShutdown ){
19159     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
19160   }
19161   memset(&mem0, 0, sizeof(mem0));
19162 }
19163 
19164 /*
19165 ** Return the amount of memory currently checked out.
19166 */
19167 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
19168   int n, mx;
19169   sqlite3_int64 res;
19170   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
19171   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
19172   return res;
19173 }
19174 
19175 /*
19176 ** Return the maximum amount of memory that has ever been
19177 ** checked out since either the beginning of this process
19178 ** or since the most recent reset.
19179 */
19180 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
19181   int n, mx;
19182   sqlite3_int64 res;
19183   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
19184   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
19185   return res;
19186 }
19187 
19188 /*
19189 ** Trigger the alarm 
19190 */
19191 static void sqlite3MallocAlarm(int nByte){
19192   void (*xCallback)(void*,sqlite3_int64,int);
19193   sqlite3_int64 nowUsed;
19194   void *pArg;
19195   if( mem0.alarmCallback==0 ) return;
19196   xCallback = mem0.alarmCallback;
19197   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19198   pArg = mem0.alarmArg;
19199   mem0.alarmCallback = 0;
19200   sqlite3_mutex_leave(mem0.mutex);
19201   xCallback(pArg, nowUsed, nByte);
19202   sqlite3_mutex_enter(mem0.mutex);
19203   mem0.alarmCallback = xCallback;
19204   mem0.alarmArg = pArg;
19205 }
19206 
19207 /*
19208 ** Do a memory allocation with statistics and alarms.  Assume the
19209 ** lock is already held.
19210 */
19211 static int mallocWithAlarm(int n, void **pp){
19212   int nFull;
19213   void *p;
19214   assert( sqlite3_mutex_held(mem0.mutex) );
19215   nFull = sqlite3GlobalConfig.m.xRoundup(n);
19216   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19217   if( mem0.alarmCallback!=0 ){
19218     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19219     if( nUsed >= mem0.alarmThreshold - nFull ){
19220       mem0.nearlyFull = 1;
19221       sqlite3MallocAlarm(nFull);
19222     }else{
19223       mem0.nearlyFull = 0;
19224     }
19225   }
19226   p = sqlite3GlobalConfig.m.xMalloc(nFull);
19227 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19228   if( p==0 && mem0.alarmCallback ){
19229     sqlite3MallocAlarm(nFull);
19230     p = sqlite3GlobalConfig.m.xMalloc(nFull);
19231   }
19232 #endif
19233   if( p ){
19234     nFull = sqlite3MallocSize(p);
19235     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19236     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19237   }
19238   *pp = p;
19239   return nFull;
19240 }
19241 
19242 /*
19243 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
19244 ** assumes the memory subsystem has already been initialized.
19245 */
19246 SQLITE_PRIVATE void *sqlite3Malloc(int n){
19247   void *p;
19248   if( n<=0               /* IMP: R-65312-04917 */ 
19249    || n>=0x7fffff00
19250   ){
19251     /* A memory allocation of a number of bytes which is near the maximum
19252     ** signed integer value might cause an integer overflow inside of the
19253     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
19254     ** 255 bytes of overhead.  SQLite itself will never use anything near
19255     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
19256     p = 0;
19257   }else if( sqlite3GlobalConfig.bMemstat ){
19258     sqlite3_mutex_enter(mem0.mutex);
19259     mallocWithAlarm(n, &p);
19260     sqlite3_mutex_leave(mem0.mutex);
19261   }else{
19262     p = sqlite3GlobalConfig.m.xMalloc(n);
19263   }
19264   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
19265   return p;
19266 }
19267 
19268 /*
19269 ** This version of the memory allocation is for use by the application.
19270 ** First make sure the memory subsystem is initialized, then do the
19271 ** allocation.
19272 */
19273 SQLITE_API void *sqlite3_malloc(int n){
19274 #ifndef SQLITE_OMIT_AUTOINIT
19275   if( sqlite3_initialize() ) return 0;
19276 #endif
19277   return sqlite3Malloc(n);
19278 }
19279 
19280 /*
19281 ** Each thread may only have a single outstanding allocation from
19282 ** xScratchMalloc().  We verify this constraint in the single-threaded
19283 ** case by setting scratchAllocOut to 1 when an allocation
19284 ** is outstanding clearing it when the allocation is freed.
19285 */
19286 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19287 static int scratchAllocOut = 0;
19288 #endif
19289 
19290 
19291 /*
19292 ** Allocate memory that is to be used and released right away.
19293 ** This routine is similar to alloca() in that it is not intended
19294 ** for situations where the memory might be held long-term.  This
19295 ** routine is intended to get memory to old large transient data
19296 ** structures that would not normally fit on the stack of an
19297 ** embedded processor.
19298 */
19299 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19300   void *p;
19301   assert( n>0 );
19302 
19303   sqlite3_mutex_enter(mem0.mutex);
19304   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19305     p = mem0.pScratchFree;
19306     mem0.pScratchFree = mem0.pScratchFree->pNext;
19307     mem0.nScratchFree--;
19308     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19309     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19310     sqlite3_mutex_leave(mem0.mutex);
19311   }else{
19312     if( sqlite3GlobalConfig.bMemstat ){
19313       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19314       n = mallocWithAlarm(n, &p);
19315       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19316       sqlite3_mutex_leave(mem0.mutex);
19317     }else{
19318       sqlite3_mutex_leave(mem0.mutex);
19319       p = sqlite3GlobalConfig.m.xMalloc(n);
19320     }
19321     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19322   }
19323   assert( sqlite3_mutex_notheld(mem0.mutex) );
19324 
19325 
19326 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19327   /* Verify that no more than two scratch allocations per thread
19328   ** are outstanding at one time.  (This is only checked in the
19329   ** single-threaded case since checking in the multi-threaded case
19330   ** would be much more complicated.) */
19331   assert( scratchAllocOut<=1 );
19332   if( p ) scratchAllocOut++;
19333 #endif
19334 
19335   return p;
19336 }
19337 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19338   if( p ){
19339 
19340 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19341     /* Verify that no more than two scratch allocation per thread
19342     ** is outstanding at one time.  (This is only checked in the
19343     ** single-threaded case since checking in the multi-threaded case
19344     ** would be much more complicated.) */
19345     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19346     scratchAllocOut--;
19347 #endif
19348 
19349     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19350       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19351       ScratchFreeslot *pSlot;
19352       pSlot = (ScratchFreeslot*)p;
19353       sqlite3_mutex_enter(mem0.mutex);
19354       pSlot->pNext = mem0.pScratchFree;
19355       mem0.pScratchFree = pSlot;
19356       mem0.nScratchFree++;
19357       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19358       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19359       sqlite3_mutex_leave(mem0.mutex);
19360     }else{
19361       /* Release memory back to the heap */
19362       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19363       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19364       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19365       if( sqlite3GlobalConfig.bMemstat ){
19366         int iSize = sqlite3MallocSize(p);
19367         sqlite3_mutex_enter(mem0.mutex);
19368         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19369         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19370         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19371         sqlite3GlobalConfig.m.xFree(p);
19372         sqlite3_mutex_leave(mem0.mutex);
19373       }else{
19374         sqlite3GlobalConfig.m.xFree(p);
19375       }
19376     }
19377   }
19378 }
19379 
19380 /*
19381 ** TRUE if p is a lookaside memory allocation from db
19382 */
19383 #ifndef SQLITE_OMIT_LOOKASIDE
19384 static int isLookaside(sqlite3 *db, void *p){
19385   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19386 }
19387 #else
19388 #define isLookaside(A,B) 0
19389 #endif
19390 
19391 /*
19392 ** Return the size of a memory allocation previously obtained from
19393 ** sqlite3Malloc() or sqlite3_malloc().
19394 */
19395 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19396   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19397   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19398   return sqlite3GlobalConfig.m.xSize(p);
19399 }
19400 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19401   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19402   if( db && isLookaside(db, p) ){
19403     return db->lookaside.sz;
19404   }else{
19405     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19406     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19407     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19408     return sqlite3GlobalConfig.m.xSize(p);
19409   }
19410 }
19411 
19412 /*
19413 ** Free memory previously obtained from sqlite3Malloc().
19414 */
19415 SQLITE_API void sqlite3_free(void *p){
19416   if( p==0 ) return;  /* IMP: R-49053-54554 */
19417   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19418   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19419   if( sqlite3GlobalConfig.bMemstat ){
19420     sqlite3_mutex_enter(mem0.mutex);
19421     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19422     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19423     sqlite3GlobalConfig.m.xFree(p);
19424     sqlite3_mutex_leave(mem0.mutex);
19425   }else{
19426     sqlite3GlobalConfig.m.xFree(p);
19427   }
19428 }
19429 
19430 /*
19431 ** Free memory that might be associated with a particular database
19432 ** connection.
19433 */
19434 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19435   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19436   if( p==0 ) return;
19437   if( db ){
19438     if( db->pnBytesFreed ){
19439       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19440       return;
19441     }
19442     if( isLookaside(db, p) ){
19443       LookasideSlot *pBuf = (LookasideSlot*)p;
19444 #if SQLITE_DEBUG
19445       /* Trash all content in the buffer being freed */
19446       memset(p, 0xaa, db->lookaside.sz);
19447 #endif
19448       pBuf->pNext = db->lookaside.pFree;
19449       db->lookaside.pFree = pBuf;
19450       db->lookaside.nOut--;
19451       return;
19452     }
19453   }
19454   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19455   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19456   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19457   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19458   sqlite3_free(p);
19459 }
19460 
19461 /*
19462 ** Change the size of an existing memory allocation
19463 */
19464 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19465   int nOld, nNew, nDiff;
19466   void *pNew;
19467   if( pOld==0 ){
19468     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19469   }
19470   if( nBytes<=0 ){
19471     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19472     return 0;
19473   }
19474   if( nBytes>=0x7fffff00 ){
19475     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19476     return 0;
19477   }
19478   nOld = sqlite3MallocSize(pOld);
19479   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19480   ** argument to xRealloc is always a value returned by a prior call to
19481   ** xRoundup. */
19482   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19483   if( nOld==nNew ){
19484     pNew = pOld;
19485   }else if( sqlite3GlobalConfig.bMemstat ){
19486     sqlite3_mutex_enter(mem0.mutex);
19487     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19488     nDiff = nNew - nOld;
19489     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
19490           mem0.alarmThreshold-nDiff ){
19491       sqlite3MallocAlarm(nDiff);
19492     }
19493     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19494     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19495     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19496     if( pNew==0 && mem0.alarmCallback ){
19497       sqlite3MallocAlarm(nBytes);
19498       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19499     }
19500     if( pNew ){
19501       nNew = sqlite3MallocSize(pNew);
19502       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19503     }
19504     sqlite3_mutex_leave(mem0.mutex);
19505   }else{
19506     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19507   }
19508   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19509   return pNew;
19510 }
19511 
19512 /*
19513 ** The public interface to sqlite3Realloc.  Make sure that the memory
19514 ** subsystem is initialized prior to invoking sqliteRealloc.
19515 */
19516 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19517 #ifndef SQLITE_OMIT_AUTOINIT
19518   if( sqlite3_initialize() ) return 0;
19519 #endif
19520   return sqlite3Realloc(pOld, n);
19521 }
19522 
19523 
19524 /*
19525 ** Allocate and zero memory.
19526 */ 
19527 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19528   void *p = sqlite3Malloc(n);
19529   if( p ){
19530     memset(p, 0, n);
19531   }
19532   return p;
19533 }
19534 
19535 /*
19536 ** Allocate and zero memory.  If the allocation fails, make
19537 ** the mallocFailed flag in the connection pointer.
19538 */
19539 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19540   void *p = sqlite3DbMallocRaw(db, n);
19541   if( p ){
19542     memset(p, 0, n);
19543   }
19544   return p;
19545 }
19546 
19547 /*
19548 ** Allocate and zero memory.  If the allocation fails, make
19549 ** the mallocFailed flag in the connection pointer.
19550 **
19551 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19552 ** failure on the same database connection) then always return 0.
19553 ** Hence for a particular database connection, once malloc starts
19554 ** failing, it fails consistently until mallocFailed is reset.
19555 ** This is an important assumption.  There are many places in the
19556 ** code that do things like this:
19557 **
19558 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19559 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19560 **         if( b ) a[10] = 9;
19561 **
19562 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19563 ** that all prior mallocs (ex: "a") worked too.
19564 */
19565 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19566   void *p;
19567   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19568   assert( db==0 || db->pnBytesFreed==0 );
19569 #ifndef SQLITE_OMIT_LOOKASIDE
19570   if( db ){
19571     LookasideSlot *pBuf;
19572     if( db->mallocFailed ){
19573       return 0;
19574     }
19575     if( db->lookaside.bEnabled ){
19576       if( n>db->lookaside.sz ){
19577         db->lookaside.anStat[1]++;
19578       }else if( (pBuf = db->lookaside.pFree)==0 ){
19579         db->lookaside.anStat[2]++;
19580       }else{
19581         db->lookaside.pFree = pBuf->pNext;
19582         db->lookaside.nOut++;
19583         db->lookaside.anStat[0]++;
19584         if( db->lookaside.nOut>db->lookaside.mxOut ){
19585           db->lookaside.mxOut = db->lookaside.nOut;
19586         }
19587         return (void*)pBuf;
19588       }
19589     }
19590   }
19591 #else
19592   if( db && db->mallocFailed ){
19593     return 0;
19594   }
19595 #endif
19596   p = sqlite3Malloc(n);
19597   if( !p && db ){
19598     db->mallocFailed = 1;
19599   }
19600   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19601          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19602   return p;
19603 }
19604 
19605 /*
19606 ** Resize the block of memory pointed to by p to n bytes. If the
19607 ** resize fails, set the mallocFailed flag in the connection object.
19608 */
19609 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19610   void *pNew = 0;
19611   assert( db!=0 );
19612   assert( sqlite3_mutex_held(db->mutex) );
19613   if( db->mallocFailed==0 ){
19614     if( p==0 ){
19615       return sqlite3DbMallocRaw(db, n);
19616     }
19617     if( isLookaside(db, p) ){
19618       if( n<=db->lookaside.sz ){
19619         return p;
19620       }
19621       pNew = sqlite3DbMallocRaw(db, n);
19622       if( pNew ){
19623         memcpy(pNew, p, db->lookaside.sz);
19624         sqlite3DbFree(db, p);
19625       }
19626     }else{
19627       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19628       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19629       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19630       pNew = sqlite3_realloc(p, n);
19631       if( !pNew ){
19632         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19633         db->mallocFailed = 1;
19634       }
19635       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19636             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19637     }
19638   }
19639   return pNew;
19640 }
19641 
19642 /*
19643 ** Attempt to reallocate p.  If the reallocation fails, then free p
19644 ** and set the mallocFailed flag in the database connection.
19645 */
19646 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19647   void *pNew;
19648   pNew = sqlite3DbRealloc(db, p, n);
19649   if( !pNew ){
19650     sqlite3DbFree(db, p);
19651   }
19652   return pNew;
19653 }
19654 
19655 /*
19656 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19657 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19658 ** is because when memory debugging is turned on, these two functions are 
19659 ** called via macros that record the current file and line number in the
19660 ** ThreadData structure.
19661 */
19662 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19663   char *zNew;
19664   size_t n;
19665   if( z==0 ){
19666     return 0;
19667   }
19668   n = sqlite3Strlen30(z) + 1;
19669   assert( (n&0x7fffffff)==n );
19670   zNew = sqlite3DbMallocRaw(db, (int)n);
19671   if( zNew ){
19672     memcpy(zNew, z, n);
19673   }
19674   return zNew;
19675 }
19676 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19677   char *zNew;
19678   if( z==0 ){
19679     return 0;
19680   }
19681   assert( (n&0x7fffffff)==n );
19682   zNew = sqlite3DbMallocRaw(db, n+1);
19683   if( zNew ){
19684     memcpy(zNew, z, n);
19685     zNew[n] = 0;
19686   }
19687   return zNew;
19688 }
19689 
19690 /*
19691 ** Create a string from the zFromat argument and the va_list that follows.
19692 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19693 ** point to that string.
19694 */
19695 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19696   va_list ap;
19697   char *z;
19698 
19699   va_start(ap, zFormat);
19700   z = sqlite3VMPrintf(db, zFormat, ap);
19701   va_end(ap);
19702   sqlite3DbFree(db, *pz);
19703   *pz = z;
19704 }
19705 
19706 
19707 /*
19708 ** This function must be called before exiting any API function (i.e. 
19709 ** returning control to the user) that has called sqlite3_malloc or
19710 ** sqlite3_realloc.
19711 **
19712 ** The returned value is normally a copy of the second argument to this
19713 ** function. However, if a malloc() failure has occurred since the previous
19714 ** invocation SQLITE_NOMEM is returned instead. 
19715 **
19716 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19717 ** then the connection error-code (the value returned by sqlite3_errcode())
19718 ** is set to SQLITE_NOMEM.
19719 */
19720 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19721   /* If the db handle is not NULL, then we must hold the connection handle
19722   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19723   ** is unsafe, as is the call to sqlite3Error().
19724   */
19725   assert( !db || sqlite3_mutex_held(db->mutex) );
19726   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19727     sqlite3Error(db, SQLITE_NOMEM, 0);
19728     db->mallocFailed = 0;
19729     rc = SQLITE_NOMEM;
19730   }
19731   return rc & (db ? db->errMask : 0xff);
19732 }
19733 
19734 /************** End of malloc.c **********************************************/
19735 /************** Begin file printf.c ******************************************/
19736 /*
19737 ** The "printf" code that follows dates from the 1980's.  It is in
19738 ** the public domain.  The original comments are included here for
19739 ** completeness.  They are very out-of-date but might be useful as
19740 ** an historical reference.  Most of the "enhancements" have been backed
19741 ** out so that the functionality is now the same as standard printf().
19742 **
19743 **************************************************************************
19744 **
19745 ** This file contains code for a set of "printf"-like routines.  These
19746 ** routines format strings much like the printf() from the standard C
19747 ** library, though the implementation here has enhancements to support
19748 ** SQLlite.
19749 */
19750 
19751 /*
19752 ** Conversion types fall into various categories as defined by the
19753 ** following enumeration.
19754 */
19755 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19756 #define etFLOAT       2 /* Floating point.  %f */
19757 #define etEXP         3 /* Exponentional notation. %e and %E */
19758 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19759 #define etSIZE        5 /* Return number of characters processed so far. %n */
19760 #define etSTRING      6 /* Strings. %s */
19761 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19762 #define etPERCENT     8 /* Percent symbol. %% */
19763 #define etCHARX       9 /* Characters. %c */
19764 /* The rest are extensions, not normally found in printf() */
19765 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19766 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19767                           NULL pointers replaced by SQL NULL.  %Q */
19768 #define etTOKEN      12 /* a pointer to a Token structure */
19769 #define etSRCLIST    13 /* a pointer to a SrcList */
19770 #define etPOINTER    14 /* The %p conversion */
19771 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19772 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19773 
19774 #define etINVALID     0 /* Any unrecognized conversion type */
19775 
19776 
19777 /*
19778 ** An "etByte" is an 8-bit unsigned value.
19779 */
19780 typedef unsigned char etByte;
19781 
19782 /*
19783 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19784 ** by an instance of the following structure
19785 */
19786 typedef struct et_info {   /* Information about each format field */
19787   char fmttype;            /* The format field code letter */
19788   etByte base;             /* The base for radix conversion */
19789   etByte flags;            /* One or more of FLAG_ constants below */
19790   etByte type;             /* Conversion paradigm */
19791   etByte charset;          /* Offset into aDigits[] of the digits string */
19792   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19793 } et_info;
19794 
19795 /*
19796 ** Allowed values for et_info.flags
19797 */
19798 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19799 #define FLAG_INTERN  2     /* True if for internal use only */
19800 #define FLAG_STRING  4     /* Allow infinity precision */
19801 
19802 
19803 /*
19804 ** The following table is searched linearly, so it is good to put the
19805 ** most frequently used conversion types first.
19806 */
19807 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19808 static const char aPrefix[] = "-x0\000X0";
19809 static const et_info fmtinfo[] = {
19810   {  'd', 10, 1, etRADIX,      0,  0 },
19811   {  's',  0, 4, etSTRING,     0,  0 },
19812   {  'g',  0, 1, etGENERIC,    30, 0 },
19813   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19814   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19815   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19816   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19817   {  'c',  0, 0, etCHARX,      0,  0 },
19818   {  'o',  8, 0, etRADIX,      0,  2 },
19819   {  'u', 10, 0, etRADIX,      0,  0 },
19820   {  'x', 16, 0, etRADIX,      16, 1 },
19821   {  'X', 16, 0, etRADIX,      0,  4 },
19822 #ifndef SQLITE_OMIT_FLOATING_POINT
19823   {  'f',  0, 1, etFLOAT,      0,  0 },
19824   {  'e',  0, 1, etEXP,        30, 0 },
19825   {  'E',  0, 1, etEXP,        14, 0 },
19826   {  'G',  0, 1, etGENERIC,    14, 0 },
19827 #endif
19828   {  'i', 10, 1, etRADIX,      0,  0 },
19829   {  'n',  0, 0, etSIZE,       0,  0 },
19830   {  '%',  0, 0, etPERCENT,    0,  0 },
19831   {  'p', 16, 0, etPOINTER,    0,  1 },
19832 
19833 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19834 ** use only */
19835   {  'T',  0, 2, etTOKEN,      0,  0 },
19836   {  'S',  0, 2, etSRCLIST,    0,  0 },
19837   {  'r', 10, 3, etORDINAL,    0,  0 },
19838 };
19839 
19840 /*
19841 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19842 ** conversions will work.
19843 */
19844 #ifndef SQLITE_OMIT_FLOATING_POINT
19845 /*
19846 ** "*val" is a double such that 0.1 <= *val < 10.0
19847 ** Return the ascii code for the leading digit of *val, then
19848 ** multiply "*val" by 10.0 to renormalize.
19849 **
19850 ** Example:
19851 **     input:     *val = 3.14159
19852 **     output:    *val = 1.4159    function return = '3'
19853 **
19854 ** The counter *cnt is incremented each time.  After counter exceeds
19855 ** 16 (the number of significant digits in a 64-bit float) '0' is
19856 ** always returned.
19857 */
19858 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19859   int digit;
19860   LONGDOUBLE_TYPE d;
19861   if( (*cnt)<=0 ) return '0';
19862   (*cnt)--;
19863   digit = (int)*val;
19864   d = digit;
19865   digit += '0';
19866   *val = (*val - d)*10.0;
19867   return (char)digit;
19868 }
19869 #endif /* SQLITE_OMIT_FLOATING_POINT */
19870 
19871 /*
19872 ** Append N space characters to the given string buffer.
19873 */
19874 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19875   static const char zSpaces[] = "                             ";
19876   while( N>=(int)sizeof(zSpaces)-1 ){
19877     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19878     N -= sizeof(zSpaces)-1;
19879   }
19880   if( N>0 ){
19881     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19882   }
19883 }
19884 
19885 /*
19886 ** On machines with a small stack size, you can redefine the
19887 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19888 */
19889 #ifndef SQLITE_PRINT_BUF_SIZE
19890 # define SQLITE_PRINT_BUF_SIZE 70
19891 #endif
19892 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19893 
19894 /*
19895 ** Render a string given by "fmt" into the StrAccum object.
19896 */
19897 SQLITE_PRIVATE void sqlite3VXPrintf(
19898   StrAccum *pAccum,                  /* Accumulate results here */
19899   int useExtended,                   /* Allow extended %-conversions */
19900   const char *fmt,                   /* Format string */
19901   va_list ap                         /* arguments */
19902 ){
19903   int c;                     /* Next character in the format string */
19904   char *bufpt;               /* Pointer to the conversion buffer */
19905   int precision;             /* Precision of the current field */
19906   int length;                /* Length of the field */
19907   int idx;                   /* A general purpose loop counter */
19908   int width;                 /* Width of the current field */
19909   etByte flag_leftjustify;   /* True if "-" flag is present */
19910   etByte flag_plussign;      /* True if "+" flag is present */
19911   etByte flag_blanksign;     /* True if " " flag is present */
19912   etByte flag_alternateform; /* True if "#" flag is present */
19913   etByte flag_altform2;      /* True if "!" flag is present */
19914   etByte flag_zeropad;       /* True if field width constant starts with zero */
19915   etByte flag_long;          /* True if "l" flag is present */
19916   etByte flag_longlong;      /* True if the "ll" flag is present */
19917   etByte done;               /* Loop termination flag */
19918   etByte xtype = 0;          /* Conversion paradigm */
19919   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19920   sqlite_uint64 longvalue;   /* Value for integer types */
19921   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19922   const et_info *infop;      /* Pointer to the appropriate info structure */
19923   char *zOut;                /* Rendering buffer */
19924   int nOut;                  /* Size of the rendering buffer */
19925   char *zExtra;              /* Malloced memory used by some conversion */
19926 #ifndef SQLITE_OMIT_FLOATING_POINT
19927   int  exp, e2;              /* exponent of real numbers */
19928   int nsd;                   /* Number of significant digits returned */
19929   double rounder;            /* Used for rounding floating point values */
19930   etByte flag_dp;            /* True if decimal point should be shown */
19931   etByte flag_rtz;           /* True if trailing zeros should be removed */
19932 #endif
19933   char buf[etBUFSIZE];       /* Conversion buffer */
19934 
19935   bufpt = 0;
19936   for(; (c=(*fmt))!=0; ++fmt){
19937     if( c!='%' ){
19938       int amt;
19939       bufpt = (char *)fmt;
19940       amt = 1;
19941       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19942       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19943       if( c==0 ) break;
19944     }
19945     if( (c=(*++fmt))==0 ){
19946       sqlite3StrAccumAppend(pAccum, "%", 1);
19947       break;
19948     }
19949     /* Find out what flags are present */
19950     flag_leftjustify = flag_plussign = flag_blanksign = 
19951      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19952     done = 0;
19953     do{
19954       switch( c ){
19955         case '-':   flag_leftjustify = 1;     break;
19956         case '+':   flag_plussign = 1;        break;
19957         case ' ':   flag_blanksign = 1;       break;
19958         case '#':   flag_alternateform = 1;   break;
19959         case '!':   flag_altform2 = 1;        break;
19960         case '0':   flag_zeropad = 1;         break;
19961         default:    done = 1;                 break;
19962       }
19963     }while( !done && (c=(*++fmt))!=0 );
19964     /* Get the field width */
19965     width = 0;
19966     if( c=='*' ){
19967       width = va_arg(ap,int);
19968       if( width<0 ){
19969         flag_leftjustify = 1;
19970         width = -width;
19971       }
19972       c = *++fmt;
19973     }else{
19974       while( c>='0' && c<='9' ){
19975         width = width*10 + c - '0';
19976         c = *++fmt;
19977       }
19978     }
19979     /* Get the precision */
19980     if( c=='.' ){
19981       precision = 0;
19982       c = *++fmt;
19983       if( c=='*' ){
19984         precision = va_arg(ap,int);
19985         if( precision<0 ) precision = -precision;
19986         c = *++fmt;
19987       }else{
19988         while( c>='0' && c<='9' ){
19989           precision = precision*10 + c - '0';
19990           c = *++fmt;
19991         }
19992       }
19993     }else{
19994       precision = -1;
19995     }
19996     /* Get the conversion type modifier */
19997     if( c=='l' ){
19998       flag_long = 1;
19999       c = *++fmt;
20000       if( c=='l' ){
20001         flag_longlong = 1;
20002         c = *++fmt;
20003       }else{
20004         flag_longlong = 0;
20005       }
20006     }else{
20007       flag_long = flag_longlong = 0;
20008     }
20009     /* Fetch the info entry for the field */
20010     infop = &fmtinfo[0];
20011     xtype = etINVALID;
20012     for(idx=0; idx<ArraySize(fmtinfo); idx++){
20013       if( c==fmtinfo[idx].fmttype ){
20014         infop = &fmtinfo[idx];
20015         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
20016           xtype = infop->type;
20017         }else{
20018           return;
20019         }
20020         break;
20021       }
20022     }
20023     zExtra = 0;
20024 
20025     /*
20026     ** At this point, variables are initialized as follows:
20027     **
20028     **   flag_alternateform          TRUE if a '#' is present.
20029     **   flag_altform2               TRUE if a '!' is present.
20030     **   flag_plussign               TRUE if a '+' is present.
20031     **   flag_leftjustify            TRUE if a '-' is present or if the
20032     **                               field width was negative.
20033     **   flag_zeropad                TRUE if the width began with 0.
20034     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
20035     **                               the conversion character.
20036     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
20037     **                               the conversion character.
20038     **   flag_blanksign              TRUE if a ' ' is present.
20039     **   width                       The specified field width.  This is
20040     **                               always non-negative.  Zero is the default.
20041     **   precision                   The specified precision.  The default
20042     **                               is -1.
20043     **   xtype                       The class of the conversion.
20044     **   infop                       Pointer to the appropriate info struct.
20045     */
20046     switch( xtype ){
20047       case etPOINTER:
20048         flag_longlong = sizeof(char*)==sizeof(i64);
20049         flag_long = sizeof(char*)==sizeof(long int);
20050         /* Fall through into the next case */
20051       case etORDINAL:
20052       case etRADIX:
20053         if( infop->flags & FLAG_SIGNED ){
20054           i64 v;
20055           if( flag_longlong ){
20056             v = va_arg(ap,i64);
20057           }else if( flag_long ){
20058             v = va_arg(ap,long int);
20059           }else{
20060             v = va_arg(ap,int);
20061           }
20062           if( v<0 ){
20063             if( v==SMALLEST_INT64 ){
20064               longvalue = ((u64)1)<<63;
20065             }else{
20066               longvalue = -v;
20067             }
20068             prefix = '-';
20069           }else{
20070             longvalue = v;
20071             if( flag_plussign )        prefix = '+';
20072             else if( flag_blanksign )  prefix = ' ';
20073             else                       prefix = 0;
20074           }
20075         }else{
20076           if( flag_longlong ){
20077             longvalue = va_arg(ap,u64);
20078           }else if( flag_long ){
20079             longvalue = va_arg(ap,unsigned long int);
20080           }else{
20081             longvalue = va_arg(ap,unsigned int);
20082           }
20083           prefix = 0;
20084         }
20085         if( longvalue==0 ) flag_alternateform = 0;
20086         if( flag_zeropad && precision<width-(prefix!=0) ){
20087           precision = width-(prefix!=0);
20088         }
20089         if( precision<etBUFSIZE-10 ){
20090           nOut = etBUFSIZE;
20091           zOut = buf;
20092         }else{
20093           nOut = precision + 10;
20094           zOut = zExtra = sqlite3Malloc( nOut );
20095           if( zOut==0 ){
20096             pAccum->accError = STRACCUM_NOMEM;
20097             return;
20098           }
20099         }
20100         bufpt = &zOut[nOut-1];
20101         if( xtype==etORDINAL ){
20102           static const char zOrd[] = "thstndrd";
20103           int x = (int)(longvalue % 10);
20104           if( x>=4 || (longvalue/10)%10==1 ){
20105             x = 0;
20106           }
20107           *(--bufpt) = zOrd[x*2+1];
20108           *(--bufpt) = zOrd[x*2];
20109         }
20110         {
20111           register const char *cset;      /* Use registers for speed */
20112           register int base;
20113           cset = &aDigits[infop->charset];
20114           base = infop->base;
20115           do{                                           /* Convert to ascii */
20116             *(--bufpt) = cset[longvalue%base];
20117             longvalue = longvalue/base;
20118           }while( longvalue>0 );
20119         }
20120         length = (int)(&zOut[nOut-1]-bufpt);
20121         for(idx=precision-length; idx>0; idx--){
20122           *(--bufpt) = '0';                             /* Zero pad */
20123         }
20124         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
20125         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
20126           const char *pre;
20127           char x;
20128           pre = &aPrefix[infop->prefix];
20129           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
20130         }
20131         length = (int)(&zOut[nOut-1]-bufpt);
20132         break;
20133       case etFLOAT:
20134       case etEXP:
20135       case etGENERIC:
20136         realvalue = va_arg(ap,double);
20137 #ifdef SQLITE_OMIT_FLOATING_POINT
20138         length = 0;
20139 #else
20140         if( precision<0 ) precision = 6;         /* Set default precision */
20141         if( realvalue<0.0 ){
20142           realvalue = -realvalue;
20143           prefix = '-';
20144         }else{
20145           if( flag_plussign )          prefix = '+';
20146           else if( flag_blanksign )    prefix = ' ';
20147           else                         prefix = 0;
20148         }
20149         if( xtype==etGENERIC && precision>0 ) precision--;
20150         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
20151         if( xtype==etFLOAT ) realvalue += rounder;
20152         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
20153         exp = 0;
20154         if( sqlite3IsNaN((double)realvalue) ){
20155           bufpt = "NaN";
20156           length = 3;
20157           break;
20158         }
20159         if( realvalue>0.0 ){
20160           LONGDOUBLE_TYPE scale = 1.0;
20161           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
20162           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
20163           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
20164           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
20165           realvalue /= scale;
20166           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
20167           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
20168           if( exp>350 ){
20169             if( prefix=='-' ){
20170               bufpt = "-Inf";
20171             }else if( prefix=='+' ){
20172               bufpt = "+Inf";
20173             }else{
20174               bufpt = "Inf";
20175             }
20176             length = sqlite3Strlen30(bufpt);
20177             break;
20178           }
20179         }
20180         bufpt = buf;
20181         /*
20182         ** If the field type is etGENERIC, then convert to either etEXP
20183         ** or etFLOAT, as appropriate.
20184         */
20185         if( xtype!=etFLOAT ){
20186           realvalue += rounder;
20187           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
20188         }
20189         if( xtype==etGENERIC ){
20190           flag_rtz = !flag_alternateform;
20191           if( exp<-4 || exp>precision ){
20192             xtype = etEXP;
20193           }else{
20194             precision = precision - exp;
20195             xtype = etFLOAT;
20196           }
20197         }else{
20198           flag_rtz = flag_altform2;
20199         }
20200         if( xtype==etEXP ){
20201           e2 = 0;
20202         }else{
20203           e2 = exp;
20204         }
20205         if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
20206           bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
20207           if( bufpt==0 ){
20208             pAccum->accError = STRACCUM_NOMEM;
20209             return;
20210           }
20211         }
20212         zOut = bufpt;
20213         nsd = 16 + flag_altform2*10;
20214         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20215         /* The sign in front of the number */
20216         if( prefix ){
20217           *(bufpt++) = prefix;
20218         }
20219         /* Digits prior to the decimal point */
20220         if( e2<0 ){
20221           *(bufpt++) = '0';
20222         }else{
20223           for(; e2>=0; e2--){
20224             *(bufpt++) = et_getdigit(&realvalue,&nsd);
20225           }
20226         }
20227         /* The decimal point */
20228         if( flag_dp ){
20229           *(bufpt++) = '.';
20230         }
20231         /* "0" digits after the decimal point but before the first
20232         ** significant digit of the number */
20233         for(e2++; e2<0; precision--, e2++){
20234           assert( precision>0 );
20235           *(bufpt++) = '0';
20236         }
20237         /* Significant digits after the decimal point */
20238         while( (precision--)>0 ){
20239           *(bufpt++) = et_getdigit(&realvalue,&nsd);
20240         }
20241         /* Remove trailing zeros and the "." if no digits follow the "." */
20242         if( flag_rtz && flag_dp ){
20243           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20244           assert( bufpt>zOut );
20245           if( bufpt[-1]=='.' ){
20246             if( flag_altform2 ){
20247               *(bufpt++) = '0';
20248             }else{
20249               *(--bufpt) = 0;
20250             }
20251           }
20252         }
20253         /* Add the "eNNN" suffix */
20254         if( xtype==etEXP ){
20255           *(bufpt++) = aDigits[infop->charset];
20256           if( exp<0 ){
20257             *(bufpt++) = '-'; exp = -exp;
20258           }else{
20259             *(bufpt++) = '+';
20260           }
20261           if( exp>=100 ){
20262             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
20263             exp %= 100;
20264           }
20265           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
20266           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
20267         }
20268         *bufpt = 0;
20269 
20270         /* The converted number is in buf[] and zero terminated. Output it.
20271         ** Note that the number is in the usual order, not reversed as with
20272         ** integer conversions. */
20273         length = (int)(bufpt-zOut);
20274         bufpt = zOut;
20275 
20276         /* Special case:  Add leading zeros if the flag_zeropad flag is
20277         ** set and we are not left justified */
20278         if( flag_zeropad && !flag_leftjustify && length < width){
20279           int i;
20280           int nPad = width - length;
20281           for(i=width; i>=nPad; i--){
20282             bufpt[i] = bufpt[i-nPad];
20283           }
20284           i = prefix!=0;
20285           while( nPad-- ) bufpt[i++] = '0';
20286           length = width;
20287         }
20288 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20289         break;
20290       case etSIZE:
20291         *(va_arg(ap,int*)) = pAccum->nChar;
20292         length = width = 0;
20293         break;
20294       case etPERCENT:
20295         buf[0] = '%';
20296         bufpt = buf;
20297         length = 1;
20298         break;
20299       case etCHARX:
20300         c = va_arg(ap,int);
20301         buf[0] = (char)c;
20302         if( precision>=0 ){
20303           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20304           length = precision;
20305         }else{
20306           length =1;
20307         }
20308         bufpt = buf;
20309         break;
20310       case etSTRING:
20311       case etDYNSTRING:
20312         bufpt = va_arg(ap,char*);
20313         if( bufpt==0 ){
20314           bufpt = "";
20315         }else if( xtype==etDYNSTRING ){
20316           zExtra = bufpt;
20317         }
20318         if( precision>=0 ){
20319           for(length=0; length<precision && bufpt[length]; length++){}
20320         }else{
20321           length = sqlite3Strlen30(bufpt);
20322         }
20323         break;
20324       case etSQLESCAPE:
20325       case etSQLESCAPE2:
20326       case etSQLESCAPE3: {
20327         int i, j, k, n, isnull;
20328         int needQuote;
20329         char ch;
20330         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
20331         char *escarg = va_arg(ap,char*);
20332         isnull = escarg==0;
20333         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20334         k = precision;
20335         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20336           if( ch==q )  n++;
20337         }
20338         needQuote = !isnull && xtype==etSQLESCAPE2;
20339         n += i + 1 + needQuote*2;
20340         if( n>etBUFSIZE ){
20341           bufpt = zExtra = sqlite3Malloc( n );
20342           if( bufpt==0 ){
20343             pAccum->accError = STRACCUM_NOMEM;
20344             return;
20345           }
20346         }else{
20347           bufpt = buf;
20348         }
20349         j = 0;
20350         if( needQuote ) bufpt[j++] = q;
20351         k = i;
20352         for(i=0; i<k; i++){
20353           bufpt[j++] = ch = escarg[i];
20354           if( ch==q ) bufpt[j++] = ch;
20355         }
20356         if( needQuote ) bufpt[j++] = q;
20357         bufpt[j] = 0;
20358         length = j;
20359         /* The precision in %q and %Q means how many input characters to
20360         ** consume, not the length of the output...
20361         ** if( precision>=0 && precision<length ) length = precision; */
20362         break;
20363       }
20364       case etTOKEN: {
20365         Token *pToken = va_arg(ap, Token*);
20366         if( pToken ){
20367           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20368         }
20369         length = width = 0;
20370         break;
20371       }
20372       case etSRCLIST: {
20373         SrcList *pSrc = va_arg(ap, SrcList*);
20374         int k = va_arg(ap, int);
20375         struct SrcList_item *pItem = &pSrc->a[k];
20376         assert( k>=0 && k<pSrc->nSrc );
20377         if( pItem->zDatabase ){
20378           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20379           sqlite3StrAccumAppend(pAccum, ".", 1);
20380         }
20381         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20382         length = width = 0;
20383         break;
20384       }
20385       default: {
20386         assert( xtype==etINVALID );
20387         return;
20388       }
20389     }/* End switch over the format type */
20390     /*
20391     ** The text of the conversion is pointed to by "bufpt" and is
20392     ** "length" characters long.  The field width is "width".  Do
20393     ** the output.
20394     */
20395     if( !flag_leftjustify ){
20396       register int nspace;
20397       nspace = width-length;
20398       if( nspace>0 ){
20399         sqlite3AppendSpace(pAccum, nspace);
20400       }
20401     }
20402     if( length>0 ){
20403       sqlite3StrAccumAppend(pAccum, bufpt, length);
20404     }
20405     if( flag_leftjustify ){
20406       register int nspace;
20407       nspace = width-length;
20408       if( nspace>0 ){
20409         sqlite3AppendSpace(pAccum, nspace);
20410       }
20411     }
20412     sqlite3_free(zExtra);
20413   }/* End for loop over the format string */
20414 } /* End of function */
20415 
20416 /*
20417 ** Append N bytes of text from z to the StrAccum object.
20418 */
20419 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20420   assert( z!=0 || N==0 );
20421   if( p->accError ){
20422     testcase(p->accError==STRACCUM_TOOBIG);
20423     testcase(p->accError==STRACCUM_NOMEM);
20424     return;
20425   }
20426   assert( p->zText!=0 || p->nChar==0 );
20427   if( N<=0 ){
20428     if( N==0 || z[0]==0 ) return;
20429     N = sqlite3Strlen30(z);
20430   }
20431   if( p->nChar+N >= p->nAlloc ){
20432     char *zNew;
20433     if( !p->useMalloc ){
20434       p->accError = STRACCUM_TOOBIG;
20435       N = p->nAlloc - p->nChar - 1;
20436       if( N<=0 ){
20437         return;
20438       }
20439     }else{
20440       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20441       i64 szNew = p->nChar;
20442       szNew += N + 1;
20443       if( szNew > p->mxAlloc ){
20444         sqlite3StrAccumReset(p);
20445         p->accError = STRACCUM_TOOBIG;
20446         return;
20447       }else{
20448         p->nAlloc = (int)szNew;
20449       }
20450       if( p->useMalloc==1 ){
20451         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20452       }else{
20453         zNew = sqlite3_realloc(zOld, p->nAlloc);
20454       }
20455       if( zNew ){
20456         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20457         p->zText = zNew;
20458       }else{
20459         p->accError = STRACCUM_NOMEM;
20460         sqlite3StrAccumReset(p);
20461         return;
20462       }
20463     }
20464   }
20465   assert( p->zText );
20466   memcpy(&p->zText[p->nChar], z, N);
20467   p->nChar += N;
20468 }
20469 
20470 /*
20471 ** Finish off a string by making sure it is zero-terminated.
20472 ** Return a pointer to the resulting string.  Return a NULL
20473 ** pointer if any kind of error was encountered.
20474 */
20475 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20476   if( p->zText ){
20477     p->zText[p->nChar] = 0;
20478     if( p->useMalloc && p->zText==p->zBase ){
20479       if( p->useMalloc==1 ){
20480         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20481       }else{
20482         p->zText = sqlite3_malloc(p->nChar+1);
20483       }
20484       if( p->zText ){
20485         memcpy(p->zText, p->zBase, p->nChar+1);
20486       }else{
20487         p->accError = STRACCUM_NOMEM;
20488       }
20489     }
20490   }
20491   return p->zText;
20492 }
20493 
20494 /*
20495 ** Reset an StrAccum string.  Reclaim all malloced memory.
20496 */
20497 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20498   if( p->zText!=p->zBase ){
20499     if( p->useMalloc==1 ){
20500       sqlite3DbFree(p->db, p->zText);
20501     }else{
20502       sqlite3_free(p->zText);
20503     }
20504   }
20505   p->zText = 0;
20506 }
20507 
20508 /*
20509 ** Initialize a string accumulator
20510 */
20511 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20512   p->zText = p->zBase = zBase;
20513   p->db = 0;
20514   p->nChar = 0;
20515   p->nAlloc = n;
20516   p->mxAlloc = mx;
20517   p->useMalloc = 1;
20518   p->accError = 0;
20519 }
20520 
20521 /*
20522 ** Print into memory obtained from sqliteMalloc().  Use the internal
20523 ** %-conversion extensions.
20524 */
20525 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20526   char *z;
20527   char zBase[SQLITE_PRINT_BUF_SIZE];
20528   StrAccum acc;
20529   assert( db!=0 );
20530   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20531                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20532   acc.db = db;
20533   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20534   z = sqlite3StrAccumFinish(&acc);
20535   if( acc.accError==STRACCUM_NOMEM ){
20536     db->mallocFailed = 1;
20537   }
20538   return z;
20539 }
20540 
20541 /*
20542 ** Print into memory obtained from sqliteMalloc().  Use the internal
20543 ** %-conversion extensions.
20544 */
20545 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20546   va_list ap;
20547   char *z;
20548   va_start(ap, zFormat);
20549   z = sqlite3VMPrintf(db, zFormat, ap);
20550   va_end(ap);
20551   return z;
20552 }
20553 
20554 /*
20555 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20556 ** the string and before returnning.  This routine is intended to be used
20557 ** to modify an existing string.  For example:
20558 **
20559 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20560 **
20561 */
20562 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20563   va_list ap;
20564   char *z;
20565   va_start(ap, zFormat);
20566   z = sqlite3VMPrintf(db, zFormat, ap);
20567   va_end(ap);
20568   sqlite3DbFree(db, zStr);
20569   return z;
20570 }
20571 
20572 /*
20573 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20574 ** %-conversion extensions.
20575 */
20576 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20577   char *z;
20578   char zBase[SQLITE_PRINT_BUF_SIZE];
20579   StrAccum acc;
20580 #ifndef SQLITE_OMIT_AUTOINIT
20581   if( sqlite3_initialize() ) return 0;
20582 #endif
20583   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20584   acc.useMalloc = 2;
20585   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20586   z = sqlite3StrAccumFinish(&acc);
20587   return z;
20588 }
20589 
20590 /*
20591 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20592 ** %-conversion extensions.
20593 */
20594 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20595   va_list ap;
20596   char *z;
20597 #ifndef SQLITE_OMIT_AUTOINIT
20598   if( sqlite3_initialize() ) return 0;
20599 #endif
20600   va_start(ap, zFormat);
20601   z = sqlite3_vmprintf(zFormat, ap);
20602   va_end(ap);
20603   return z;
20604 }
20605 
20606 /*
20607 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20608 ** current locale settings.  This is important for SQLite because we
20609 ** are not able to use a "," as the decimal point in place of "." as
20610 ** specified by some locales.
20611 **
20612 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20613 ** from the snprintf() standard.  Unfortunately, it is too late to change
20614 ** this without breaking compatibility, so we just have to live with the
20615 ** mistake.
20616 **
20617 ** sqlite3_vsnprintf() is the varargs version.
20618 */
20619 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20620   StrAccum acc;
20621   if( n<=0 ) return zBuf;
20622   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20623   acc.useMalloc = 0;
20624   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20625   return sqlite3StrAccumFinish(&acc);
20626 }
20627 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20628   char *z;
20629   va_list ap;
20630   va_start(ap,zFormat);
20631   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20632   va_end(ap);
20633   return z;
20634 }
20635 
20636 /*
20637 ** This is the routine that actually formats the sqlite3_log() message.
20638 ** We house it in a separate routine from sqlite3_log() to avoid using
20639 ** stack space on small-stack systems when logging is disabled.
20640 **
20641 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20642 ** allocate memory because it might be called while the memory allocator
20643 ** mutex is held.
20644 */
20645 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20646   StrAccum acc;                          /* String accumulator */
20647   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20648 
20649   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20650   acc.useMalloc = 0;
20651   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20652   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20653                            sqlite3StrAccumFinish(&acc));
20654 }
20655 
20656 /*
20657 ** Format and write a message to the log if logging is enabled.
20658 */
20659 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20660   va_list ap;                             /* Vararg list */
20661   if( sqlite3GlobalConfig.xLog ){
20662     va_start(ap, zFormat);
20663     renderLogMsg(iErrCode, zFormat, ap);
20664     va_end(ap);
20665   }
20666 }
20667 
20668 #if defined(SQLITE_DEBUG)
20669 /*
20670 ** A version of printf() that understands %lld.  Used for debugging.
20671 ** The printf() built into some versions of windows does not understand %lld
20672 ** and segfaults if you give it a long long int.
20673 */
20674 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20675   va_list ap;
20676   StrAccum acc;
20677   char zBuf[500];
20678   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20679   acc.useMalloc = 0;
20680   va_start(ap,zFormat);
20681   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20682   va_end(ap);
20683   sqlite3StrAccumFinish(&acc);
20684   fprintf(stdout,"%s", zBuf);
20685   fflush(stdout);
20686 }
20687 #endif
20688 
20689 #ifndef SQLITE_OMIT_TRACE
20690 /*
20691 ** variable-argument wrapper around sqlite3VXPrintf().
20692 */
20693 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20694   va_list ap;
20695   va_start(ap,zFormat);
20696   sqlite3VXPrintf(p, 1, zFormat, ap);
20697   va_end(ap);
20698 }
20699 #endif
20700 
20701 /************** End of printf.c **********************************************/
20702 /************** Begin file random.c ******************************************/
20703 /*
20704 ** 2001 September 15
20705 **
20706 ** The author disclaims copyright to this source code.  In place of
20707 ** a legal notice, here is a blessing:
20708 **
20709 **    May you do good and not evil.
20710 **    May you find forgiveness for yourself and forgive others.
20711 **    May you share freely, never taking more than you give.
20712 **
20713 *************************************************************************
20714 ** This file contains code to implement a pseudo-random number
20715 ** generator (PRNG) for SQLite.
20716 **
20717 ** Random numbers are used by some of the database backends in order
20718 ** to generate random integer keys for tables or random filenames.
20719 */
20720 
20721 
20722 /* All threads share a single random number generator.
20723 ** This structure is the current state of the generator.
20724 */
20725 static SQLITE_WSD struct sqlite3PrngType {
20726   unsigned char isInit;          /* True if initialized */
20727   unsigned char i, j;            /* State variables */
20728   unsigned char s[256];          /* State variables */
20729 } sqlite3Prng;
20730 
20731 /*
20732 ** Return N random bytes.
20733 */
20734 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20735   unsigned char t;
20736   unsigned char *zBuf = pBuf;
20737 
20738   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20739   ** state vector.  If writable static data is unsupported on the target,
20740   ** we have to locate the state vector at run-time.  In the more common
20741   ** case where writable static data is supported, wsdPrng can refer directly
20742   ** to the "sqlite3Prng" state vector declared above.
20743   */
20744 #ifdef SQLITE_OMIT_WSD
20745   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20746 # define wsdPrng p[0]
20747 #else
20748 # define wsdPrng sqlite3Prng
20749 #endif
20750 
20751 #if SQLITE_THREADSAFE
20752   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20753   sqlite3_mutex_enter(mutex);
20754 #endif
20755 
20756   /* Initialize the state of the random number generator once,
20757   ** the first time this routine is called.  The seed value does
20758   ** not need to contain a lot of randomness since we are not
20759   ** trying to do secure encryption or anything like that...
20760   **
20761   ** Nothing in this file or anywhere else in SQLite does any kind of
20762   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20763   ** number generator) not as an encryption device.
20764   */
20765   if( !wsdPrng.isInit ){
20766     int i;
20767     char k[256];
20768     wsdPrng.j = 0;
20769     wsdPrng.i = 0;
20770     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20771     for(i=0; i<256; i++){
20772       wsdPrng.s[i] = (u8)i;
20773     }
20774     for(i=0; i<256; i++){
20775       wsdPrng.j += wsdPrng.s[i] + k[i];
20776       t = wsdPrng.s[wsdPrng.j];
20777       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20778       wsdPrng.s[i] = t;
20779     }
20780     wsdPrng.isInit = 1;
20781   }
20782 
20783   while( N-- ){
20784     wsdPrng.i++;
20785     t = wsdPrng.s[wsdPrng.i];
20786     wsdPrng.j += t;
20787     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20788     wsdPrng.s[wsdPrng.j] = t;
20789     t += wsdPrng.s[wsdPrng.i];
20790     *(zBuf++) = wsdPrng.s[t];
20791   }
20792   sqlite3_mutex_leave(mutex);
20793 }
20794 
20795 #ifndef SQLITE_OMIT_BUILTIN_TEST
20796 /*
20797 ** For testing purposes, we sometimes want to preserve the state of
20798 ** PRNG and restore the PRNG to its saved state at a later time, or
20799 ** to reset the PRNG to its initial state.  These routines accomplish
20800 ** those tasks.
20801 **
20802 ** The sqlite3_test_control() interface calls these routines to
20803 ** control the PRNG.
20804 */
20805 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20806 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20807   memcpy(
20808     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20809     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20810     sizeof(sqlite3Prng)
20811   );
20812 }
20813 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20814   memcpy(
20815     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20816     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20817     sizeof(sqlite3Prng)
20818   );
20819 }
20820 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20821   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20822 }
20823 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20824 
20825 /************** End of random.c **********************************************/
20826 /************** Begin file utf.c *********************************************/
20827 /*
20828 ** 2004 April 13
20829 **
20830 ** The author disclaims copyright to this source code.  In place of
20831 ** a legal notice, here is a blessing:
20832 **
20833 **    May you do good and not evil.
20834 **    May you find forgiveness for yourself and forgive others.
20835 **    May you share freely, never taking more than you give.
20836 **
20837 *************************************************************************
20838 ** This file contains routines used to translate between UTF-8, 
20839 ** UTF-16, UTF-16BE, and UTF-16LE.
20840 **
20841 ** Notes on UTF-8:
20842 **
20843 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20844 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20845 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20846 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20847 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20848 **
20849 **
20850 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20851 **
20852 **      Word-0               Word-1          Value
20853 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20854 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20855 **
20856 **
20857 ** BOM or Byte Order Mark:
20858 **     0xff 0xfe   little-endian utf-16 follows
20859 **     0xfe 0xff   big-endian utf-16 follows
20860 **
20861 */
20862 /* #include <assert.h> */
20863 
20864 #ifndef SQLITE_AMALGAMATION
20865 /*
20866 ** The following constant value is used by the SQLITE_BIGENDIAN and
20867 ** SQLITE_LITTLEENDIAN macros.
20868 */
20869 SQLITE_PRIVATE const int sqlite3one = 1;
20870 #endif /* SQLITE_AMALGAMATION */
20871 
20872 /*
20873 ** This lookup table is used to help decode the first byte of
20874 ** a multi-byte UTF8 character.
20875 */
20876 static const unsigned char sqlite3Utf8Trans1[] = {
20877   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20878   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20879   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20880   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20881   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20882   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20883   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20884   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20885 };
20886 
20887 
20888 #define WRITE_UTF8(zOut, c) {                          \
20889   if( c<0x00080 ){                                     \
20890     *zOut++ = (u8)(c&0xFF);                            \
20891   }                                                    \
20892   else if( c<0x00800 ){                                \
20893     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20894     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20895   }                                                    \
20896   else if( c<0x10000 ){                                \
20897     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20898     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20899     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20900   }else{                                               \
20901     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20902     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20903     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20904     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20905   }                                                    \
20906 }
20907 
20908 #define WRITE_UTF16LE(zOut, c) {                                    \
20909   if( c<=0xFFFF ){                                                  \
20910     *zOut++ = (u8)(c&0x00FF);                                       \
20911     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20912   }else{                                                            \
20913     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20914     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20915     *zOut++ = (u8)(c&0x00FF);                                       \
20916     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20917   }                                                                 \
20918 }
20919 
20920 #define WRITE_UTF16BE(zOut, c) {                                    \
20921   if( c<=0xFFFF ){                                                  \
20922     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20923     *zOut++ = (u8)(c&0x00FF);                                       \
20924   }else{                                                            \
20925     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20926     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20927     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20928     *zOut++ = (u8)(c&0x00FF);                                       \
20929   }                                                                 \
20930 }
20931 
20932 #define READ_UTF16LE(zIn, TERM, c){                                   \
20933   c = (*zIn++);                                                       \
20934   c += ((*zIn++)<<8);                                                 \
20935   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20936     int c2 = (*zIn++);                                                \
20937     c2 += ((*zIn++)<<8);                                              \
20938     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20939   }                                                                   \
20940 }
20941 
20942 #define READ_UTF16BE(zIn, TERM, c){                                   \
20943   c = ((*zIn++)<<8);                                                  \
20944   c += (*zIn++);                                                      \
20945   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20946     int c2 = ((*zIn++)<<8);                                           \
20947     c2 += (*zIn++);                                                   \
20948     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20949   }                                                                   \
20950 }
20951 
20952 /*
20953 ** Translate a single UTF-8 character.  Return the unicode value.
20954 **
20955 ** During translation, assume that the byte that zTerm points
20956 ** is a 0x00.
20957 **
20958 ** Write a pointer to the next unread byte back into *pzNext.
20959 **
20960 ** Notes On Invalid UTF-8:
20961 **
20962 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20963 **     be encoded as a multi-byte character.  Any multi-byte character that
20964 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20965 **
20966 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20967 **     If a multi-byte character attempts to encode a value between
20968 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20969 **
20970 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20971 **     byte of a character are interpreted as single-byte characters
20972 **     and rendered as themselves even though they are technically
20973 **     invalid characters.
20974 **
20975 **  *  This routine accepts an infinite number of different UTF8 encodings
20976 **     for unicode values 0x80 and greater.  It do not change over-length
20977 **     encodings to 0xfffd as some systems recommend.
20978 */
20979 #define READ_UTF8(zIn, zTerm, c)                           \
20980   c = *(zIn++);                                            \
20981   if( c>=0xc0 ){                                           \
20982     c = sqlite3Utf8Trans1[c-0xc0];                         \
20983     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20984       c = (c<<6) + (0x3f & *(zIn++));                      \
20985     }                                                      \
20986     if( c<0x80                                             \
20987         || (c&0xFFFFF800)==0xD800                          \
20988         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20989   }
20990 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20991   const unsigned char **pz    /* Pointer to string from which to read char */
20992 ){
20993   unsigned int c;
20994 
20995   /* Same as READ_UTF8() above but without the zTerm parameter.
20996   ** For this routine, we assume the UTF8 string is always zero-terminated.
20997   */
20998   c = *((*pz)++);
20999   if( c>=0xc0 ){
21000     c = sqlite3Utf8Trans1[c-0xc0];
21001     while( (*(*pz) & 0xc0)==0x80 ){
21002       c = (c<<6) + (0x3f & *((*pz)++));
21003     }
21004     if( c<0x80
21005         || (c&0xFFFFF800)==0xD800
21006         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
21007   }
21008   return c;
21009 }
21010 
21011 
21012 
21013 
21014 /*
21015 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
21016 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
21017 */ 
21018 /* #define TRANSLATE_TRACE 1 */
21019 
21020 #ifndef SQLITE_OMIT_UTF16
21021 /*
21022 ** This routine transforms the internal text encoding used by pMem to
21023 ** desiredEnc. It is an error if the string is already of the desired
21024 ** encoding, or if *pMem does not contain a string value.
21025 */
21026 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
21027   int len;                    /* Maximum length of output string in bytes */
21028   unsigned char *zOut;                  /* Output buffer */
21029   unsigned char *zIn;                   /* Input iterator */
21030   unsigned char *zTerm;                 /* End of input */
21031   unsigned char *z;                     /* Output iterator */
21032   unsigned int c;
21033 
21034   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
21035   assert( pMem->flags&MEM_Str );
21036   assert( pMem->enc!=desiredEnc );
21037   assert( pMem->enc!=0 );
21038   assert( pMem->n>=0 );
21039 
21040 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21041   {
21042     char zBuf[100];
21043     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21044     fprintf(stderr, "INPUT:  %s\n", zBuf);
21045   }
21046 #endif
21047 
21048   /* If the translation is between UTF-16 little and big endian, then 
21049   ** all that is required is to swap the byte order. This case is handled
21050   ** differently from the others.
21051   */
21052   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
21053     u8 temp;
21054     int rc;
21055     rc = sqlite3VdbeMemMakeWriteable(pMem);
21056     if( rc!=SQLITE_OK ){
21057       assert( rc==SQLITE_NOMEM );
21058       return SQLITE_NOMEM;
21059     }
21060     zIn = (u8*)pMem->z;
21061     zTerm = &zIn[pMem->n&~1];
21062     while( zIn<zTerm ){
21063       temp = *zIn;
21064       *zIn = *(zIn+1);
21065       zIn++;
21066       *zIn++ = temp;
21067     }
21068     pMem->enc = desiredEnc;
21069     goto translate_out;
21070   }
21071 
21072   /* Set len to the maximum number of bytes required in the output buffer. */
21073   if( desiredEnc==SQLITE_UTF8 ){
21074     /* When converting from UTF-16, the maximum growth results from
21075     ** translating a 2-byte character to a 4-byte UTF-8 character.
21076     ** A single byte is required for the output string
21077     ** nul-terminator.
21078     */
21079     pMem->n &= ~1;
21080     len = pMem->n * 2 + 1;
21081   }else{
21082     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
21083     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
21084     ** character. Two bytes are required in the output buffer for the
21085     ** nul-terminator.
21086     */
21087     len = pMem->n * 2 + 2;
21088   }
21089 
21090   /* Set zIn to point at the start of the input buffer and zTerm to point 1
21091   ** byte past the end.
21092   **
21093   ** Variable zOut is set to point at the output buffer, space obtained
21094   ** from sqlite3_malloc().
21095   */
21096   zIn = (u8*)pMem->z;
21097   zTerm = &zIn[pMem->n];
21098   zOut = sqlite3DbMallocRaw(pMem->db, len);
21099   if( !zOut ){
21100     return SQLITE_NOMEM;
21101   }
21102   z = zOut;
21103 
21104   if( pMem->enc==SQLITE_UTF8 ){
21105     if( desiredEnc==SQLITE_UTF16LE ){
21106       /* UTF-8 -> UTF-16 Little-endian */
21107       while( zIn<zTerm ){
21108         READ_UTF8(zIn, zTerm, c);
21109         WRITE_UTF16LE(z, c);
21110       }
21111     }else{
21112       assert( desiredEnc==SQLITE_UTF16BE );
21113       /* UTF-8 -> UTF-16 Big-endian */
21114       while( zIn<zTerm ){
21115         READ_UTF8(zIn, zTerm, c);
21116         WRITE_UTF16BE(z, c);
21117       }
21118     }
21119     pMem->n = (int)(z - zOut);
21120     *z++ = 0;
21121   }else{
21122     assert( desiredEnc==SQLITE_UTF8 );
21123     if( pMem->enc==SQLITE_UTF16LE ){
21124       /* UTF-16 Little-endian -> UTF-8 */
21125       while( zIn<zTerm ){
21126         READ_UTF16LE(zIn, zIn<zTerm, c); 
21127         WRITE_UTF8(z, c);
21128       }
21129     }else{
21130       /* UTF-16 Big-endian -> UTF-8 */
21131       while( zIn<zTerm ){
21132         READ_UTF16BE(zIn, zIn<zTerm, c); 
21133         WRITE_UTF8(z, c);
21134       }
21135     }
21136     pMem->n = (int)(z - zOut);
21137   }
21138   *z = 0;
21139   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
21140 
21141   sqlite3VdbeMemRelease(pMem);
21142   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
21143   pMem->enc = desiredEnc;
21144   pMem->flags |= (MEM_Term|MEM_Dyn);
21145   pMem->z = (char*)zOut;
21146   pMem->zMalloc = pMem->z;
21147 
21148 translate_out:
21149 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21150   {
21151     char zBuf[100];
21152     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21153     fprintf(stderr, "OUTPUT: %s\n", zBuf);
21154   }
21155 #endif
21156   return SQLITE_OK;
21157 }
21158 
21159 /*
21160 ** This routine checks for a byte-order mark at the beginning of the 
21161 ** UTF-16 string stored in *pMem. If one is present, it is removed and
21162 ** the encoding of the Mem adjusted. This routine does not do any
21163 ** byte-swapping, it just sets Mem.enc appropriately.
21164 **
21165 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
21166 ** changed by this function.
21167 */
21168 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
21169   int rc = SQLITE_OK;
21170   u8 bom = 0;
21171 
21172   assert( pMem->n>=0 );
21173   if( pMem->n>1 ){
21174     u8 b1 = *(u8 *)pMem->z;
21175     u8 b2 = *(((u8 *)pMem->z) + 1);
21176     if( b1==0xFE && b2==0xFF ){
21177       bom = SQLITE_UTF16BE;
21178     }
21179     if( b1==0xFF && b2==0xFE ){
21180       bom = SQLITE_UTF16LE;
21181     }
21182   }
21183   
21184   if( bom ){
21185     rc = sqlite3VdbeMemMakeWriteable(pMem);
21186     if( rc==SQLITE_OK ){
21187       pMem->n -= 2;
21188       memmove(pMem->z, &pMem->z[2], pMem->n);
21189       pMem->z[pMem->n] = '\0';
21190       pMem->z[pMem->n+1] = '\0';
21191       pMem->flags |= MEM_Term;
21192       pMem->enc = bom;
21193     }
21194   }
21195   return rc;
21196 }
21197 #endif /* SQLITE_OMIT_UTF16 */
21198 
21199 /*
21200 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21201 ** return the number of unicode characters in pZ up to (but not including)
21202 ** the first 0x00 byte. If nByte is not less than zero, return the
21203 ** number of unicode characters in the first nByte of pZ (or up to 
21204 ** the first 0x00, whichever comes first).
21205 */
21206 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21207   int r = 0;
21208   const u8 *z = (const u8*)zIn;
21209   const u8 *zTerm;
21210   if( nByte>=0 ){
21211     zTerm = &z[nByte];
21212   }else{
21213     zTerm = (const u8*)(-1);
21214   }
21215   assert( z<=zTerm );
21216   while( *z!=0 && z<zTerm ){
21217     SQLITE_SKIP_UTF8(z);
21218     r++;
21219   }
21220   return r;
21221 }
21222 
21223 /* This test function is not currently used by the automated test-suite. 
21224 ** Hence it is only available in debug builds.
21225 */
21226 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21227 /*
21228 ** Translate UTF-8 to UTF-8.
21229 **
21230 ** This has the effect of making sure that the string is well-formed
21231 ** UTF-8.  Miscoded characters are removed.
21232 **
21233 ** The translation is done in-place and aborted if the output
21234 ** overruns the input.
21235 */
21236 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21237   unsigned char *zOut = zIn;
21238   unsigned char *zStart = zIn;
21239   u32 c;
21240 
21241   while( zIn[0] && zOut<=zIn ){
21242     c = sqlite3Utf8Read((const u8**)&zIn);
21243     if( c!=0xfffd ){
21244       WRITE_UTF8(zOut, c);
21245     }
21246   }
21247   *zOut = 0;
21248   return (int)(zOut - zStart);
21249 }
21250 #endif
21251 
21252 #ifndef SQLITE_OMIT_UTF16
21253 /*
21254 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21255 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21256 ** be freed by the calling function.
21257 **
21258 ** NULL is returned if there is an allocation error.
21259 */
21260 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21261   Mem m;
21262   memset(&m, 0, sizeof(m));
21263   m.db = db;
21264   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21265   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21266   if( db->mallocFailed ){
21267     sqlite3VdbeMemRelease(&m);
21268     m.z = 0;
21269   }
21270   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21271   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21272   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21273   assert( m.z || db->mallocFailed );
21274   return m.z;
21275 }
21276 
21277 /*
21278 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21279 ** Return the number of bytes in the first nChar unicode characters
21280 ** in pZ.  nChar must be non-negative.
21281 */
21282 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21283   int c;
21284   unsigned char const *z = zIn;
21285   int n = 0;
21286   
21287   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21288     while( n<nChar ){
21289       READ_UTF16BE(z, 1, c);
21290       n++;
21291     }
21292   }else{
21293     while( n<nChar ){
21294       READ_UTF16LE(z, 1, c);
21295       n++;
21296     }
21297   }
21298   return (int)(z-(unsigned char const *)zIn);
21299 }
21300 
21301 #if defined(SQLITE_TEST)
21302 /*
21303 ** This routine is called from the TCL test function "translate_selftest".
21304 ** It checks that the primitives for serializing and deserializing
21305 ** characters in each encoding are inverses of each other.
21306 */
21307 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21308   unsigned int i, t;
21309   unsigned char zBuf[20];
21310   unsigned char *z;
21311   int n;
21312   unsigned int c;
21313 
21314   for(i=0; i<0x00110000; i++){
21315     z = zBuf;
21316     WRITE_UTF8(z, i);
21317     n = (int)(z-zBuf);
21318     assert( n>0 && n<=4 );
21319     z[0] = 0;
21320     z = zBuf;
21321     c = sqlite3Utf8Read((const u8**)&z);
21322     t = i;
21323     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21324     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21325     assert( c==t );
21326     assert( (z-zBuf)==n );
21327   }
21328   for(i=0; i<0x00110000; i++){
21329     if( i>=0xD800 && i<0xE000 ) continue;
21330     z = zBuf;
21331     WRITE_UTF16LE(z, i);
21332     n = (int)(z-zBuf);
21333     assert( n>0 && n<=4 );
21334     z[0] = 0;
21335     z = zBuf;
21336     READ_UTF16LE(z, 1, c);
21337     assert( c==i );
21338     assert( (z-zBuf)==n );
21339   }
21340   for(i=0; i<0x00110000; i++){
21341     if( i>=0xD800 && i<0xE000 ) continue;
21342     z = zBuf;
21343     WRITE_UTF16BE(z, i);
21344     n = (int)(z-zBuf);
21345     assert( n>0 && n<=4 );
21346     z[0] = 0;
21347     z = zBuf;
21348     READ_UTF16BE(z, 1, c);
21349     assert( c==i );
21350     assert( (z-zBuf)==n );
21351   }
21352 }
21353 #endif /* SQLITE_TEST */
21354 #endif /* SQLITE_OMIT_UTF16 */
21355 
21356 /************** End of utf.c *************************************************/
21357 /************** Begin file util.c ********************************************/
21358 /*
21359 ** 2001 September 15
21360 **
21361 ** The author disclaims copyright to this source code.  In place of
21362 ** a legal notice, here is a blessing:
21363 **
21364 **    May you do good and not evil.
21365 **    May you find forgiveness for yourself and forgive others.
21366 **    May you share freely, never taking more than you give.
21367 **
21368 *************************************************************************
21369 ** Utility functions used throughout sqlite.
21370 **
21371 ** This file contains functions for allocating memory, comparing
21372 ** strings, and stuff like that.
21373 **
21374 */
21375 /* #include <stdarg.h> */
21376 #ifdef SQLITE_HAVE_ISNAN
21377 # include <math.h>
21378 #endif
21379 
21380 /*
21381 ** Routine needed to support the testcase() macro.
21382 */
21383 #ifdef SQLITE_COVERAGE_TEST
21384 SQLITE_PRIVATE void sqlite3Coverage(int x){
21385   static unsigned dummy = 0;
21386   dummy += (unsigned)x;
21387 }
21388 #endif
21389 
21390 #ifndef SQLITE_OMIT_FLOATING_POINT
21391 /*
21392 ** Return true if the floating point value is Not a Number (NaN).
21393 **
21394 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21395 ** Otherwise, we have our own implementation that works on most systems.
21396 */
21397 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21398   int rc;   /* The value return */
21399 #if !defined(SQLITE_HAVE_ISNAN)
21400   /*
21401   ** Systems that support the isnan() library function should probably
21402   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21403   ** found that many systems do not have a working isnan() function so
21404   ** this implementation is provided as an alternative.
21405   **
21406   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21407   ** On the other hand, the use of -ffast-math comes with the following
21408   ** warning:
21409   **
21410   **      This option [-ffast-math] should never be turned on by any
21411   **      -O option since it can result in incorrect output for programs
21412   **      which depend on an exact implementation of IEEE or ISO 
21413   **      rules/specifications for math functions.
21414   **
21415   ** Under MSVC, this NaN test may fail if compiled with a floating-
21416   ** point precision mode other than /fp:precise.  From the MSDN 
21417   ** documentation:
21418   **
21419   **      The compiler [with /fp:precise] will properly handle comparisons 
21420   **      involving NaN. For example, x != x evaluates to true if x is NaN 
21421   **      ...
21422   */
21423 #ifdef __FAST_MATH__
21424 # error SQLite will not work correctly with the -ffast-math option of GCC.
21425 #endif
21426   volatile double y = x;
21427   volatile double z = y;
21428   rc = (y!=z);
21429 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21430   rc = isnan(x);
21431 #endif /* SQLITE_HAVE_ISNAN */
21432   testcase( rc );
21433   return rc;
21434 }
21435 #endif /* SQLITE_OMIT_FLOATING_POINT */
21436 
21437 /*
21438 ** Compute a string length that is limited to what can be stored in
21439 ** lower 30 bits of a 32-bit signed integer.
21440 **
21441 ** The value returned will never be negative.  Nor will it ever be greater
21442 ** than the actual length of the string.  For very long strings (greater
21443 ** than 1GiB) the value returned might be less than the true string length.
21444 */
21445 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21446   const char *z2 = z;
21447   if( z==0 ) return 0;
21448   while( *z2 ){ z2++; }
21449   return 0x3fffffff & (int)(z2 - z);
21450 }
21451 
21452 /*
21453 ** Set the most recent error code and error string for the sqlite
21454 ** handle "db". The error code is set to "err_code".
21455 **
21456 ** If it is not NULL, string zFormat specifies the format of the
21457 ** error string in the style of the printf functions: The following
21458 ** format characters are allowed:
21459 **
21460 **      %s      Insert a string
21461 **      %z      A string that should be freed after use
21462 **      %d      Insert an integer
21463 **      %T      Insert a token
21464 **      %S      Insert the first element of a SrcList
21465 **
21466 ** zFormat and any string tokens that follow it are assumed to be
21467 ** encoded in UTF-8.
21468 **
21469 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21470 ** should be called with err_code set to SQLITE_OK and zFormat set
21471 ** to NULL.
21472 */
21473 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21474   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21475     db->errCode = err_code;
21476     if( zFormat ){
21477       char *z;
21478       va_list ap;
21479       va_start(ap, zFormat);
21480       z = sqlite3VMPrintf(db, zFormat, ap);
21481       va_end(ap);
21482       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21483     }else{
21484       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21485     }
21486   }
21487 }
21488 
21489 /*
21490 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21491 ** The following formatting characters are allowed:
21492 **
21493 **      %s      Insert a string
21494 **      %z      A string that should be freed after use
21495 **      %d      Insert an integer
21496 **      %T      Insert a token
21497 **      %S      Insert the first element of a SrcList
21498 **
21499 ** This function should be used to report any error that occurs whilst
21500 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21501 ** last thing the sqlite3_prepare() function does is copy the error
21502 ** stored by this function into the database handle using sqlite3Error().
21503 ** Function sqlite3Error() should be used during statement execution
21504 ** (sqlite3_step() etc.).
21505 */
21506 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21507   char *zMsg;
21508   va_list ap;
21509   sqlite3 *db = pParse->db;
21510   va_start(ap, zFormat);
21511   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21512   va_end(ap);
21513   if( db->suppressErr ){
21514     sqlite3DbFree(db, zMsg);
21515   }else{
21516     pParse->nErr++;
21517     sqlite3DbFree(db, pParse->zErrMsg);
21518     pParse->zErrMsg = zMsg;
21519     pParse->rc = SQLITE_ERROR;
21520   }
21521 }
21522 
21523 /*
21524 ** Convert an SQL-style quoted string into a normal string by removing
21525 ** the quote characters.  The conversion is done in-place.  If the
21526 ** input does not begin with a quote character, then this routine
21527 ** is a no-op.
21528 **
21529 ** The input string must be zero-terminated.  A new zero-terminator
21530 ** is added to the dequoted string.
21531 **
21532 ** The return value is -1 if no dequoting occurs or the length of the
21533 ** dequoted string, exclusive of the zero terminator, if dequoting does
21534 ** occur.
21535 **
21536 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21537 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21538 ** "a-b-c".
21539 */
21540 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21541   char quote;
21542   int i, j;
21543   if( z==0 ) return -1;
21544   quote = z[0];
21545   switch( quote ){
21546     case '\'':  break;
21547     case '"':   break;
21548     case '`':   break;                /* For MySQL compatibility */
21549     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21550     default:    return -1;
21551   }
21552   for(i=1, j=0;; i++){
21553     assert( z[i] );
21554     if( z[i]==quote ){
21555       if( z[i+1]==quote ){
21556         z[j++] = quote;
21557         i++;
21558       }else{
21559         break;
21560       }
21561     }else{
21562       z[j++] = z[i];
21563     }
21564   }
21565   z[j] = 0;
21566   return j;
21567 }
21568 
21569 /* Convenient short-hand */
21570 #define UpperToLower sqlite3UpperToLower
21571 
21572 /*
21573 ** Some systems have stricmp().  Others have strcasecmp().  Because
21574 ** there is no consistency, we will define our own.
21575 **
21576 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21577 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21578 ** the contents of two buffers containing UTF-8 strings in a
21579 ** case-independent fashion, using the same definition of "case
21580 ** independence" that SQLite uses internally when comparing identifiers.
21581 */
21582 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21583   register unsigned char *a, *b;
21584   a = (unsigned char *)zLeft;
21585   b = (unsigned char *)zRight;
21586   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21587   return UpperToLower[*a] - UpperToLower[*b];
21588 }
21589 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21590   register unsigned char *a, *b;
21591   a = (unsigned char *)zLeft;
21592   b = (unsigned char *)zRight;
21593   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21594   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21595 }
21596 
21597 /*
21598 ** The string z[] is an text representation of a real number.
21599 ** Convert this string to a double and write it into *pResult.
21600 **
21601 ** The string z[] is length bytes in length (bytes, not characters) and
21602 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21603 **
21604 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21605 ** if the string is empty or contains extraneous text.  Valid numbers
21606 ** are in one of these formats:
21607 **
21608 **    [+-]digits[E[+-]digits]
21609 **    [+-]digits.[digits][E[+-]digits]
21610 **    [+-].digits[E[+-]digits]
21611 **
21612 ** Leading and trailing whitespace is ignored for the purpose of determining
21613 ** validity.
21614 **
21615 ** If some prefix of the input string is a valid number, this routine
21616 ** returns FALSE but it still converts the prefix and writes the result
21617 ** into *pResult.
21618 */
21619 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21620 #ifndef SQLITE_OMIT_FLOATING_POINT
21621   int incr;
21622   const char *zEnd = z + length;
21623   /* sign * significand * (10 ^ (esign * exponent)) */
21624   int sign = 1;    /* sign of significand */
21625   i64 s = 0;       /* significand */
21626   int d = 0;       /* adjust exponent for shifting decimal point */
21627   int esign = 1;   /* sign of exponent */
21628   int e = 0;       /* exponent */
21629   int eValid = 1;  /* True exponent is either not used or is well-formed */
21630   double result;
21631   int nDigits = 0;
21632   int nonNum = 0;
21633 
21634   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21635   *pResult = 0.0;   /* Default return value, in case of an error */
21636 
21637   if( enc==SQLITE_UTF8 ){
21638     incr = 1;
21639   }else{
21640     int i;
21641     incr = 2;
21642     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21643     for(i=3-enc; i<length && z[i]==0; i+=2){}
21644     nonNum = i<length;
21645     zEnd = z+i+enc-3;
21646     z += (enc&1);
21647   }
21648 
21649   /* skip leading spaces */
21650   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21651   if( z>=zEnd ) return 0;
21652 
21653   /* get sign of significand */
21654   if( *z=='-' ){
21655     sign = -1;
21656     z+=incr;
21657   }else if( *z=='+' ){
21658     z+=incr;
21659   }
21660 
21661   /* skip leading zeroes */
21662   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21663 
21664   /* copy max significant digits to significand */
21665   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21666     s = s*10 + (*z - '0');
21667     z+=incr, nDigits++;
21668   }
21669 
21670   /* skip non-significant significand digits
21671   ** (increase exponent by d to shift decimal left) */
21672   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21673   if( z>=zEnd ) goto do_atof_calc;
21674 
21675   /* if decimal point is present */
21676   if( *z=='.' ){
21677     z+=incr;
21678     /* copy digits from after decimal to significand
21679     ** (decrease exponent by d to shift decimal right) */
21680     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21681       s = s*10 + (*z - '0');
21682       z+=incr, nDigits++, d--;
21683     }
21684     /* skip non-significant digits */
21685     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21686   }
21687   if( z>=zEnd ) goto do_atof_calc;
21688 
21689   /* if exponent is present */
21690   if( *z=='e' || *z=='E' ){
21691     z+=incr;
21692     eValid = 0;
21693     if( z>=zEnd ) goto do_atof_calc;
21694     /* get sign of exponent */
21695     if( *z=='-' ){
21696       esign = -1;
21697       z+=incr;
21698     }else if( *z=='+' ){
21699       z+=incr;
21700     }
21701     /* copy digits to exponent */
21702     while( z<zEnd && sqlite3Isdigit(*z) ){
21703       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21704       z+=incr;
21705       eValid = 1;
21706     }
21707   }
21708 
21709   /* skip trailing spaces */
21710   if( nDigits && eValid ){
21711     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21712   }
21713 
21714 do_atof_calc:
21715   /* adjust exponent by d, and update sign */
21716   e = (e*esign) + d;
21717   if( e<0 ) {
21718     esign = -1;
21719     e *= -1;
21720   } else {
21721     esign = 1;
21722   }
21723 
21724   /* if 0 significand */
21725   if( !s ) {
21726     /* In the IEEE 754 standard, zero is signed.
21727     ** Add the sign if we've seen at least one digit */
21728     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21729   } else {
21730     /* attempt to reduce exponent */
21731     if( esign>0 ){
21732       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21733     }else{
21734       while( !(s%10) && e>0 ) e--,s/=10;
21735     }
21736 
21737     /* adjust the sign of significand */
21738     s = sign<0 ? -s : s;
21739 
21740     /* if exponent, scale significand as appropriate
21741     ** and store in result. */
21742     if( e ){
21743       LONGDOUBLE_TYPE scale = 1.0;
21744       /* attempt to handle extremely small/large numbers better */
21745       if( e>307 && e<342 ){
21746         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21747         if( esign<0 ){
21748           result = s / scale;
21749           result /= 1.0e+308;
21750         }else{
21751           result = s * scale;
21752           result *= 1.0e+308;
21753         }
21754       }else if( e>=342 ){
21755         if( esign<0 ){
21756           result = 0.0*s;
21757         }else{
21758           result = 1e308*1e308*s;  /* Infinity */
21759         }
21760       }else{
21761         /* 1.0e+22 is the largest power of 10 than can be 
21762         ** represented exactly. */
21763         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21764         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21765         if( esign<0 ){
21766           result = s / scale;
21767         }else{
21768           result = s * scale;
21769         }
21770       }
21771     } else {
21772       result = (double)s;
21773     }
21774   }
21775 
21776   /* store the result */
21777   *pResult = result;
21778 
21779   /* return true if number and no extra non-whitespace chracters after */
21780   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21781 #else
21782   return !sqlite3Atoi64(z, pResult, length, enc);
21783 #endif /* SQLITE_OMIT_FLOATING_POINT */
21784 }
21785 
21786 /*
21787 ** Compare the 19-character string zNum against the text representation
21788 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21789 ** if zNum is less than, equal to, or greater than the string.
21790 ** Note that zNum must contain exactly 19 characters.
21791 **
21792 ** Unlike memcmp() this routine is guaranteed to return the difference
21793 ** in the values of the last digit if the only difference is in the
21794 ** last digit.  So, for example,
21795 **
21796 **      compare2pow63("9223372036854775800", 1)
21797 **
21798 ** will return -8.
21799 */
21800 static int compare2pow63(const char *zNum, int incr){
21801   int c = 0;
21802   int i;
21803                     /* 012345678901234567 */
21804   const char *pow63 = "922337203685477580";
21805   for(i=0; c==0 && i<18; i++){
21806     c = (zNum[i*incr]-pow63[i])*10;
21807   }
21808   if( c==0 ){
21809     c = zNum[18*incr] - '8';
21810     testcase( c==(-1) );
21811     testcase( c==0 );
21812     testcase( c==(+1) );
21813   }
21814   return c;
21815 }
21816 
21817 
21818 /*
21819 ** Convert zNum to a 64-bit signed integer.
21820 **
21821 ** If the zNum value is representable as a 64-bit twos-complement 
21822 ** integer, then write that value into *pNum and return 0.
21823 **
21824 ** If zNum is exactly 9223372036854775808, return 2.  This special
21825 ** case is broken out because while 9223372036854775808 cannot be a 
21826 ** signed 64-bit integer, its negative -9223372036854775808 can be.
21827 **
21828 ** If zNum is too big for a 64-bit integer and is not
21829 ** 9223372036854775808  or if zNum contains any non-numeric text,
21830 ** then return 1.
21831 **
21832 ** length is the number of bytes in the string (bytes, not characters).
21833 ** The string is not necessarily zero-terminated.  The encoding is
21834 ** given by enc.
21835 */
21836 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21837   int incr;
21838   u64 u = 0;
21839   int neg = 0; /* assume positive */
21840   int i;
21841   int c = 0;
21842   int nonNum = 0;
21843   const char *zStart;
21844   const char *zEnd = zNum + length;
21845   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21846   if( enc==SQLITE_UTF8 ){
21847     incr = 1;
21848   }else{
21849     incr = 2;
21850     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21851     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21852     nonNum = i<length;
21853     zEnd = zNum+i+enc-3;
21854     zNum += (enc&1);
21855   }
21856   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21857   if( zNum<zEnd ){
21858     if( *zNum=='-' ){
21859       neg = 1;
21860       zNum+=incr;
21861     }else if( *zNum=='+' ){
21862       zNum+=incr;
21863     }
21864   }
21865   zStart = zNum;
21866   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21867   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21868     u = u*10 + c - '0';
21869   }
21870   if( u>LARGEST_INT64 ){
21871     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
21872   }else if( neg ){
21873     *pNum = -(i64)u;
21874   }else{
21875     *pNum = (i64)u;
21876   }
21877   testcase( i==18 );
21878   testcase( i==19 );
21879   testcase( i==20 );
21880   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21881     /* zNum is empty or contains non-numeric text or is longer
21882     ** than 19 digits (thus guaranteeing that it is too large) */
21883     return 1;
21884   }else if( i<19*incr ){
21885     /* Less than 19 digits, so we know that it fits in 64 bits */
21886     assert( u<=LARGEST_INT64 );
21887     return 0;
21888   }else{
21889     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21890     c = compare2pow63(zNum, incr);
21891     if( c<0 ){
21892       /* zNum is less than 9223372036854775808 so it fits */
21893       assert( u<=LARGEST_INT64 );
21894       return 0;
21895     }else if( c>0 ){
21896       /* zNum is greater than 9223372036854775808 so it overflows */
21897       return 1;
21898     }else{
21899       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21900       ** special case 2 overflow if positive */
21901       assert( u-1==LARGEST_INT64 );
21902       return neg ? 0 : 2;
21903     }
21904   }
21905 }
21906 
21907 /*
21908 ** If zNum represents an integer that will fit in 32-bits, then set
21909 ** *pValue to that integer and return true.  Otherwise return false.
21910 **
21911 ** Any non-numeric characters that following zNum are ignored.
21912 ** This is different from sqlite3Atoi64() which requires the
21913 ** input number to be zero-terminated.
21914 */
21915 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21916   sqlite_int64 v = 0;
21917   int i, c;
21918   int neg = 0;
21919   if( zNum[0]=='-' ){
21920     neg = 1;
21921     zNum++;
21922   }else if( zNum[0]=='+' ){
21923     zNum++;
21924   }
21925   while( zNum[0]=='0' ) zNum++;
21926   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21927     v = v*10 + c;
21928   }
21929 
21930   /* The longest decimal representation of a 32 bit integer is 10 digits:
21931   **
21932   **             1234567890
21933   **     2^31 -> 2147483648
21934   */
21935   testcase( i==10 );
21936   if( i>10 ){
21937     return 0;
21938   }
21939   testcase( v-neg==2147483647 );
21940   if( v-neg>2147483647 ){
21941     return 0;
21942   }
21943   if( neg ){
21944     v = -v;
21945   }
21946   *pValue = (int)v;
21947   return 1;
21948 }
21949 
21950 /*
21951 ** Return a 32-bit integer value extracted from a string.  If the
21952 ** string is not an integer, just return 0.
21953 */
21954 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21955   int x = 0;
21956   if( z ) sqlite3GetInt32(z, &x);
21957   return x;
21958 }
21959 
21960 /*
21961 ** The variable-length integer encoding is as follows:
21962 **
21963 ** KEY:
21964 **         A = 0xxxxxxx    7 bits of data and one flag bit
21965 **         B = 1xxxxxxx    7 bits of data and one flag bit
21966 **         C = xxxxxxxx    8 bits of data
21967 **
21968 **  7 bits - A
21969 ** 14 bits - BA
21970 ** 21 bits - BBA
21971 ** 28 bits - BBBA
21972 ** 35 bits - BBBBA
21973 ** 42 bits - BBBBBA
21974 ** 49 bits - BBBBBBA
21975 ** 56 bits - BBBBBBBA
21976 ** 64 bits - BBBBBBBBC
21977 */
21978 
21979 /*
21980 ** Write a 64-bit variable-length integer to memory starting at p[0].
21981 ** The length of data write will be between 1 and 9 bytes.  The number
21982 ** of bytes written is returned.
21983 **
21984 ** A variable-length integer consists of the lower 7 bits of each byte
21985 ** for all bytes that have the 8th bit set and one byte with the 8th
21986 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21987 ** 8 bits and is the last byte.
21988 */
21989 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21990   int i, j, n;
21991   u8 buf[10];
21992   if( v & (((u64)0xff000000)<<32) ){
21993     p[8] = (u8)v;
21994     v >>= 8;
21995     for(i=7; i>=0; i--){
21996       p[i] = (u8)((v & 0x7f) | 0x80);
21997       v >>= 7;
21998     }
21999     return 9;
22000   }    
22001   n = 0;
22002   do{
22003     buf[n++] = (u8)((v & 0x7f) | 0x80);
22004     v >>= 7;
22005   }while( v!=0 );
22006   buf[0] &= 0x7f;
22007   assert( n<=9 );
22008   for(i=0, j=n-1; j>=0; j--, i++){
22009     p[i] = buf[j];
22010   }
22011   return n;
22012 }
22013 
22014 /*
22015 ** This routine is a faster version of sqlite3PutVarint() that only
22016 ** works for 32-bit positive integers and which is optimized for
22017 ** the common case of small integers.  A MACRO version, putVarint32,
22018 ** is provided which inlines the single-byte case.  All code should use
22019 ** the MACRO version as this function assumes the single-byte case has
22020 ** already been handled.
22021 */
22022 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
22023 #ifndef putVarint32
22024   if( (v & ~0x7f)==0 ){
22025     p[0] = v;
22026     return 1;
22027   }
22028 #endif
22029   if( (v & ~0x3fff)==0 ){
22030     p[0] = (u8)((v>>7) | 0x80);
22031     p[1] = (u8)(v & 0x7f);
22032     return 2;
22033   }
22034   return sqlite3PutVarint(p, v);
22035 }
22036 
22037 /*
22038 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
22039 ** are defined here rather than simply putting the constant expressions
22040 ** inline in order to work around bugs in the RVT compiler.
22041 **
22042 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
22043 **
22044 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
22045 */
22046 #define SLOT_2_0     0x001fc07f
22047 #define SLOT_4_2_0   0xf01fc07f
22048 
22049 
22050 /*
22051 ** Read a 64-bit variable-length integer from memory starting at p[0].
22052 ** Return the number of bytes read.  The value is stored in *v.
22053 */
22054 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
22055   u32 a,b,s;
22056 
22057   a = *p;
22058   /* a: p0 (unmasked) */
22059   if (!(a&0x80))
22060   {
22061     *v = a;
22062     return 1;
22063   }
22064 
22065   p++;
22066   b = *p;
22067   /* b: p1 (unmasked) */
22068   if (!(b&0x80))
22069   {
22070     a &= 0x7f;
22071     a = a<<7;
22072     a |= b;
22073     *v = a;
22074     return 2;
22075   }
22076 
22077   /* Verify that constants are precomputed correctly */
22078   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
22079   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
22080 
22081   p++;
22082   a = a<<14;
22083   a |= *p;
22084   /* a: p0<<14 | p2 (unmasked) */
22085   if (!(a&0x80))
22086   {
22087     a &= SLOT_2_0;
22088     b &= 0x7f;
22089     b = b<<7;
22090     a |= b;
22091     *v = a;
22092     return 3;
22093   }
22094 
22095   /* CSE1 from below */
22096   a &= SLOT_2_0;
22097   p++;
22098   b = b<<14;
22099   b |= *p;
22100   /* b: p1<<14 | p3 (unmasked) */
22101   if (!(b&0x80))
22102   {
22103     b &= SLOT_2_0;
22104     /* moved CSE1 up */
22105     /* a &= (0x7f<<14)|(0x7f); */
22106     a = a<<7;
22107     a |= b;
22108     *v = a;
22109     return 4;
22110   }
22111 
22112   /* a: p0<<14 | p2 (masked) */
22113   /* b: p1<<14 | p3 (unmasked) */
22114   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22115   /* moved CSE1 up */
22116   /* a &= (0x7f<<14)|(0x7f); */
22117   b &= SLOT_2_0;
22118   s = a;
22119   /* s: p0<<14 | p2 (masked) */
22120 
22121   p++;
22122   a = a<<14;
22123   a |= *p;
22124   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22125   if (!(a&0x80))
22126   {
22127     /* we can skip these cause they were (effectively) done above in calc'ing s */
22128     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22129     /* b &= (0x7f<<14)|(0x7f); */
22130     b = b<<7;
22131     a |= b;
22132     s = s>>18;
22133     *v = ((u64)s)<<32 | a;
22134     return 5;
22135   }
22136 
22137   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22138   s = s<<7;
22139   s |= b;
22140   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22141 
22142   p++;
22143   b = b<<14;
22144   b |= *p;
22145   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
22146   if (!(b&0x80))
22147   {
22148     /* we can skip this cause it was (effectively) done above in calc'ing s */
22149     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22150     a &= SLOT_2_0;
22151     a = a<<7;
22152     a |= b;
22153     s = s>>18;
22154     *v = ((u64)s)<<32 | a;
22155     return 6;
22156   }
22157 
22158   p++;
22159   a = a<<14;
22160   a |= *p;
22161   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
22162   if (!(a&0x80))
22163   {
22164     a &= SLOT_4_2_0;
22165     b &= SLOT_2_0;
22166     b = b<<7;
22167     a |= b;
22168     s = s>>11;
22169     *v = ((u64)s)<<32 | a;
22170     return 7;
22171   }
22172 
22173   /* CSE2 from below */
22174   a &= SLOT_2_0;
22175   p++;
22176   b = b<<14;
22177   b |= *p;
22178   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22179   if (!(b&0x80))
22180   {
22181     b &= SLOT_4_2_0;
22182     /* moved CSE2 up */
22183     /* a &= (0x7f<<14)|(0x7f); */
22184     a = a<<7;
22185     a |= b;
22186     s = s>>4;
22187     *v = ((u64)s)<<32 | a;
22188     return 8;
22189   }
22190 
22191   p++;
22192   a = a<<15;
22193   a |= *p;
22194   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22195 
22196   /* moved CSE2 up */
22197   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22198   b &= SLOT_2_0;
22199   b = b<<8;
22200   a |= b;
22201 
22202   s = s<<4;
22203   b = p[-4];
22204   b &= 0x7f;
22205   b = b>>3;
22206   s |= b;
22207 
22208   *v = ((u64)s)<<32 | a;
22209 
22210   return 9;
22211 }
22212 
22213 /*
22214 ** Read a 32-bit variable-length integer from memory starting at p[0].
22215 ** Return the number of bytes read.  The value is stored in *v.
22216 **
22217 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22218 ** integer, then set *v to 0xffffffff.
22219 **
22220 ** A MACRO version, getVarint32, is provided which inlines the 
22221 ** single-byte case.  All code should use the MACRO version as 
22222 ** this function assumes the single-byte case has already been handled.
22223 */
22224 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22225   u32 a,b;
22226 
22227   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
22228   ** by the getVarin32() macro */
22229   a = *p;
22230   /* a: p0 (unmasked) */
22231 #ifndef getVarint32
22232   if (!(a&0x80))
22233   {
22234     /* Values between 0 and 127 */
22235     *v = a;
22236     return 1;
22237   }
22238 #endif
22239 
22240   /* The 2-byte case */
22241   p++;
22242   b = *p;
22243   /* b: p1 (unmasked) */
22244   if (!(b&0x80))
22245   {
22246     /* Values between 128 and 16383 */
22247     a &= 0x7f;
22248     a = a<<7;
22249     *v = a | b;
22250     return 2;
22251   }
22252 
22253   /* The 3-byte case */
22254   p++;
22255   a = a<<14;
22256   a |= *p;
22257   /* a: p0<<14 | p2 (unmasked) */
22258   if (!(a&0x80))
22259   {
22260     /* Values between 16384 and 2097151 */
22261     a &= (0x7f<<14)|(0x7f);
22262     b &= 0x7f;
22263     b = b<<7;
22264     *v = a | b;
22265     return 3;
22266   }
22267 
22268   /* A 32-bit varint is used to store size information in btrees.
22269   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22270   ** A 3-byte varint is sufficient, for example, to record the size
22271   ** of a 1048569-byte BLOB or string.
22272   **
22273   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
22274   ** rare larger cases can be handled by the slower 64-bit varint
22275   ** routine.
22276   */
22277 #if 1
22278   {
22279     u64 v64;
22280     u8 n;
22281 
22282     p -= 2;
22283     n = sqlite3GetVarint(p, &v64);
22284     assert( n>3 && n<=9 );
22285     if( (v64 & SQLITE_MAX_U32)!=v64 ){
22286       *v = 0xffffffff;
22287     }else{
22288       *v = (u32)v64;
22289     }
22290     return n;
22291   }
22292 
22293 #else
22294   /* For following code (kept for historical record only) shows an
22295   ** unrolling for the 3- and 4-byte varint cases.  This code is
22296   ** slightly faster, but it is also larger and much harder to test.
22297   */
22298   p++;
22299   b = b<<14;
22300   b |= *p;
22301   /* b: p1<<14 | p3 (unmasked) */
22302   if (!(b&0x80))
22303   {
22304     /* Values between 2097152 and 268435455 */
22305     b &= (0x7f<<14)|(0x7f);
22306     a &= (0x7f<<14)|(0x7f);
22307     a = a<<7;
22308     *v = a | b;
22309     return 4;
22310   }
22311 
22312   p++;
22313   a = a<<14;
22314   a |= *p;
22315   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22316   if (!(a&0x80))
22317   {
22318     /* Values  between 268435456 and 34359738367 */
22319     a &= SLOT_4_2_0;
22320     b &= SLOT_4_2_0;
22321     b = b<<7;
22322     *v = a | b;
22323     return 5;
22324   }
22325 
22326   /* We can only reach this point when reading a corrupt database
22327   ** file.  In that case we are not in any hurry.  Use the (relatively
22328   ** slow) general-purpose sqlite3GetVarint() routine to extract the
22329   ** value. */
22330   {
22331     u64 v64;
22332     u8 n;
22333 
22334     p -= 4;
22335     n = sqlite3GetVarint(p, &v64);
22336     assert( n>5 && n<=9 );
22337     *v = (u32)v64;
22338     return n;
22339   }
22340 #endif
22341 }
22342 
22343 /*
22344 ** Return the number of bytes that will be needed to store the given
22345 ** 64-bit integer.
22346 */
22347 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22348   int i = 0;
22349   do{
22350     i++;
22351     v >>= 7;
22352   }while( v!=0 && ALWAYS(i<9) );
22353   return i;
22354 }
22355 
22356 
22357 /*
22358 ** Read or write a four-byte big-endian integer value.
22359 */
22360 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22361   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22362 }
22363 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22364   p[0] = (u8)(v>>24);
22365   p[1] = (u8)(v>>16);
22366   p[2] = (u8)(v>>8);
22367   p[3] = (u8)v;
22368 }
22369 
22370 
22371 
22372 /*
22373 ** Translate a single byte of Hex into an integer.
22374 ** This routine only works if h really is a valid hexadecimal
22375 ** character:  0..9a..fA..F
22376 */
22377 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22378   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22379 #ifdef SQLITE_ASCII
22380   h += 9*(1&(h>>6));
22381 #endif
22382 #ifdef SQLITE_EBCDIC
22383   h += 9*(1&~(h>>4));
22384 #endif
22385   return (u8)(h & 0xf);
22386 }
22387 
22388 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22389 /*
22390 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22391 ** value.  Return a pointer to its binary value.  Space to hold the
22392 ** binary value has been obtained from malloc and must be freed by
22393 ** the calling routine.
22394 */
22395 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22396   char *zBlob;
22397   int i;
22398 
22399   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22400   n--;
22401   if( zBlob ){
22402     for(i=0; i<n; i+=2){
22403       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22404     }
22405     zBlob[i/2] = 0;
22406   }
22407   return zBlob;
22408 }
22409 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22410 
22411 /*
22412 ** Log an error that is an API call on a connection pointer that should
22413 ** not have been used.  The "type" of connection pointer is given as the
22414 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22415 */
22416 static void logBadConnection(const char *zType){
22417   sqlite3_log(SQLITE_MISUSE, 
22418      "API call with %s database connection pointer",
22419      zType
22420   );
22421 }
22422 
22423 /*
22424 ** Check to make sure we have a valid db pointer.  This test is not
22425 ** foolproof but it does provide some measure of protection against
22426 ** misuse of the interface such as passing in db pointers that are
22427 ** NULL or which have been previously closed.  If this routine returns
22428 ** 1 it means that the db pointer is valid and 0 if it should not be
22429 ** dereferenced for any reason.  The calling function should invoke
22430 ** SQLITE_MISUSE immediately.
22431 **
22432 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22433 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22434 ** open properly and is not fit for general use but which can be
22435 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22436 */
22437 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22438   u32 magic;
22439   if( db==0 ){
22440     logBadConnection("NULL");
22441     return 0;
22442   }
22443   magic = db->magic;
22444   if( magic!=SQLITE_MAGIC_OPEN ){
22445     if( sqlite3SafetyCheckSickOrOk(db) ){
22446       testcase( sqlite3GlobalConfig.xLog!=0 );
22447       logBadConnection("unopened");
22448     }
22449     return 0;
22450   }else{
22451     return 1;
22452   }
22453 }
22454 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22455   u32 magic;
22456   magic = db->magic;
22457   if( magic!=SQLITE_MAGIC_SICK &&
22458       magic!=SQLITE_MAGIC_OPEN &&
22459       magic!=SQLITE_MAGIC_BUSY ){
22460     testcase( sqlite3GlobalConfig.xLog!=0 );
22461     logBadConnection("invalid");
22462     return 0;
22463   }else{
22464     return 1;
22465   }
22466 }
22467 
22468 /*
22469 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22470 ** the other 64-bit signed integer at *pA and store the result in *pA.
22471 ** Return 0 on success.  Or if the operation would have resulted in an
22472 ** overflow, leave *pA unchanged and return 1.
22473 */
22474 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22475   i64 iA = *pA;
22476   testcase( iA==0 ); testcase( iA==1 );
22477   testcase( iB==-1 ); testcase( iB==0 );
22478   if( iB>=0 ){
22479     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22480     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22481     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22482     *pA += iB;
22483   }else{
22484     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22485     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22486     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22487     *pA += iB;
22488   }
22489   return 0; 
22490 }
22491 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22492   testcase( iB==SMALLEST_INT64+1 );
22493   if( iB==SMALLEST_INT64 ){
22494     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22495     if( (*pA)>=0 ) return 1;
22496     *pA -= iB;
22497     return 0;
22498   }else{
22499     return sqlite3AddInt64(pA, -iB);
22500   }
22501 }
22502 #define TWOPOWER32 (((i64)1)<<32)
22503 #define TWOPOWER31 (((i64)1)<<31)
22504 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22505   i64 iA = *pA;
22506   i64 iA1, iA0, iB1, iB0, r;
22507 
22508   iA1 = iA/TWOPOWER32;
22509   iA0 = iA % TWOPOWER32;
22510   iB1 = iB/TWOPOWER32;
22511   iB0 = iB % TWOPOWER32;
22512   if( iA1*iB1 != 0 ) return 1;
22513   assert( iA1*iB0==0 || iA0*iB1==0 );
22514   r = iA1*iB0 + iA0*iB1;
22515   testcase( r==(-TWOPOWER31)-1 );
22516   testcase( r==(-TWOPOWER31) );
22517   testcase( r==TWOPOWER31 );
22518   testcase( r==TWOPOWER31-1 );
22519   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22520   r *= TWOPOWER32;
22521   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22522   *pA = r;
22523   return 0;
22524 }
22525 
22526 /*
22527 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22528 ** if the integer has a value of -2147483648, return +2147483647
22529 */
22530 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22531   if( x>=0 ) return x;
22532   if( x==(int)0x80000000 ) return 0x7fffffff;
22533   return -x;
22534 }
22535 
22536 #ifdef SQLITE_ENABLE_8_3_NAMES
22537 /*
22538 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22539 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22540 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22541 ** three characters, then shorten the suffix on z[] to be the last three
22542 ** characters of the original suffix.
22543 **
22544 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22545 ** do the suffix shortening regardless of URI parameter.
22546 **
22547 ** Examples:
22548 **
22549 **     test.db-journal    =>   test.nal
22550 **     test.db-wal        =>   test.wal
22551 **     test.db-shm        =>   test.shm
22552 **     test.db-mj7f3319fa =>   test.9fa
22553 */
22554 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22555 #if SQLITE_ENABLE_8_3_NAMES<2
22556   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22557 #endif
22558   {
22559     int i, sz;
22560     sz = sqlite3Strlen30(z);
22561     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22562     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22563   }
22564 }
22565 #endif
22566 
22567 /* 
22568 ** Find (an approximate) sum of two LogEst values.  This computation is
22569 ** not a simple "+" operator because LogEst is stored as a logarithmic
22570 ** value.
22571 ** 
22572 */
22573 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
22574   static const unsigned char x[] = {
22575      10, 10,                         /* 0,1 */
22576       9, 9,                          /* 2,3 */
22577       8, 8,                          /* 4,5 */
22578       7, 7, 7,                       /* 6,7,8 */
22579       6, 6, 6,                       /* 9,10,11 */
22580       5, 5, 5,                       /* 12-14 */
22581       4, 4, 4, 4,                    /* 15-18 */
22582       3, 3, 3, 3, 3, 3,              /* 19-24 */
22583       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
22584   };
22585   if( a>=b ){
22586     if( a>b+49 ) return a;
22587     if( a>b+31 ) return a+1;
22588     return a+x[a-b];
22589   }else{
22590     if( b>a+49 ) return b;
22591     if( b>a+31 ) return b+1;
22592     return b+x[b-a];
22593   }
22594 }
22595 
22596 /*
22597 ** Convert an integer into a LogEst.  In other words, compute a
22598 ** good approximatation for 10*log2(x).
22599 */
22600 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
22601   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
22602   LogEst y = 40;
22603   if( x<8 ){
22604     if( x<2 ) return 0;
22605     while( x<8 ){  y -= 10; x <<= 1; }
22606   }else{
22607     while( x>255 ){ y += 40; x >>= 4; }
22608     while( x>15 ){  y += 10; x >>= 1; }
22609   }
22610   return a[x&7] + y - 10;
22611 }
22612 
22613 #ifndef SQLITE_OMIT_VIRTUALTABLE
22614 /*
22615 ** Convert a double into a LogEst
22616 ** In other words, compute an approximation for 10*log2(x).
22617 */
22618 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
22619   u64 a;
22620   LogEst e;
22621   assert( sizeof(x)==8 && sizeof(a)==8 );
22622   if( x<=1 ) return 0;
22623   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
22624   memcpy(&a, &x, 8);
22625   e = (a>>52) - 1022;
22626   return e*10;
22627 }
22628 #endif /* SQLITE_OMIT_VIRTUALTABLE */
22629 
22630 /*
22631 ** Convert a LogEst into an integer.
22632 */
22633 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
22634   u64 n;
22635   if( x<10 ) return 1;
22636   n = x%10;
22637   x /= 10;
22638   if( n>=5 ) n -= 2;
22639   else if( n>=1 ) n -= 1;
22640   if( x>=3 ){
22641     return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
22642   }
22643   return (n+8)>>(3-x);
22644 }
22645 
22646 /************** End of util.c ************************************************/
22647 /************** Begin file hash.c ********************************************/
22648 /*
22649 ** 2001 September 22
22650 **
22651 ** The author disclaims copyright to this source code.  In place of
22652 ** a legal notice, here is a blessing:
22653 **
22654 **    May you do good and not evil.
22655 **    May you find forgiveness for yourself and forgive others.
22656 **    May you share freely, never taking more than you give.
22657 **
22658 *************************************************************************
22659 ** This is the implementation of generic hash-tables
22660 ** used in SQLite.
22661 */
22662 /* #include <assert.h> */
22663 
22664 /* Turn bulk memory into a hash table object by initializing the
22665 ** fields of the Hash structure.
22666 **
22667 ** "pNew" is a pointer to the hash table that is to be initialized.
22668 */
22669 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22670   assert( pNew!=0 );
22671   pNew->first = 0;
22672   pNew->count = 0;
22673   pNew->htsize = 0;
22674   pNew->ht = 0;
22675 }
22676 
22677 /* Remove all entries from a hash table.  Reclaim all memory.
22678 ** Call this routine to delete a hash table or to reset a hash table
22679 ** to the empty state.
22680 */
22681 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22682   HashElem *elem;         /* For looping over all elements of the table */
22683 
22684   assert( pH!=0 );
22685   elem = pH->first;
22686   pH->first = 0;
22687   sqlite3_free(pH->ht);
22688   pH->ht = 0;
22689   pH->htsize = 0;
22690   while( elem ){
22691     HashElem *next_elem = elem->next;
22692     sqlite3_free(elem);
22693     elem = next_elem;
22694   }
22695   pH->count = 0;
22696 }
22697 
22698 /*
22699 ** The hashing function.
22700 */
22701 static unsigned int strHash(const char *z, int nKey){
22702   int h = 0;
22703   assert( nKey>=0 );
22704   while( nKey > 0  ){
22705     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22706     nKey--;
22707   }
22708   return h;
22709 }
22710 
22711 
22712 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22713 ** insert pNew into the pEntry hash bucket.
22714 */
22715 static void insertElement(
22716   Hash *pH,              /* The complete hash table */
22717   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22718   HashElem *pNew         /* The element to be inserted */
22719 ){
22720   HashElem *pHead;       /* First element already in pEntry */
22721   if( pEntry ){
22722     pHead = pEntry->count ? pEntry->chain : 0;
22723     pEntry->count++;
22724     pEntry->chain = pNew;
22725   }else{
22726     pHead = 0;
22727   }
22728   if( pHead ){
22729     pNew->next = pHead;
22730     pNew->prev = pHead->prev;
22731     if( pHead->prev ){ pHead->prev->next = pNew; }
22732     else             { pH->first = pNew; }
22733     pHead->prev = pNew;
22734   }else{
22735     pNew->next = pH->first;
22736     if( pH->first ){ pH->first->prev = pNew; }
22737     pNew->prev = 0;
22738     pH->first = pNew;
22739   }
22740 }
22741 
22742 
22743 /* Resize the hash table so that it cantains "new_size" buckets.
22744 **
22745 ** The hash table might fail to resize if sqlite3_malloc() fails or
22746 ** if the new size is the same as the prior size.
22747 ** Return TRUE if the resize occurs and false if not.
22748 */
22749 static int rehash(Hash *pH, unsigned int new_size){
22750   struct _ht *new_ht;            /* The new hash table */
22751   HashElem *elem, *next_elem;    /* For looping over existing elements */
22752 
22753 #if SQLITE_MALLOC_SOFT_LIMIT>0
22754   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22755     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22756   }
22757   if( new_size==pH->htsize ) return 0;
22758 #endif
22759 
22760   /* The inability to allocates space for a larger hash table is
22761   ** a performance hit but it is not a fatal error.  So mark the
22762   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
22763   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22764   ** only zeroes the requested number of bytes whereas this module will
22765   ** use the actual amount of space allocated for the hash table (which
22766   ** may be larger than the requested amount).
22767   */
22768   sqlite3BeginBenignMalloc();
22769   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22770   sqlite3EndBenignMalloc();
22771 
22772   if( new_ht==0 ) return 0;
22773   sqlite3_free(pH->ht);
22774   pH->ht = new_ht;
22775   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22776   memset(new_ht, 0, new_size*sizeof(struct _ht));
22777   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22778     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22779     next_elem = elem->next;
22780     insertElement(pH, &new_ht[h], elem);
22781   }
22782   return 1;
22783 }
22784 
22785 /* This function (for internal use only) locates an element in an
22786 ** hash table that matches the given key.  The hash for this key has
22787 ** already been computed and is passed as the 4th parameter.
22788 */
22789 static HashElem *findElementGivenHash(
22790   const Hash *pH,     /* The pH to be searched */
22791   const char *pKey,   /* The key we are searching for */
22792   int nKey,           /* Bytes in key (not counting zero terminator) */
22793   unsigned int h      /* The hash for this key. */
22794 ){
22795   HashElem *elem;                /* Used to loop thru the element list */
22796   int count;                     /* Number of elements left to test */
22797 
22798   if( pH->ht ){
22799     struct _ht *pEntry = &pH->ht[h];
22800     elem = pEntry->chain;
22801     count = pEntry->count;
22802   }else{
22803     elem = pH->first;
22804     count = pH->count;
22805   }
22806   while( count-- && ALWAYS(elem) ){
22807     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22808       return elem;
22809     }
22810     elem = elem->next;
22811   }
22812   return 0;
22813 }
22814 
22815 /* Remove a single entry from the hash table given a pointer to that
22816 ** element and a hash on the element's key.
22817 */
22818 static void removeElementGivenHash(
22819   Hash *pH,         /* The pH containing "elem" */
22820   HashElem* elem,   /* The element to be removed from the pH */
22821   unsigned int h    /* Hash value for the element */
22822 ){
22823   struct _ht *pEntry;
22824   if( elem->prev ){
22825     elem->prev->next = elem->next; 
22826   }else{
22827     pH->first = elem->next;
22828   }
22829   if( elem->next ){
22830     elem->next->prev = elem->prev;
22831   }
22832   if( pH->ht ){
22833     pEntry = &pH->ht[h];
22834     if( pEntry->chain==elem ){
22835       pEntry->chain = elem->next;
22836     }
22837     pEntry->count--;
22838     assert( pEntry->count>=0 );
22839   }
22840   sqlite3_free( elem );
22841   pH->count--;
22842   if( pH->count==0 ){
22843     assert( pH->first==0 );
22844     assert( pH->count==0 );
22845     sqlite3HashClear(pH);
22846   }
22847 }
22848 
22849 /* Attempt to locate an element of the hash table pH with a key
22850 ** that matches pKey,nKey.  Return the data for this element if it is
22851 ** found, or NULL if there is no match.
22852 */
22853 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22854   HashElem *elem;    /* The element that matches key */
22855   unsigned int h;    /* A hash on key */
22856 
22857   assert( pH!=0 );
22858   assert( pKey!=0 );
22859   assert( nKey>=0 );
22860   if( pH->ht ){
22861     h = strHash(pKey, nKey) % pH->htsize;
22862   }else{
22863     h = 0;
22864   }
22865   elem = findElementGivenHash(pH, pKey, nKey, h);
22866   return elem ? elem->data : 0;
22867 }
22868 
22869 /* Insert an element into the hash table pH.  The key is pKey,nKey
22870 ** and the data is "data".
22871 **
22872 ** If no element exists with a matching key, then a new
22873 ** element is created and NULL is returned.
22874 **
22875 ** If another element already exists with the same key, then the
22876 ** new data replaces the old data and the old data is returned.
22877 ** The key is not copied in this instance.  If a malloc fails, then
22878 ** the new data is returned and the hash table is unchanged.
22879 **
22880 ** If the "data" parameter to this function is NULL, then the
22881 ** element corresponding to "key" is removed from the hash table.
22882 */
22883 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22884   unsigned int h;       /* the hash of the key modulo hash table size */
22885   HashElem *elem;       /* Used to loop thru the element list */
22886   HashElem *new_elem;   /* New element added to the pH */
22887 
22888   assert( pH!=0 );
22889   assert( pKey!=0 );
22890   assert( nKey>=0 );
22891   if( pH->htsize ){
22892     h = strHash(pKey, nKey) % pH->htsize;
22893   }else{
22894     h = 0;
22895   }
22896   elem = findElementGivenHash(pH,pKey,nKey,h);
22897   if( elem ){
22898     void *old_data = elem->data;
22899     if( data==0 ){
22900       removeElementGivenHash(pH,elem,h);
22901     }else{
22902       elem->data = data;
22903       elem->pKey = pKey;
22904       assert(nKey==elem->nKey);
22905     }
22906     return old_data;
22907   }
22908   if( data==0 ) return 0;
22909   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22910   if( new_elem==0 ) return data;
22911   new_elem->pKey = pKey;
22912   new_elem->nKey = nKey;
22913   new_elem->data = data;
22914   pH->count++;
22915   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22916     if( rehash(pH, pH->count*2) ){
22917       assert( pH->htsize>0 );
22918       h = strHash(pKey, nKey) % pH->htsize;
22919     }
22920   }
22921   if( pH->ht ){
22922     insertElement(pH, &pH->ht[h], new_elem);
22923   }else{
22924     insertElement(pH, 0, new_elem);
22925   }
22926   return 0;
22927 }
22928 
22929 /************** End of hash.c ************************************************/
22930 /************** Begin file opcodes.c *****************************************/
22931 /* Automatically generated.  Do not edit */
22932 /* See the mkopcodec.awk script for details. */
22933 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22934 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
22935 # define OpHelp(X) "\0" X
22936 #else
22937 # define OpHelp(X)
22938 #endif
22939 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22940  static const char *const azName[] = { "?",
22941      /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
22942      /*   2 */ "Savepoint"        OpHelp(""),
22943      /*   3 */ "AutoCommit"       OpHelp(""),
22944      /*   4 */ "Transaction"      OpHelp(""),
22945      /*   5 */ "SorterNext"       OpHelp(""),
22946      /*   6 */ "PrevIfOpen"       OpHelp(""),
22947      /*   7 */ "NextIfOpen"       OpHelp(""),
22948      /*   8 */ "Prev"             OpHelp(""),
22949      /*   9 */ "Next"             OpHelp(""),
22950      /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
22951      /*  11 */ "Checkpoint"       OpHelp(""),
22952      /*  12 */ "JournalMode"      OpHelp(""),
22953      /*  13 */ "Vacuum"           OpHelp(""),
22954      /*  14 */ "VFilter"          OpHelp("iPlan=r[P3] zPlan='P4'"),
22955      /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
22956      /*  16 */ "Goto"             OpHelp(""),
22957      /*  17 */ "Gosub"            OpHelp(""),
22958      /*  18 */ "Return"           OpHelp(""),
22959      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
22960      /*  20 */ "Yield"            OpHelp(""),
22961      /*  21 */ "HaltIfNull"       OpHelp("if r[P3] null then halt"),
22962      /*  22 */ "Halt"             OpHelp(""),
22963      /*  23 */ "Integer"          OpHelp("r[P2]=P1"),
22964      /*  24 */ "Int64"            OpHelp("r[P2]=P4"),
22965      /*  25 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
22966      /*  26 */ "Null"             OpHelp("r[P2..P3]=NULL"),
22967      /*  27 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
22968      /*  28 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
22969      /*  29 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
22970      /*  30 */ "Copy"             OpHelp("r[P2@P3]=r[P1@P3]"),
22971      /*  31 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
22972      /*  32 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
22973      /*  33 */ "CollSeq"          OpHelp(""),
22974      /*  34 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
22975      /*  35 */ "MustBeInt"        OpHelp(""),
22976      /*  36 */ "RealAffinity"     OpHelp(""),
22977      /*  37 */ "Permutation"      OpHelp(""),
22978      /*  38 */ "Compare"          OpHelp(""),
22979      /*  39 */ "Jump"             OpHelp(""),
22980      /*  40 */ "Once"             OpHelp(""),
22981      /*  41 */ "If"               OpHelp(""),
22982      /*  42 */ "IfNot"            OpHelp(""),
22983      /*  43 */ "Column"           OpHelp("r[P3]=PX"),
22984      /*  44 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
22985      /*  45 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
22986      /*  46 */ "Count"            OpHelp("r[P2]=count()"),
22987      /*  47 */ "ReadCookie"       OpHelp(""),
22988      /*  48 */ "SetCookie"        OpHelp(""),
22989      /*  49 */ "VerifyCookie"     OpHelp(""),
22990      /*  50 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
22991      /*  51 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
22992      /*  52 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
22993      /*  53 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
22994      /*  54 */ "SorterOpen"       OpHelp(""),
22995      /*  55 */ "OpenPseudo"       OpHelp("content in r[P2@P3]"),
22996      /*  56 */ "Close"            OpHelp(""),
22997      /*  57 */ "SeekLt"           OpHelp("key=r[P3@P4]"),
22998      /*  58 */ "SeekLe"           OpHelp("key=r[P3@P4]"),
22999      /*  59 */ "SeekGe"           OpHelp("key=r[P3@P4]"),
23000      /*  60 */ "SeekGt"           OpHelp("key=r[P3@P4]"),
23001      /*  61 */ "Seek"             OpHelp("intkey=r[P2]"),
23002      /*  62 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
23003      /*  63 */ "NotFound"         OpHelp("key=r[P3@P4]"),
23004      /*  64 */ "Found"            OpHelp("key=r[P3@P4]"),
23005      /*  65 */ "NotExists"        OpHelp("intkey=r[P3]"),
23006      /*  66 */ "Sequence"         OpHelp("r[P2]=rowid"),
23007      /*  67 */ "NewRowid"         OpHelp("r[P2]=rowid"),
23008      /*  68 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
23009      /*  69 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
23010      /*  70 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
23011      /*  71 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
23012      /*  72 */ "Delete"           OpHelp(""),
23013      /*  73 */ "ResetCount"       OpHelp(""),
23014      /*  74 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
23015      /*  75 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
23016      /*  76 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
23017      /*  77 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
23018      /*  78 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
23019      /*  79 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
23020      /*  80 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
23021      /*  81 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
23022      /*  82 */ "SorterCompare"    OpHelp("if key(P1)!=rtrim(r[P3],P4) goto P2"),
23023      /*  83 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
23024      /*  84 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
23025      /*  85 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
23026      /*  86 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
23027      /*  87 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
23028      /*  88 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
23029      /*  89 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
23030      /*  90 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
23031      /*  91 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
23032      /*  92 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
23033      /*  93 */ "SorterData"       OpHelp("r[P2]=data"),
23034      /*  94 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
23035      /*  95 */ "String8"          OpHelp("r[P2]='P4'"),
23036      /*  96 */ "RowKey"           OpHelp("r[P2]=key"),
23037      /*  97 */ "RowData"          OpHelp("r[P2]=data"),
23038      /*  98 */ "Rowid"            OpHelp("r[P2]=rowid"),
23039      /*  99 */ "NullRow"          OpHelp(""),
23040      /* 100 */ "Last"             OpHelp(""),
23041      /* 101 */ "SorterSort"       OpHelp(""),
23042      /* 102 */ "Sort"             OpHelp(""),
23043      /* 103 */ "Rewind"           OpHelp(""),
23044      /* 104 */ "SorterInsert"     OpHelp(""),
23045      /* 105 */ "IdxInsert"        OpHelp("key=r[P2]"),
23046      /* 106 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
23047      /* 107 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
23048      /* 108 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
23049      /* 109 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
23050      /* 110 */ "Destroy"          OpHelp(""),
23051      /* 111 */ "Clear"            OpHelp(""),
23052      /* 112 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
23053      /* 113 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
23054      /* 114 */ "ParseSchema"      OpHelp(""),
23055      /* 115 */ "LoadAnalysis"     OpHelp(""),
23056      /* 116 */ "DropTable"        OpHelp(""),
23057      /* 117 */ "DropIndex"        OpHelp(""),
23058      /* 118 */ "DropTrigger"      OpHelp(""),
23059      /* 119 */ "IntegrityCk"      OpHelp(""),
23060      /* 120 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
23061      /* 121 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
23062      /* 122 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
23063      /* 123 */ "Program"          OpHelp(""),
23064      /* 124 */ "Param"            OpHelp(""),
23065      /* 125 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
23066      /* 126 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
23067      /* 127 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
23068      /* 128 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
23069      /* 129 */ "IfNeg"            OpHelp("if r[P1]<0 goto P2"),
23070      /* 130 */ "IfZero"           OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
23071      /* 131 */ "Real"             OpHelp("r[P2]=P4"),
23072      /* 132 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
23073      /* 133 */ "IncrVacuum"       OpHelp(""),
23074      /* 134 */ "Expire"           OpHelp(""),
23075      /* 135 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
23076      /* 136 */ "VBegin"           OpHelp(""),
23077      /* 137 */ "VCreate"          OpHelp(""),
23078      /* 138 */ "VDestroy"         OpHelp(""),
23079      /* 139 */ "VOpen"            OpHelp(""),
23080      /* 140 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
23081      /* 141 */ "VNext"            OpHelp(""),
23082      /* 142 */ "ToText"           OpHelp(""),
23083      /* 143 */ "ToBlob"           OpHelp(""),
23084      /* 144 */ "ToNumeric"        OpHelp(""),
23085      /* 145 */ "ToInt"            OpHelp(""),
23086      /* 146 */ "ToReal"           OpHelp(""),
23087      /* 147 */ "VRename"          OpHelp(""),
23088      /* 148 */ "Pagecount"        OpHelp(""),
23089      /* 149 */ "MaxPgcnt"         OpHelp(""),
23090      /* 150 */ "Trace"            OpHelp(""),
23091      /* 151 */ "Noop"             OpHelp(""),
23092      /* 152 */ "Explain"          OpHelp(""),
23093   };
23094   return azName[i];
23095 }
23096 #endif
23097 
23098 /************** End of opcodes.c *********************************************/
23099 /************** Begin file os_unix.c *****************************************/
23100 /*
23101 ** 2004 May 22
23102 **
23103 ** The author disclaims copyright to this source code.  In place of
23104 ** a legal notice, here is a blessing:
23105 **
23106 **    May you do good and not evil.
23107 **    May you find forgiveness for yourself and forgive others.
23108 **    May you share freely, never taking more than you give.
23109 **
23110 ******************************************************************************
23111 **
23112 ** This file contains the VFS implementation for unix-like operating systems
23113 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23114 **
23115 ** There are actually several different VFS implementations in this file.
23116 ** The differences are in the way that file locking is done.  The default
23117 ** implementation uses Posix Advisory Locks.  Alternative implementations
23118 ** use flock(), dot-files, various proprietary locking schemas, or simply
23119 ** skip locking all together.
23120 **
23121 ** This source file is organized into divisions where the logic for various
23122 ** subfunctions is contained within the appropriate division.  PLEASE
23123 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
23124 ** in the correct division and should be clearly labeled.
23125 **
23126 ** The layout of divisions is as follows:
23127 **
23128 **   *  General-purpose declarations and utility functions.
23129 **   *  Unique file ID logic used by VxWorks.
23130 **   *  Various locking primitive implementations (all except proxy locking):
23131 **      + for Posix Advisory Locks
23132 **      + for no-op locks
23133 **      + for dot-file locks
23134 **      + for flock() locking
23135 **      + for named semaphore locks (VxWorks only)
23136 **      + for AFP filesystem locks (MacOSX only)
23137 **   *  sqlite3_file methods not associated with locking.
23138 **   *  Definitions of sqlite3_io_methods objects for all locking
23139 **      methods plus "finder" functions for each locking method.
23140 **   *  sqlite3_vfs method implementations.
23141 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
23142 **   *  Definitions of sqlite3_vfs objects for all locking methods
23143 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
23144 */
23145 #if SQLITE_OS_UNIX              /* This file is used on unix only */
23146 
23147 /*
23148 ** There are various methods for file locking used for concurrency
23149 ** control:
23150 **
23151 **   1. POSIX locking (the default),
23152 **   2. No locking,
23153 **   3. Dot-file locking,
23154 **   4. flock() locking,
23155 **   5. AFP locking (OSX only),
23156 **   6. Named POSIX semaphores (VXWorks only),
23157 **   7. proxy locking. (OSX only)
23158 **
23159 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
23160 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
23161 ** selection of the appropriate locking style based on the filesystem
23162 ** where the database is located.  
23163 */
23164 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
23165 #  if defined(__APPLE__)
23166 #    define SQLITE_ENABLE_LOCKING_STYLE 1
23167 #  else
23168 #    define SQLITE_ENABLE_LOCKING_STYLE 0
23169 #  endif
23170 #endif
23171 
23172 /*
23173 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
23174 ** vxworks, or 0 otherwise.
23175 */
23176 #ifndef OS_VXWORKS
23177 #  if defined(__RTP__) || defined(_WRS_KERNEL)
23178 #    define OS_VXWORKS 1
23179 #  else
23180 #    define OS_VXWORKS 0
23181 #  endif
23182 #endif
23183 
23184 /*
23185 ** These #defines should enable >2GB file support on Posix if the
23186 ** underlying operating system supports it.  If the OS lacks
23187 ** large file support, these should be no-ops.
23188 **
23189 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
23190 ** on the compiler command line.  This is necessary if you are compiling
23191 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
23192 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
23193 ** without this option, LFS is enable.  But LFS does not exist in the kernel
23194 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
23195 ** portability you should omit LFS.
23196 **
23197 ** The previous paragraph was written in 2005.  (This paragraph is written
23198 ** on 2008-11-28.) These days, all Linux kernels support large files, so
23199 ** you should probably leave LFS enabled.  But some embedded platforms might
23200 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
23201 */
23202 #ifndef SQLITE_DISABLE_LFS
23203 # define _LARGE_FILE       1
23204 # ifndef _FILE_OFFSET_BITS
23205 #   define _FILE_OFFSET_BITS 64
23206 # endif
23207 # define _LARGEFILE_SOURCE 1
23208 #endif
23209 
23210 /*
23211 ** standard include files.
23212 */
23213 #include <sys/types.h>
23214 #include <sys/stat.h>
23215 #include <fcntl.h>
23216 #include <unistd.h>
23217 /* #include <time.h> */
23218 #include <sys/time.h>
23219 #include <errno.h>
23220 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23221 #include <sys/mman.h>
23222 #endif
23223 
23224 
23225 #if SQLITE_ENABLE_LOCKING_STYLE
23226 # include <sys/ioctl.h>
23227 # if OS_VXWORKS
23228 #  include <semaphore.h>
23229 #  include <limits.h>
23230 # else
23231 #  include <sys/file.h>
23232 #  include <sys/param.h>
23233 # endif
23234 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23235 
23236 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23237 # include <sys/mount.h>
23238 #endif
23239 
23240 #ifdef HAVE_UTIME
23241 # include <utime.h>
23242 #endif
23243 
23244 /*
23245 ** Allowed values of unixFile.fsFlags
23246 */
23247 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
23248 
23249 /*
23250 ** If we are to be thread-safe, include the pthreads header and define
23251 ** the SQLITE_UNIX_THREADS macro.
23252 */
23253 #if SQLITE_THREADSAFE
23254 /* # include <pthread.h> */
23255 # define SQLITE_UNIX_THREADS 1
23256 #endif
23257 
23258 /*
23259 ** Default permissions when creating a new file
23260 */
23261 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23262 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23263 #endif
23264 
23265 /*
23266 ** Default permissions when creating auto proxy dir
23267 */
23268 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23269 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23270 #endif
23271 
23272 /*
23273 ** Maximum supported path-length.
23274 */
23275 #define MAX_PATHNAME 512
23276 
23277 /*
23278 ** Only set the lastErrno if the error code is a real error and not 
23279 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23280 */
23281 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23282 
23283 /* Forward references */
23284 typedef struct unixShm unixShm;               /* Connection shared memory */
23285 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
23286 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
23287 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
23288 
23289 /*
23290 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
23291 ** cannot be closed immediately. In these cases, instances of the following
23292 ** structure are used to store the file descriptor while waiting for an
23293 ** opportunity to either close or reuse it.
23294 */
23295 struct UnixUnusedFd {
23296   int fd;                   /* File descriptor to close */
23297   int flags;                /* Flags this file descriptor was opened with */
23298   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
23299 };
23300 
23301 /*
23302 ** The unixFile structure is subclass of sqlite3_file specific to the unix
23303 ** VFS implementations.
23304 */
23305 typedef struct unixFile unixFile;
23306 struct unixFile {
23307   sqlite3_io_methods const *pMethod;  /* Always the first entry */
23308   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
23309   unixInodeInfo *pInode;              /* Info about locks on this inode */
23310   int h;                              /* The file descriptor */
23311   unsigned char eFileLock;            /* The type of lock held on this fd */
23312   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
23313   int lastErrno;                      /* The unix errno from last I/O error */
23314   void *lockingContext;               /* Locking style specific state */
23315   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
23316   const char *zPath;                  /* Name of the file */
23317   unixShm *pShm;                      /* Shared memory segment information */
23318   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
23319 #if SQLITE_MAX_MMAP_SIZE>0
23320   int nFetchOut;                      /* Number of outstanding xFetch refs */
23321   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
23322   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
23323   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
23324   void *pMapRegion;                   /* Memory mapped region */
23325 #endif
23326 #ifdef __QNXNTO__
23327   int sectorSize;                     /* Device sector size */
23328   int deviceCharacteristics;          /* Precomputed device characteristics */
23329 #endif
23330 #if SQLITE_ENABLE_LOCKING_STYLE
23331   int openFlags;                      /* The flags specified at open() */
23332 #endif
23333 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23334   unsigned fsFlags;                   /* cached details from statfs() */
23335 #endif
23336 #if OS_VXWORKS
23337   struct vxworksFileId *pId;          /* Unique file ID */
23338 #endif
23339 #ifdef SQLITE_DEBUG
23340   /* The next group of variables are used to track whether or not the
23341   ** transaction counter in bytes 24-27 of database files are updated
23342   ** whenever any part of the database changes.  An assertion fault will
23343   ** occur if a file is updated without also updating the transaction
23344   ** counter.  This test is made to avoid new problems similar to the
23345   ** one described by ticket #3584. 
23346   */
23347   unsigned char transCntrChng;   /* True if the transaction counter changed */
23348   unsigned char dbUpdate;        /* True if any part of database file changed */
23349   unsigned char inNormalWrite;   /* True if in a normal write operation */
23350 
23351 #endif
23352 
23353 #ifdef SQLITE_TEST
23354   /* In test mode, increase the size of this structure a bit so that 
23355   ** it is larger than the struct CrashFile defined in test6.c.
23356   */
23357   char aPadding[32];
23358 #endif
23359 };
23360 
23361 /*
23362 ** Allowed values for the unixFile.ctrlFlags bitmask:
23363 */
23364 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
23365 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
23366 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
23367 #ifndef SQLITE_DISABLE_DIRSYNC
23368 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
23369 #else
23370 # define UNIXFILE_DIRSYNC    0x00
23371 #endif
23372 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23373 #define UNIXFILE_DELETE      0x20     /* Delete on close */
23374 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
23375 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
23376 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
23377 
23378 /*
23379 ** Include code that is common to all os_*.c files
23380 */
23381 /************** Include os_common.h in the middle of os_unix.c ***************/
23382 /************** Begin file os_common.h ***************************************/
23383 /*
23384 ** 2004 May 22
23385 **
23386 ** The author disclaims copyright to this source code.  In place of
23387 ** a legal notice, here is a blessing:
23388 **
23389 **    May you do good and not evil.
23390 **    May you find forgiveness for yourself and forgive others.
23391 **    May you share freely, never taking more than you give.
23392 **
23393 ******************************************************************************
23394 **
23395 ** This file contains macros and a little bit of code that is common to
23396 ** all of the platform-specific files (os_*.c) and is #included into those
23397 ** files.
23398 **
23399 ** This file should be #included by the os_*.c files only.  It is not a
23400 ** general purpose header file.
23401 */
23402 #ifndef _OS_COMMON_H_
23403 #define _OS_COMMON_H_
23404 
23405 /*
23406 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23407 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23408 ** switch.  The following code should catch this problem at compile-time.
23409 */
23410 #ifdef MEMORY_DEBUG
23411 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23412 #endif
23413 
23414 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23415 # ifndef SQLITE_DEBUG_OS_TRACE
23416 #   define SQLITE_DEBUG_OS_TRACE 0
23417 # endif
23418   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23419 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23420 #else
23421 # define OSTRACE(X)
23422 #endif
23423 
23424 /*
23425 ** Macros for performance tracing.  Normally turned off.  Only works
23426 ** on i486 hardware.
23427 */
23428 #ifdef SQLITE_PERFORMANCE_TRACE
23429 
23430 /* 
23431 ** hwtime.h contains inline assembler code for implementing 
23432 ** high-performance timing routines.
23433 */
23434 /************** Include hwtime.h in the middle of os_common.h ****************/
23435 /************** Begin file hwtime.h ******************************************/
23436 /*
23437 ** 2008 May 27
23438 **
23439 ** The author disclaims copyright to this source code.  In place of
23440 ** a legal notice, here is a blessing:
23441 **
23442 **    May you do good and not evil.
23443 **    May you find forgiveness for yourself and forgive others.
23444 **    May you share freely, never taking more than you give.
23445 **
23446 ******************************************************************************
23447 **
23448 ** This file contains inline asm code for retrieving "high-performance"
23449 ** counters for x86 class CPUs.
23450 */
23451 #ifndef _HWTIME_H_
23452 #define _HWTIME_H_
23453 
23454 /*
23455 ** The following routine only works on pentium-class (or newer) processors.
23456 ** It uses the RDTSC opcode to read the cycle count value out of the
23457 ** processor and returns that value.  This can be used for high-res
23458 ** profiling.
23459 */
23460 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23461       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23462 
23463   #if defined(__GNUC__)
23464 
23465   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23466      unsigned int lo, hi;
23467      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23468      return (sqlite_uint64)hi << 32 | lo;
23469   }
23470 
23471   #elif defined(_MSC_VER)
23472 
23473   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23474      __asm {
23475         rdtsc
23476         ret       ; return value at EDX:EAX
23477      }
23478   }
23479 
23480   #endif
23481 
23482 #elif (defined(__GNUC__) && defined(__x86_64__))
23483 
23484   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23485       unsigned long val;
23486       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23487       return val;
23488   }
23489  
23490 #elif (defined(__GNUC__) && defined(__ppc__))
23491 
23492   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23493       unsigned long long retval;
23494       unsigned long junk;
23495       __asm__ __volatile__ ("\n\
23496           1:      mftbu   %1\n\
23497                   mftb    %L0\n\
23498                   mftbu   %0\n\
23499                   cmpw    %0,%1\n\
23500                   bne     1b"
23501                   : "=r" (retval), "=r" (junk));
23502       return retval;
23503   }
23504 
23505 #else
23506 
23507   #error Need implementation of sqlite3Hwtime() for your platform.
23508 
23509   /*
23510   ** To compile without implementing sqlite3Hwtime() for your platform,
23511   ** you can remove the above #error and use the following
23512   ** stub function.  You will lose timing support for many
23513   ** of the debugging and testing utilities, but it should at
23514   ** least compile and run.
23515   */
23516 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23517 
23518 #endif
23519 
23520 #endif /* !defined(_HWTIME_H_) */
23521 
23522 /************** End of hwtime.h **********************************************/
23523 /************** Continuing where we left off in os_common.h ******************/
23524 
23525 static sqlite_uint64 g_start;
23526 static sqlite_uint64 g_elapsed;
23527 #define TIMER_START       g_start=sqlite3Hwtime()
23528 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23529 #define TIMER_ELAPSED     g_elapsed
23530 #else
23531 #define TIMER_START
23532 #define TIMER_END
23533 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23534 #endif
23535 
23536 /*
23537 ** If we compile with the SQLITE_TEST macro set, then the following block
23538 ** of code will give us the ability to simulate a disk I/O error.  This
23539 ** is used for testing the I/O recovery logic.
23540 */
23541 #ifdef SQLITE_TEST
23542 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23543 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23544 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23545 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23546 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23547 SQLITE_API int sqlite3_diskfull_pending = 0;
23548 SQLITE_API int sqlite3_diskfull = 0;
23549 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23550 #define SimulateIOError(CODE)  \
23551   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23552        || sqlite3_io_error_pending-- == 1 )  \
23553               { local_ioerr(); CODE; }
23554 static void local_ioerr(){
23555   IOTRACE(("IOERR\n"));
23556   sqlite3_io_error_hit++;
23557   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23558 }
23559 #define SimulateDiskfullError(CODE) \
23560    if( sqlite3_diskfull_pending ){ \
23561      if( sqlite3_diskfull_pending == 1 ){ \
23562        local_ioerr(); \
23563        sqlite3_diskfull = 1; \
23564        sqlite3_io_error_hit = 1; \
23565        CODE; \
23566      }else{ \
23567        sqlite3_diskfull_pending--; \
23568      } \
23569    }
23570 #else
23571 #define SimulateIOErrorBenign(X)
23572 #define SimulateIOError(A)
23573 #define SimulateDiskfullError(A)
23574 #endif
23575 
23576 /*
23577 ** When testing, keep a count of the number of open files.
23578 */
23579 #ifdef SQLITE_TEST
23580 SQLITE_API int sqlite3_open_file_count = 0;
23581 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23582 #else
23583 #define OpenCounter(X)
23584 #endif
23585 
23586 #endif /* !defined(_OS_COMMON_H_) */
23587 
23588 /************** End of os_common.h *******************************************/
23589 /************** Continuing where we left off in os_unix.c ********************/
23590 
23591 /*
23592 ** Define various macros that are missing from some systems.
23593 */
23594 #ifndef O_LARGEFILE
23595 # define O_LARGEFILE 0
23596 #endif
23597 #ifdef SQLITE_DISABLE_LFS
23598 # undef O_LARGEFILE
23599 # define O_LARGEFILE 0
23600 #endif
23601 #ifndef O_NOFOLLOW
23602 # define O_NOFOLLOW 0
23603 #endif
23604 #ifndef O_BINARY
23605 # define O_BINARY 0
23606 #endif
23607 
23608 /*
23609 ** The threadid macro resolves to the thread-id or to 0.  Used for
23610 ** testing and debugging only.
23611 */
23612 #if SQLITE_THREADSAFE
23613 #define threadid pthread_self()
23614 #else
23615 #define threadid 0
23616 #endif
23617 
23618 /*
23619 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
23620 */
23621 #if !defined(HAVE_MREMAP)
23622 # if defined(__linux__) && defined(_GNU_SOURCE)
23623 #  define HAVE_MREMAP 1
23624 # else
23625 #  define HAVE_MREMAP 0
23626 # endif
23627 #endif
23628 
23629 /*
23630 ** Different Unix systems declare open() in different ways.  Same use
23631 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23632 ** The difference is important when using a pointer to the function.
23633 **
23634 ** The safest way to deal with the problem is to always use this wrapper
23635 ** which always has the same well-defined interface.
23636 */
23637 static int posixOpen(const char *zFile, int flags, int mode){
23638   return open(zFile, flags, mode);
23639 }
23640 
23641 /*
23642 ** On some systems, calls to fchown() will trigger a message in a security
23643 ** log if they come from non-root processes.  So avoid calling fchown() if
23644 ** we are not running as root.
23645 */
23646 static int posixFchown(int fd, uid_t uid, gid_t gid){
23647   return geteuid() ? 0 : fchown(fd,uid,gid);
23648 }
23649 
23650 /* Forward reference */
23651 static int openDirectory(const char*, int*);
23652 
23653 /*
23654 ** Many system calls are accessed through pointer-to-functions so that
23655 ** they may be overridden at runtime to facilitate fault injection during
23656 ** testing and sandboxing.  The following array holds the names and pointers
23657 ** to all overrideable system calls.
23658 */
23659 static struct unix_syscall {
23660   const char *zName;            /* Name of the system call */
23661   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23662   sqlite3_syscall_ptr pDefault; /* Default value */
23663 } aSyscall[] = {
23664   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23665 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23666 
23667   { "close",        (sqlite3_syscall_ptr)close,      0  },
23668 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23669 
23670   { "access",       (sqlite3_syscall_ptr)access,     0  },
23671 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23672 
23673   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23674 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23675 
23676   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23677 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23678 
23679 /*
23680 ** The DJGPP compiler environment looks mostly like Unix, but it
23681 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23682 ** that always succeeds.  This means that locking does not occur under
23683 ** DJGPP.  But it is DOS - what did you expect?
23684 */
23685 #ifdef __DJGPP__
23686   { "fstat",        0,                 0  },
23687 #define osFstat(a,b,c)    0
23688 #else     
23689   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23690 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23691 #endif
23692 
23693   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23694 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23695 
23696   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23697 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23698 
23699   { "read",         (sqlite3_syscall_ptr)read,       0  },
23700 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23701 
23702 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23703   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23704 #else
23705   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23706 #endif
23707 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23708 
23709 #if defined(USE_PREAD64)
23710   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23711 #else
23712   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23713 #endif
23714 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23715 
23716   { "write",        (sqlite3_syscall_ptr)write,      0  },
23717 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23718 
23719 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23720   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23721 #else
23722   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23723 #endif
23724 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23725                     aSyscall[12].pCurrent)
23726 
23727 #if defined(USE_PREAD64)
23728   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23729 #else
23730   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23731 #endif
23732 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23733                     aSyscall[13].pCurrent)
23734 
23735   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23736 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23737 
23738 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23739   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23740 #else
23741   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23742 #endif
23743 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23744 
23745   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23746 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23747 
23748   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23749 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23750 
23751   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23752 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23753 
23754   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23755 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23756 
23757   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23758 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23759 
23760 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23761   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
23762 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
23763 
23764   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
23765 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
23766 
23767 #if HAVE_MREMAP
23768   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
23769 #else
23770   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
23771 #endif
23772 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
23773 #endif
23774 
23775 }; /* End of the overrideable system calls */
23776 
23777 /*
23778 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23779 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23780 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23781 ** system call named zName.
23782 */
23783 static int unixSetSystemCall(
23784   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23785   const char *zName,            /* Name of system call to override */
23786   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23787 ){
23788   unsigned int i;
23789   int rc = SQLITE_NOTFOUND;
23790 
23791   UNUSED_PARAMETER(pNotUsed);
23792   if( zName==0 ){
23793     /* If no zName is given, restore all system calls to their default
23794     ** settings and return NULL
23795     */
23796     rc = SQLITE_OK;
23797     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23798       if( aSyscall[i].pDefault ){
23799         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23800       }
23801     }
23802   }else{
23803     /* If zName is specified, operate on only the one system call
23804     ** specified.
23805     */
23806     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23807       if( strcmp(zName, aSyscall[i].zName)==0 ){
23808         if( aSyscall[i].pDefault==0 ){
23809           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23810         }
23811         rc = SQLITE_OK;
23812         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23813         aSyscall[i].pCurrent = pNewFunc;
23814         break;
23815       }
23816     }
23817   }
23818   return rc;
23819 }
23820 
23821 /*
23822 ** Return the value of a system call.  Return NULL if zName is not a
23823 ** recognized system call name.  NULL is also returned if the system call
23824 ** is currently undefined.
23825 */
23826 static sqlite3_syscall_ptr unixGetSystemCall(
23827   sqlite3_vfs *pNotUsed,
23828   const char *zName
23829 ){
23830   unsigned int i;
23831 
23832   UNUSED_PARAMETER(pNotUsed);
23833   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23834     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23835   }
23836   return 0;
23837 }
23838 
23839 /*
23840 ** Return the name of the first system call after zName.  If zName==NULL
23841 ** then return the name of the first system call.  Return NULL if zName
23842 ** is the last system call or if zName is not the name of a valid
23843 ** system call.
23844 */
23845 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23846   int i = -1;
23847 
23848   UNUSED_PARAMETER(p);
23849   if( zName ){
23850     for(i=0; i<ArraySize(aSyscall)-1; i++){
23851       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23852     }
23853   }
23854   for(i++; i<ArraySize(aSyscall); i++){
23855     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23856   }
23857   return 0;
23858 }
23859 
23860 /*
23861 ** Do not accept any file descriptor less than this value, in order to avoid
23862 ** opening database file using file descriptors that are commonly used for 
23863 ** standard input, output, and error.
23864 */
23865 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
23866 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
23867 #endif
23868 
23869 /*
23870 ** Invoke open().  Do so multiple times, until it either succeeds or
23871 ** fails for some reason other than EINTR.
23872 **
23873 ** If the file creation mode "m" is 0 then set it to the default for
23874 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23875 ** 0644) as modified by the system umask.  If m is not 0, then
23876 ** make the file creation mode be exactly m ignoring the umask.
23877 **
23878 ** The m parameter will be non-zero only when creating -wal, -journal,
23879 ** and -shm files.  We want those files to have *exactly* the same
23880 ** permissions as their original database, unadulterated by the umask.
23881 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23882 ** transaction crashes and leaves behind hot journals, then any
23883 ** process that is able to write to the database will also be able to
23884 ** recover the hot journals.
23885 */
23886 static int robust_open(const char *z, int f, mode_t m){
23887   int fd;
23888   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23889   while(1){
23890 #if defined(O_CLOEXEC)
23891     fd = osOpen(z,f|O_CLOEXEC,m2);
23892 #else
23893     fd = osOpen(z,f,m2);
23894 #endif
23895     if( fd<0 ){
23896       if( errno==EINTR ) continue;
23897       break;
23898     }
23899     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
23900     osClose(fd);
23901     sqlite3_log(SQLITE_WARNING, 
23902                 "attempt to open \"%s\" as file descriptor %d", z, fd);
23903     fd = -1;
23904     if( osOpen("/dev/null", f, m)<0 ) break;
23905   }
23906   if( fd>=0 ){
23907     if( m!=0 ){
23908       struct stat statbuf;
23909       if( osFstat(fd, &statbuf)==0 
23910        && statbuf.st_size==0
23911        && (statbuf.st_mode&0777)!=m 
23912       ){
23913         osFchmod(fd, m);
23914       }
23915     }
23916 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23917     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23918 #endif
23919   }
23920   return fd;
23921 }
23922 
23923 /*
23924 ** Helper functions to obtain and relinquish the global mutex. The
23925 ** global mutex is used to protect the unixInodeInfo and
23926 ** vxworksFileId objects used by this file, all of which may be 
23927 ** shared by multiple threads.
23928 **
23929 ** Function unixMutexHeld() is used to assert() that the global mutex 
23930 ** is held when required. This function is only used as part of assert() 
23931 ** statements. e.g.
23932 **
23933 **   unixEnterMutex()
23934 **     assert( unixMutexHeld() );
23935 **   unixEnterLeave()
23936 */
23937 static void unixEnterMutex(void){
23938   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23939 }
23940 static void unixLeaveMutex(void){
23941   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23942 }
23943 #ifdef SQLITE_DEBUG
23944 static int unixMutexHeld(void) {
23945   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23946 }
23947 #endif
23948 
23949 
23950 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23951 /*
23952 ** Helper function for printing out trace information from debugging
23953 ** binaries. This returns the string represetation of the supplied
23954 ** integer lock-type.
23955 */
23956 static const char *azFileLock(int eFileLock){
23957   switch( eFileLock ){
23958     case NO_LOCK: return "NONE";
23959     case SHARED_LOCK: return "SHARED";
23960     case RESERVED_LOCK: return "RESERVED";
23961     case PENDING_LOCK: return "PENDING";
23962     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23963   }
23964   return "ERROR";
23965 }
23966 #endif
23967 
23968 #ifdef SQLITE_LOCK_TRACE
23969 /*
23970 ** Print out information about all locking operations.
23971 **
23972 ** This routine is used for troubleshooting locks on multithreaded
23973 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23974 ** command-line option on the compiler.  This code is normally
23975 ** turned off.
23976 */
23977 static int lockTrace(int fd, int op, struct flock *p){
23978   char *zOpName, *zType;
23979   int s;
23980   int savedErrno;
23981   if( op==F_GETLK ){
23982     zOpName = "GETLK";
23983   }else if( op==F_SETLK ){
23984     zOpName = "SETLK";
23985   }else{
23986     s = osFcntl(fd, op, p);
23987     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23988     return s;
23989   }
23990   if( p->l_type==F_RDLCK ){
23991     zType = "RDLCK";
23992   }else if( p->l_type==F_WRLCK ){
23993     zType = "WRLCK";
23994   }else if( p->l_type==F_UNLCK ){
23995     zType = "UNLCK";
23996   }else{
23997     assert( 0 );
23998   }
23999   assert( p->l_whence==SEEK_SET );
24000   s = osFcntl(fd, op, p);
24001   savedErrno = errno;
24002   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24003      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24004      (int)p->l_pid, s);
24005   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24006     struct flock l2;
24007     l2 = *p;
24008     osFcntl(fd, F_GETLK, &l2);
24009     if( l2.l_type==F_RDLCK ){
24010       zType = "RDLCK";
24011     }else if( l2.l_type==F_WRLCK ){
24012       zType = "WRLCK";
24013     }else if( l2.l_type==F_UNLCK ){
24014       zType = "UNLCK";
24015     }else{
24016       assert( 0 );
24017     }
24018     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24019        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24020   }
24021   errno = savedErrno;
24022   return s;
24023 }
24024 #undef osFcntl
24025 #define osFcntl lockTrace
24026 #endif /* SQLITE_LOCK_TRACE */
24027 
24028 /*
24029 ** Retry ftruncate() calls that fail due to EINTR
24030 */
24031 static int robust_ftruncate(int h, sqlite3_int64 sz){
24032   int rc;
24033   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24034   return rc;
24035 }
24036 
24037 /*
24038 ** This routine translates a standard POSIX errno code into something
24039 ** useful to the clients of the sqlite3 functions.  Specifically, it is
24040 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24041 ** and a variety of "please close the file descriptor NOW" errors into 
24042 ** SQLITE_IOERR
24043 ** 
24044 ** Errors during initialization of locks, or file system support for locks,
24045 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24046 */
24047 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24048   switch (posixError) {
24049 #if 0
24050   /* At one point this code was not commented out. In theory, this branch
24051   ** should never be hit, as this function should only be called after
24052   ** a locking-related function (i.e. fcntl()) has returned non-zero with
24053   ** the value of errno as the first argument. Since a system call has failed,
24054   ** errno should be non-zero.
24055   **
24056   ** Despite this, if errno really is zero, we still don't want to return
24057   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24058   ** propagated back to the caller. Commenting this branch out means errno==0
24059   ** will be handled by the "default:" case below.
24060   */
24061   case 0: 
24062     return SQLITE_OK;
24063 #endif
24064 
24065   case EAGAIN:
24066   case ETIMEDOUT:
24067   case EBUSY:
24068   case EINTR:
24069   case ENOLCK:  
24070     /* random NFS retry error, unless during file system support 
24071      * introspection, in which it actually means what it says */
24072     return SQLITE_BUSY;
24073     
24074   case EACCES: 
24075     /* EACCES is like EAGAIN during locking operations, but not any other time*/
24076     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
24077         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
24078         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24079         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24080       return SQLITE_BUSY;
24081     }
24082     /* else fall through */
24083   case EPERM: 
24084     return SQLITE_PERM;
24085     
24086   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24087   ** this module never makes such a call. And the code in SQLite itself 
24088   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24089   ** this case is also commented out. If the system does set errno to EDEADLK,
24090   ** the default SQLITE_IOERR_XXX code will be returned. */
24091 #if 0
24092   case EDEADLK:
24093     return SQLITE_IOERR_BLOCKED;
24094 #endif
24095     
24096 #if EOPNOTSUPP!=ENOTSUP
24097   case EOPNOTSUPP: 
24098     /* something went terribly awry, unless during file system support 
24099      * introspection, in which it actually means what it says */
24100 #endif
24101 #ifdef ENOTSUP
24102   case ENOTSUP: 
24103     /* invalid fd, unless during file system support introspection, in which 
24104      * it actually means what it says */
24105 #endif
24106   case EIO:
24107   case EBADF:
24108   case EINVAL:
24109   case ENOTCONN:
24110   case ENODEV:
24111   case ENXIO:
24112   case ENOENT:
24113 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
24114   case ESTALE:
24115 #endif
24116   case ENOSYS:
24117     /* these should force the client to close the file and reconnect */
24118     
24119   default: 
24120     return sqliteIOErr;
24121   }
24122 }
24123 
24124 
24125 /******************************************************************************
24126 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24127 **
24128 ** On most versions of unix, we can get a unique ID for a file by concatenating
24129 ** the device number and the inode number.  But this does not work on VxWorks.
24130 ** On VxWorks, a unique file id must be based on the canonical filename.
24131 **
24132 ** A pointer to an instance of the following structure can be used as a
24133 ** unique file ID in VxWorks.  Each instance of this structure contains
24134 ** a copy of the canonical filename.  There is also a reference count.  
24135 ** The structure is reclaimed when the number of pointers to it drops to
24136 ** zero.
24137 **
24138 ** There are never very many files open at one time and lookups are not
24139 ** a performance-critical path, so it is sufficient to put these
24140 ** structures on a linked list.
24141 */
24142 struct vxworksFileId {
24143   struct vxworksFileId *pNext;  /* Next in a list of them all */
24144   int nRef;                     /* Number of references to this one */
24145   int nName;                    /* Length of the zCanonicalName[] string */
24146   char *zCanonicalName;         /* Canonical filename */
24147 };
24148 
24149 #if OS_VXWORKS
24150 /* 
24151 ** All unique filenames are held on a linked list headed by this
24152 ** variable:
24153 */
24154 static struct vxworksFileId *vxworksFileList = 0;
24155 
24156 /*
24157 ** Simplify a filename into its canonical form
24158 ** by making the following changes:
24159 **
24160 **  * removing any trailing and duplicate /
24161 **  * convert /./ into just /
24162 **  * convert /A/../ where A is any simple name into just /
24163 **
24164 ** Changes are made in-place.  Return the new name length.
24165 **
24166 ** The original filename is in z[0..n-1].  Return the number of
24167 ** characters in the simplified name.
24168 */
24169 static int vxworksSimplifyName(char *z, int n){
24170   int i, j;
24171   while( n>1 && z[n-1]=='/' ){ n--; }
24172   for(i=j=0; i<n; i++){
24173     if( z[i]=='/' ){
24174       if( z[i+1]=='/' ) continue;
24175       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24176         i += 1;
24177         continue;
24178       }
24179       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24180         while( j>0 && z[j-1]!='/' ){ j--; }
24181         if( j>0 ){ j--; }
24182         i += 2;
24183         continue;
24184       }
24185     }
24186     z[j++] = z[i];
24187   }
24188   z[j] = 0;
24189   return j;
24190 }
24191 
24192 /*
24193 ** Find a unique file ID for the given absolute pathname.  Return
24194 ** a pointer to the vxworksFileId object.  This pointer is the unique
24195 ** file ID.
24196 **
24197 ** The nRef field of the vxworksFileId object is incremented before
24198 ** the object is returned.  A new vxworksFileId object is created
24199 ** and added to the global list if necessary.
24200 **
24201 ** If a memory allocation error occurs, return NULL.
24202 */
24203 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24204   struct vxworksFileId *pNew;         /* search key and new file ID */
24205   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
24206   int n;                              /* Length of zAbsoluteName string */
24207 
24208   assert( zAbsoluteName[0]=='/' );
24209   n = (int)strlen(zAbsoluteName);
24210   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24211   if( pNew==0 ) return 0;
24212   pNew->zCanonicalName = (char*)&pNew[1];
24213   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24214   n = vxworksSimplifyName(pNew->zCanonicalName, n);
24215 
24216   /* Search for an existing entry that matching the canonical name.
24217   ** If found, increment the reference count and return a pointer to
24218   ** the existing file ID.
24219   */
24220   unixEnterMutex();
24221   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24222     if( pCandidate->nName==n 
24223      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24224     ){
24225        sqlite3_free(pNew);
24226        pCandidate->nRef++;
24227        unixLeaveMutex();
24228        return pCandidate;
24229     }
24230   }
24231 
24232   /* No match was found.  We will make a new file ID */
24233   pNew->nRef = 1;
24234   pNew->nName = n;
24235   pNew->pNext = vxworksFileList;
24236   vxworksFileList = pNew;
24237   unixLeaveMutex();
24238   return pNew;
24239 }
24240 
24241 /*
24242 ** Decrement the reference count on a vxworksFileId object.  Free
24243 ** the object when the reference count reaches zero.
24244 */
24245 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24246   unixEnterMutex();
24247   assert( pId->nRef>0 );
24248   pId->nRef--;
24249   if( pId->nRef==0 ){
24250     struct vxworksFileId **pp;
24251     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24252     assert( *pp==pId );
24253     *pp = pId->pNext;
24254     sqlite3_free(pId);
24255   }
24256   unixLeaveMutex();
24257 }
24258 #endif /* OS_VXWORKS */
24259 /*************** End of Unique File ID Utility Used By VxWorks ****************
24260 ******************************************************************************/
24261 
24262 
24263 /******************************************************************************
24264 *************************** Posix Advisory Locking ****************************
24265 **
24266 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24267 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24268 ** sets or clears a lock, that operation overrides any prior locks set
24269 ** by the same process.  It does not explicitly say so, but this implies
24270 ** that it overrides locks set by the same process using a different
24271 ** file descriptor.  Consider this test case:
24272 **
24273 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24274 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24275 **
24276 ** Suppose ./file1 and ./file2 are really the same file (because
24277 ** one is a hard or symbolic link to the other) then if you set
24278 ** an exclusive lock on fd1, then try to get an exclusive lock
24279 ** on fd2, it works.  I would have expected the second lock to
24280 ** fail since there was already a lock on the file due to fd1.
24281 ** But not so.  Since both locks came from the same process, the
24282 ** second overrides the first, even though they were on different
24283 ** file descriptors opened on different file names.
24284 **
24285 ** This means that we cannot use POSIX locks to synchronize file access
24286 ** among competing threads of the same process.  POSIX locks will work fine
24287 ** to synchronize access for threads in separate processes, but not
24288 ** threads within the same process.
24289 **
24290 ** To work around the problem, SQLite has to manage file locks internally
24291 ** on its own.  Whenever a new database is opened, we have to find the
24292 ** specific inode of the database file (the inode is determined by the
24293 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24294 ** and check for locks already existing on that inode.  When locks are
24295 ** created or removed, we have to look at our own internal record of the
24296 ** locks to see if another thread has previously set a lock on that same
24297 ** inode.
24298 **
24299 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24300 ** For VxWorks, we have to use the alternative unique ID system based on
24301 ** canonical filename and implemented in the previous division.)
24302 **
24303 ** The sqlite3_file structure for POSIX is no longer just an integer file
24304 ** descriptor.  It is now a structure that holds the integer file
24305 ** descriptor and a pointer to a structure that describes the internal
24306 ** locks on the corresponding inode.  There is one locking structure
24307 ** per inode, so if the same inode is opened twice, both unixFile structures
24308 ** point to the same locking structure.  The locking structure keeps
24309 ** a reference count (so we will know when to delete it) and a "cnt"
24310 ** field that tells us its internal lock status.  cnt==0 means the
24311 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24312 ** cnt>0 means there are cnt shared locks on the file.
24313 **
24314 ** Any attempt to lock or unlock a file first checks the locking
24315 ** structure.  The fcntl() system call is only invoked to set a 
24316 ** POSIX lock if the internal lock structure transitions between
24317 ** a locked and an unlocked state.
24318 **
24319 ** But wait:  there are yet more problems with POSIX advisory locks.
24320 **
24321 ** If you close a file descriptor that points to a file that has locks,
24322 ** all locks on that file that are owned by the current process are
24323 ** released.  To work around this problem, each unixInodeInfo object
24324 ** maintains a count of the number of pending locks on tha inode.
24325 ** When an attempt is made to close an unixFile, if there are
24326 ** other unixFile open on the same inode that are holding locks, the call
24327 ** to close() the file descriptor is deferred until all of the locks clear.
24328 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24329 ** be closed and that list is walked (and cleared) when the last lock
24330 ** clears.
24331 **
24332 ** Yet another problem:  LinuxThreads do not play well with posix locks.
24333 **
24334 ** Many older versions of linux use the LinuxThreads library which is
24335 ** not posix compliant.  Under LinuxThreads, a lock created by thread
24336 ** A cannot be modified or overridden by a different thread B.
24337 ** Only thread A can modify the lock.  Locking behavior is correct
24338 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
24339 ** on linux - with NPTL a lock created by thread A can override locks
24340 ** in thread B.  But there is no way to know at compile-time which
24341 ** threading library is being used.  So there is no way to know at
24342 ** compile-time whether or not thread A can override locks on thread B.
24343 ** One has to do a run-time check to discover the behavior of the
24344 ** current process.
24345 **
24346 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
24347 ** was dropped beginning with version 3.7.0.  SQLite will still work with
24348 ** LinuxThreads provided that (1) there is no more than one connection 
24349 ** per database file in the same process and (2) database connections
24350 ** do not move across threads.
24351 */
24352 
24353 /*
24354 ** An instance of the following structure serves as the key used
24355 ** to locate a particular unixInodeInfo object.
24356 */
24357 struct unixFileId {
24358   dev_t dev;                  /* Device number */
24359 #if OS_VXWORKS
24360   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
24361 #else
24362   ino_t ino;                  /* Inode number */
24363 #endif
24364 };
24365 
24366 /*
24367 ** An instance of the following structure is allocated for each open
24368 ** inode.  Or, on LinuxThreads, there is one of these structures for
24369 ** each inode opened by each thread.
24370 **
24371 ** A single inode can have multiple file descriptors, so each unixFile
24372 ** structure contains a pointer to an instance of this object and this
24373 ** object keeps a count of the number of unixFile pointing to it.
24374 */
24375 struct unixInodeInfo {
24376   struct unixFileId fileId;       /* The lookup key */
24377   int nShared;                    /* Number of SHARED locks held */
24378   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24379   unsigned char bProcessLock;     /* An exclusive process lock is held */
24380   int nRef;                       /* Number of pointers to this structure */
24381   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
24382   int nLock;                      /* Number of outstanding file locks */
24383   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
24384   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
24385   unixInodeInfo *pPrev;           /*    .... doubly linked */
24386 #if SQLITE_ENABLE_LOCKING_STYLE
24387   unsigned long long sharedByte;  /* for AFP simulated shared lock */
24388 #endif
24389 #if OS_VXWORKS
24390   sem_t *pSem;                    /* Named POSIX semaphore */
24391   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
24392 #endif
24393 };
24394 
24395 /*
24396 ** A lists of all unixInodeInfo objects.
24397 */
24398 static unixInodeInfo *inodeList = 0;
24399 
24400 /*
24401 **
24402 ** This function - unixLogError_x(), is only ever called via the macro
24403 ** unixLogError().
24404 **
24405 ** It is invoked after an error occurs in an OS function and errno has been
24406 ** set. It logs a message using sqlite3_log() containing the current value of
24407 ** errno and, if possible, the human-readable equivalent from strerror() or
24408 ** strerror_r().
24409 **
24410 ** The first argument passed to the macro should be the error code that
24411 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
24412 ** The two subsequent arguments should be the name of the OS function that
24413 ** failed (e.g. "unlink", "open") and the associated file-system path,
24414 ** if any.
24415 */
24416 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
24417 static int unixLogErrorAtLine(
24418   int errcode,                    /* SQLite error code */
24419   const char *zFunc,              /* Name of OS function that failed */
24420   const char *zPath,              /* File path associated with error */
24421   int iLine                       /* Source line number where error occurred */
24422 ){
24423   char *zErr;                     /* Message from strerror() or equivalent */
24424   int iErrno = errno;             /* Saved syscall error number */
24425 
24426   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24427   ** the strerror() function to obtain the human-readable error message
24428   ** equivalent to errno. Otherwise, use strerror_r().
24429   */ 
24430 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24431   char aErr[80];
24432   memset(aErr, 0, sizeof(aErr));
24433   zErr = aErr;
24434 
24435   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24436   ** assume that the system provides the GNU version of strerror_r() that
24437   ** returns a pointer to a buffer containing the error message. That pointer 
24438   ** may point to aErr[], or it may point to some static storage somewhere. 
24439   ** Otherwise, assume that the system provides the POSIX version of 
24440   ** strerror_r(), which always writes an error message into aErr[].
24441   **
24442   ** If the code incorrectly assumes that it is the POSIX version that is
24443   ** available, the error message will often be an empty string. Not a
24444   ** huge problem. Incorrectly concluding that the GNU version is available 
24445   ** could lead to a segfault though.
24446   */
24447 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24448   zErr = 
24449 # endif
24450   strerror_r(iErrno, aErr, sizeof(aErr)-1);
24451 
24452 #elif SQLITE_THREADSAFE
24453   /* This is a threadsafe build, but strerror_r() is not available. */
24454   zErr = "";
24455 #else
24456   /* Non-threadsafe build, use strerror(). */
24457   zErr = strerror(iErrno);
24458 #endif
24459 
24460   if( zPath==0 ) zPath = "";
24461   sqlite3_log(errcode,
24462       "os_unix.c:%d: (%d) %s(%s) - %s",
24463       iLine, iErrno, zFunc, zPath, zErr
24464   );
24465 
24466   return errcode;
24467 }
24468 
24469 /*
24470 ** Close a file descriptor.
24471 **
24472 ** We assume that close() almost always works, since it is only in a
24473 ** very sick application or on a very sick platform that it might fail.
24474 ** If it does fail, simply leak the file descriptor, but do log the
24475 ** error.
24476 **
24477 ** Note that it is not safe to retry close() after EINTR since the
24478 ** file descriptor might have already been reused by another thread.
24479 ** So we don't even try to recover from an EINTR.  Just log the error
24480 ** and move on.
24481 */
24482 static void robust_close(unixFile *pFile, int h, int lineno){
24483   if( osClose(h) ){
24484     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24485                        pFile ? pFile->zPath : 0, lineno);
24486   }
24487 }
24488 
24489 /*
24490 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24491 */ 
24492 static void closePendingFds(unixFile *pFile){
24493   unixInodeInfo *pInode = pFile->pInode;
24494   UnixUnusedFd *p;
24495   UnixUnusedFd *pNext;
24496   for(p=pInode->pUnused; p; p=pNext){
24497     pNext = p->pNext;
24498     robust_close(pFile, p->fd, __LINE__);
24499     sqlite3_free(p);
24500   }
24501   pInode->pUnused = 0;
24502 }
24503 
24504 /*
24505 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24506 **
24507 ** The mutex entered using the unixEnterMutex() function must be held
24508 ** when this function is called.
24509 */
24510 static void releaseInodeInfo(unixFile *pFile){
24511   unixInodeInfo *pInode = pFile->pInode;
24512   assert( unixMutexHeld() );
24513   if( ALWAYS(pInode) ){
24514     pInode->nRef--;
24515     if( pInode->nRef==0 ){
24516       assert( pInode->pShmNode==0 );
24517       closePendingFds(pFile);
24518       if( pInode->pPrev ){
24519         assert( pInode->pPrev->pNext==pInode );
24520         pInode->pPrev->pNext = pInode->pNext;
24521       }else{
24522         assert( inodeList==pInode );
24523         inodeList = pInode->pNext;
24524       }
24525       if( pInode->pNext ){
24526         assert( pInode->pNext->pPrev==pInode );
24527         pInode->pNext->pPrev = pInode->pPrev;
24528       }
24529       sqlite3_free(pInode);
24530     }
24531   }
24532 }
24533 
24534 /*
24535 ** Given a file descriptor, locate the unixInodeInfo object that
24536 ** describes that file descriptor.  Create a new one if necessary.  The
24537 ** return value might be uninitialized if an error occurs.
24538 **
24539 ** The mutex entered using the unixEnterMutex() function must be held
24540 ** when this function is called.
24541 **
24542 ** Return an appropriate error code.
24543 */
24544 static int findInodeInfo(
24545   unixFile *pFile,               /* Unix file with file desc used in the key */
24546   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24547 ){
24548   int rc;                        /* System call return code */
24549   int fd;                        /* The file descriptor for pFile */
24550   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24551   struct stat statbuf;           /* Low-level file information */
24552   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24553 
24554   assert( unixMutexHeld() );
24555 
24556   /* Get low-level information about the file that we can used to
24557   ** create a unique name for the file.
24558   */
24559   fd = pFile->h;
24560   rc = osFstat(fd, &statbuf);
24561   if( rc!=0 ){
24562     pFile->lastErrno = errno;
24563 #ifdef EOVERFLOW
24564     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24565 #endif
24566     return SQLITE_IOERR;
24567   }
24568 
24569 #ifdef __APPLE__
24570   /* On OS X on an msdos filesystem, the inode number is reported
24571   ** incorrectly for zero-size files.  See ticket #3260.  To work
24572   ** around this problem (we consider it a bug in OS X, not SQLite)
24573   ** we always increase the file size to 1 by writing a single byte
24574   ** prior to accessing the inode number.  The one byte written is
24575   ** an ASCII 'S' character which also happens to be the first byte
24576   ** in the header of every SQLite database.  In this way, if there
24577   ** is a race condition such that another thread has already populated
24578   ** the first page of the database, no damage is done.
24579   */
24580   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24581     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24582     if( rc!=1 ){
24583       pFile->lastErrno = errno;
24584       return SQLITE_IOERR;
24585     }
24586     rc = osFstat(fd, &statbuf);
24587     if( rc!=0 ){
24588       pFile->lastErrno = errno;
24589       return SQLITE_IOERR;
24590     }
24591   }
24592 #endif
24593 
24594   memset(&fileId, 0, sizeof(fileId));
24595   fileId.dev = statbuf.st_dev;
24596 #if OS_VXWORKS
24597   fileId.pId = pFile->pId;
24598 #else
24599   fileId.ino = statbuf.st_ino;
24600 #endif
24601   pInode = inodeList;
24602   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24603     pInode = pInode->pNext;
24604   }
24605   if( pInode==0 ){
24606     pInode = sqlite3_malloc( sizeof(*pInode) );
24607     if( pInode==0 ){
24608       return SQLITE_NOMEM;
24609     }
24610     memset(pInode, 0, sizeof(*pInode));
24611     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24612     pInode->nRef = 1;
24613     pInode->pNext = inodeList;
24614     pInode->pPrev = 0;
24615     if( inodeList ) inodeList->pPrev = pInode;
24616     inodeList = pInode;
24617   }else{
24618     pInode->nRef++;
24619   }
24620   *ppInode = pInode;
24621   return SQLITE_OK;
24622 }
24623 
24624 
24625 /*
24626 ** Check a unixFile that is a database.  Verify the following:
24627 **
24628 ** (1) There is exactly one hard link on the file
24629 ** (2) The file is not a symbolic link
24630 ** (3) The file has not been renamed or unlinked
24631 **
24632 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
24633 */
24634 static void verifyDbFile(unixFile *pFile){
24635   struct stat buf;
24636   int rc;
24637   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
24638     /* One or more of the following warnings have already been issued.  Do not
24639     ** repeat them so as not to clutter the error log */
24640     return;
24641   }
24642   rc = osFstat(pFile->h, &buf);
24643   if( rc!=0 ){
24644     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
24645     pFile->ctrlFlags |= UNIXFILE_WARNED;
24646     return;
24647   }
24648   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
24649     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
24650     pFile->ctrlFlags |= UNIXFILE_WARNED;
24651     return;
24652   }
24653   if( buf.st_nlink>1 ){
24654     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
24655     pFile->ctrlFlags |= UNIXFILE_WARNED;
24656     return;
24657   }
24658   if( pFile->pInode!=0
24659    && ((rc = osStat(pFile->zPath, &buf))!=0
24660        || buf.st_ino!=pFile->pInode->fileId.ino)
24661   ){
24662     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
24663     pFile->ctrlFlags |= UNIXFILE_WARNED;
24664     return;
24665   }
24666 }
24667 
24668 
24669 /*
24670 ** This routine checks if there is a RESERVED lock held on the specified
24671 ** file by this or any other process. If such a lock is held, set *pResOut
24672 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24673 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24674 */
24675 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24676   int rc = SQLITE_OK;
24677   int reserved = 0;
24678   unixFile *pFile = (unixFile*)id;
24679 
24680   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24681 
24682   assert( pFile );
24683   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24684 
24685   /* Check if a thread in this process holds such a lock */
24686   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24687     reserved = 1;
24688   }
24689 
24690   /* Otherwise see if some other process holds it.
24691   */
24692 #ifndef __DJGPP__
24693   if( !reserved && !pFile->pInode->bProcessLock ){
24694     struct flock lock;
24695     lock.l_whence = SEEK_SET;
24696     lock.l_start = RESERVED_BYTE;
24697     lock.l_len = 1;
24698     lock.l_type = F_WRLCK;
24699     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24700       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24701       pFile->lastErrno = errno;
24702     } else if( lock.l_type!=F_UNLCK ){
24703       reserved = 1;
24704     }
24705   }
24706 #endif
24707   
24708   unixLeaveMutex();
24709   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24710 
24711   *pResOut = reserved;
24712   return rc;
24713 }
24714 
24715 /*
24716 ** Attempt to set a system-lock on the file pFile.  The lock is 
24717 ** described by pLock.
24718 **
24719 ** If the pFile was opened read/write from unix-excl, then the only lock
24720 ** ever obtained is an exclusive lock, and it is obtained exactly once
24721 ** the first time any lock is attempted.  All subsequent system locking
24722 ** operations become no-ops.  Locking operations still happen internally,
24723 ** in order to coordinate access between separate database connections
24724 ** within this process, but all of that is handled in memory and the
24725 ** operating system does not participate.
24726 **
24727 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24728 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24729 ** and is read-only.
24730 **
24731 ** Zero is returned if the call completes successfully, or -1 if a call
24732 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24733 */
24734 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24735   int rc;
24736   unixInodeInfo *pInode = pFile->pInode;
24737   assert( unixMutexHeld() );
24738   assert( pInode!=0 );
24739   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24740    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24741   ){
24742     if( pInode->bProcessLock==0 ){
24743       struct flock lock;
24744       assert( pInode->nLock==0 );
24745       lock.l_whence = SEEK_SET;
24746       lock.l_start = SHARED_FIRST;
24747       lock.l_len = SHARED_SIZE;
24748       lock.l_type = F_WRLCK;
24749       rc = osFcntl(pFile->h, F_SETLK, &lock);
24750       if( rc<0 ) return rc;
24751       pInode->bProcessLock = 1;
24752       pInode->nLock++;
24753     }else{
24754       rc = 0;
24755     }
24756   }else{
24757     rc = osFcntl(pFile->h, F_SETLK, pLock);
24758   }
24759   return rc;
24760 }
24761 
24762 /*
24763 ** Lock the file with the lock specified by parameter eFileLock - one
24764 ** of the following:
24765 **
24766 **     (1) SHARED_LOCK
24767 **     (2) RESERVED_LOCK
24768 **     (3) PENDING_LOCK
24769 **     (4) EXCLUSIVE_LOCK
24770 **
24771 ** Sometimes when requesting one lock state, additional lock states
24772 ** are inserted in between.  The locking might fail on one of the later
24773 ** transitions leaving the lock state different from what it started but
24774 ** still short of its goal.  The following chart shows the allowed
24775 ** transitions and the inserted intermediate states:
24776 **
24777 **    UNLOCKED -> SHARED
24778 **    SHARED -> RESERVED
24779 **    SHARED -> (PENDING) -> EXCLUSIVE
24780 **    RESERVED -> (PENDING) -> EXCLUSIVE
24781 **    PENDING -> EXCLUSIVE
24782 **
24783 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24784 ** routine to lower a locking level.
24785 */
24786 static int unixLock(sqlite3_file *id, int eFileLock){
24787   /* The following describes the implementation of the various locks and
24788   ** lock transitions in terms of the POSIX advisory shared and exclusive
24789   ** lock primitives (called read-locks and write-locks below, to avoid
24790   ** confusion with SQLite lock names). The algorithms are complicated
24791   ** slightly in order to be compatible with windows systems simultaneously
24792   ** accessing the same database file, in case that is ever required.
24793   **
24794   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24795   ** byte', each single bytes at well known offsets, and the 'shared byte
24796   ** range', a range of 510 bytes at a well known offset.
24797   **
24798   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24799   ** byte'.  If this is successful, a random byte from the 'shared byte
24800   ** range' is read-locked and the lock on the 'pending byte' released.
24801   **
24802   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24803   ** A RESERVED lock is implemented by grabbing a write-lock on the
24804   ** 'reserved byte'. 
24805   **
24806   ** A process may only obtain a PENDING lock after it has obtained a
24807   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24808   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24809   ** obtained, but existing SHARED locks are allowed to persist. A process
24810   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24811   ** This property is used by the algorithm for rolling back a journal file
24812   ** after a crash.
24813   **
24814   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24815   ** implemented by obtaining a write-lock on the entire 'shared byte
24816   ** range'. Since all other locks require a read-lock on one of the bytes
24817   ** within this range, this ensures that no other locks are held on the
24818   ** database. 
24819   **
24820   ** The reason a single byte cannot be used instead of the 'shared byte
24821   ** range' is that some versions of windows do not support read-locks. By
24822   ** locking a random byte from a range, concurrent SHARED locks may exist
24823   ** even if the locking primitive used is always a write-lock.
24824   */
24825   int rc = SQLITE_OK;
24826   unixFile *pFile = (unixFile*)id;
24827   unixInodeInfo *pInode;
24828   struct flock lock;
24829   int tErrno = 0;
24830 
24831   assert( pFile );
24832   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24833       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24834       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24835 
24836   /* If there is already a lock of this type or more restrictive on the
24837   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24838   ** unixEnterMutex() hasn't been called yet.
24839   */
24840   if( pFile->eFileLock>=eFileLock ){
24841     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24842             azFileLock(eFileLock)));
24843     return SQLITE_OK;
24844   }
24845 
24846   /* Make sure the locking sequence is correct.
24847   **  (1) We never move from unlocked to anything higher than shared lock.
24848   **  (2) SQLite never explicitly requests a pendig lock.
24849   **  (3) A shared lock is always held when a reserve lock is requested.
24850   */
24851   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24852   assert( eFileLock!=PENDING_LOCK );
24853   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24854 
24855   /* This mutex is needed because pFile->pInode is shared across threads
24856   */
24857   unixEnterMutex();
24858   pInode = pFile->pInode;
24859 
24860   /* If some thread using this PID has a lock via a different unixFile*
24861   ** handle that precludes the requested lock, return BUSY.
24862   */
24863   if( (pFile->eFileLock!=pInode->eFileLock && 
24864           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24865   ){
24866     rc = SQLITE_BUSY;
24867     goto end_lock;
24868   }
24869 
24870   /* If a SHARED lock is requested, and some thread using this PID already
24871   ** has a SHARED or RESERVED lock, then increment reference counts and
24872   ** return SQLITE_OK.
24873   */
24874   if( eFileLock==SHARED_LOCK && 
24875       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24876     assert( eFileLock==SHARED_LOCK );
24877     assert( pFile->eFileLock==0 );
24878     assert( pInode->nShared>0 );
24879     pFile->eFileLock = SHARED_LOCK;
24880     pInode->nShared++;
24881     pInode->nLock++;
24882     goto end_lock;
24883   }
24884 
24885 
24886   /* A PENDING lock is needed before acquiring a SHARED lock and before
24887   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24888   ** be released.
24889   */
24890   lock.l_len = 1L;
24891   lock.l_whence = SEEK_SET;
24892   if( eFileLock==SHARED_LOCK 
24893       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24894   ){
24895     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24896     lock.l_start = PENDING_BYTE;
24897     if( unixFileLock(pFile, &lock) ){
24898       tErrno = errno;
24899       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24900       if( rc!=SQLITE_BUSY ){
24901         pFile->lastErrno = tErrno;
24902       }
24903       goto end_lock;
24904     }
24905   }
24906 
24907 
24908   /* If control gets to this point, then actually go ahead and make
24909   ** operating system calls for the specified lock.
24910   */
24911   if( eFileLock==SHARED_LOCK ){
24912     assert( pInode->nShared==0 );
24913     assert( pInode->eFileLock==0 );
24914     assert( rc==SQLITE_OK );
24915 
24916     /* Now get the read-lock */
24917     lock.l_start = SHARED_FIRST;
24918     lock.l_len = SHARED_SIZE;
24919     if( unixFileLock(pFile, &lock) ){
24920       tErrno = errno;
24921       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24922     }
24923 
24924     /* Drop the temporary PENDING lock */
24925     lock.l_start = PENDING_BYTE;
24926     lock.l_len = 1L;
24927     lock.l_type = F_UNLCK;
24928     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24929       /* This could happen with a network mount */
24930       tErrno = errno;
24931       rc = SQLITE_IOERR_UNLOCK; 
24932     }
24933 
24934     if( rc ){
24935       if( rc!=SQLITE_BUSY ){
24936         pFile->lastErrno = tErrno;
24937       }
24938       goto end_lock;
24939     }else{
24940       pFile->eFileLock = SHARED_LOCK;
24941       pInode->nLock++;
24942       pInode->nShared = 1;
24943     }
24944   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24945     /* We are trying for an exclusive lock but another thread in this
24946     ** same process is still holding a shared lock. */
24947     rc = SQLITE_BUSY;
24948   }else{
24949     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24950     ** assumed that there is a SHARED or greater lock on the file
24951     ** already.
24952     */
24953     assert( 0!=pFile->eFileLock );
24954     lock.l_type = F_WRLCK;
24955 
24956     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24957     if( eFileLock==RESERVED_LOCK ){
24958       lock.l_start = RESERVED_BYTE;
24959       lock.l_len = 1L;
24960     }else{
24961       lock.l_start = SHARED_FIRST;
24962       lock.l_len = SHARED_SIZE;
24963     }
24964 
24965     if( unixFileLock(pFile, &lock) ){
24966       tErrno = errno;
24967       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24968       if( rc!=SQLITE_BUSY ){
24969         pFile->lastErrno = tErrno;
24970       }
24971     }
24972   }
24973   
24974 
24975 #ifdef SQLITE_DEBUG
24976   /* Set up the transaction-counter change checking flags when
24977   ** transitioning from a SHARED to a RESERVED lock.  The change
24978   ** from SHARED to RESERVED marks the beginning of a normal
24979   ** write operation (not a hot journal rollback).
24980   */
24981   if( rc==SQLITE_OK
24982    && pFile->eFileLock<=SHARED_LOCK
24983    && eFileLock==RESERVED_LOCK
24984   ){
24985     pFile->transCntrChng = 0;
24986     pFile->dbUpdate = 0;
24987     pFile->inNormalWrite = 1;
24988   }
24989 #endif
24990 
24991 
24992   if( rc==SQLITE_OK ){
24993     pFile->eFileLock = eFileLock;
24994     pInode->eFileLock = eFileLock;
24995   }else if( eFileLock==EXCLUSIVE_LOCK ){
24996     pFile->eFileLock = PENDING_LOCK;
24997     pInode->eFileLock = PENDING_LOCK;
24998   }
24999 
25000 end_lock:
25001   unixLeaveMutex();
25002   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
25003       rc==SQLITE_OK ? "ok" : "failed"));
25004   return rc;
25005 }
25006 
25007 /*
25008 ** Add the file descriptor used by file handle pFile to the corresponding
25009 ** pUnused list.
25010 */
25011 static void setPendingFd(unixFile *pFile){
25012   unixInodeInfo *pInode = pFile->pInode;
25013   UnixUnusedFd *p = pFile->pUnused;
25014   p->pNext = pInode->pUnused;
25015   pInode->pUnused = p;
25016   pFile->h = -1;
25017   pFile->pUnused = 0;
25018 }
25019 
25020 /*
25021 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25022 ** must be either NO_LOCK or SHARED_LOCK.
25023 **
25024 ** If the locking level of the file descriptor is already at or below
25025 ** the requested locking level, this routine is a no-op.
25026 ** 
25027 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25028 ** the byte range is divided into 2 parts and the first part is unlocked then
25029 ** set to a read lock, then the other part is simply unlocked.  This works 
25030 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
25031 ** remove the write lock on a region when a read lock is set.
25032 */
25033 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25034   unixFile *pFile = (unixFile*)id;
25035   unixInodeInfo *pInode;
25036   struct flock lock;
25037   int rc = SQLITE_OK;
25038 
25039   assert( pFile );
25040   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25041       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25042       getpid()));
25043 
25044   assert( eFileLock<=SHARED_LOCK );
25045   if( pFile->eFileLock<=eFileLock ){
25046     return SQLITE_OK;
25047   }
25048   unixEnterMutex();
25049   pInode = pFile->pInode;
25050   assert( pInode->nShared!=0 );
25051   if( pFile->eFileLock>SHARED_LOCK ){
25052     assert( pInode->eFileLock==pFile->eFileLock );
25053 
25054 #ifdef SQLITE_DEBUG
25055     /* When reducing a lock such that other processes can start
25056     ** reading the database file again, make sure that the
25057     ** transaction counter was updated if any part of the database
25058     ** file changed.  If the transaction counter is not updated,
25059     ** other connections to the same file might not realize that
25060     ** the file has changed and hence might not know to flush their
25061     ** cache.  The use of a stale cache can lead to database corruption.
25062     */
25063     pFile->inNormalWrite = 0;
25064 #endif
25065 
25066     /* downgrading to a shared lock on NFS involves clearing the write lock
25067     ** before establishing the readlock - to avoid a race condition we downgrade
25068     ** the lock in 2 blocks, so that part of the range will be covered by a 
25069     ** write lock until the rest is covered by a read lock:
25070     **  1:   [WWWWW]
25071     **  2:   [....W]
25072     **  3:   [RRRRW]
25073     **  4:   [RRRR.]
25074     */
25075     if( eFileLock==SHARED_LOCK ){
25076 
25077 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25078       (void)handleNFSUnlock;
25079       assert( handleNFSUnlock==0 );
25080 #endif
25081 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25082       if( handleNFSUnlock ){
25083         int tErrno;               /* Error code from system call errors */
25084         off_t divSize = SHARED_SIZE - 1;
25085         
25086         lock.l_type = F_UNLCK;
25087         lock.l_whence = SEEK_SET;
25088         lock.l_start = SHARED_FIRST;
25089         lock.l_len = divSize;
25090         if( unixFileLock(pFile, &lock)==(-1) ){
25091           tErrno = errno;
25092           rc = SQLITE_IOERR_UNLOCK;
25093           if( IS_LOCK_ERROR(rc) ){
25094             pFile->lastErrno = tErrno;
25095           }
25096           goto end_unlock;
25097         }
25098         lock.l_type = F_RDLCK;
25099         lock.l_whence = SEEK_SET;
25100         lock.l_start = SHARED_FIRST;
25101         lock.l_len = divSize;
25102         if( unixFileLock(pFile, &lock)==(-1) ){
25103           tErrno = errno;
25104           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25105           if( IS_LOCK_ERROR(rc) ){
25106             pFile->lastErrno = tErrno;
25107           }
25108           goto end_unlock;
25109         }
25110         lock.l_type = F_UNLCK;
25111         lock.l_whence = SEEK_SET;
25112         lock.l_start = SHARED_FIRST+divSize;
25113         lock.l_len = SHARED_SIZE-divSize;
25114         if( unixFileLock(pFile, &lock)==(-1) ){
25115           tErrno = errno;
25116           rc = SQLITE_IOERR_UNLOCK;
25117           if( IS_LOCK_ERROR(rc) ){
25118             pFile->lastErrno = tErrno;
25119           }
25120           goto end_unlock;
25121         }
25122       }else
25123 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25124       {
25125         lock.l_type = F_RDLCK;
25126         lock.l_whence = SEEK_SET;
25127         lock.l_start = SHARED_FIRST;
25128         lock.l_len = SHARED_SIZE;
25129         if( unixFileLock(pFile, &lock) ){
25130           /* In theory, the call to unixFileLock() cannot fail because another
25131           ** process is holding an incompatible lock. If it does, this 
25132           ** indicates that the other process is not following the locking
25133           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25134           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
25135           ** an assert to fail). */ 
25136           rc = SQLITE_IOERR_RDLOCK;
25137           pFile->lastErrno = errno;
25138           goto end_unlock;
25139         }
25140       }
25141     }
25142     lock.l_type = F_UNLCK;
25143     lock.l_whence = SEEK_SET;
25144     lock.l_start = PENDING_BYTE;
25145     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
25146     if( unixFileLock(pFile, &lock)==0 ){
25147       pInode->eFileLock = SHARED_LOCK;
25148     }else{
25149       rc = SQLITE_IOERR_UNLOCK;
25150       pFile->lastErrno = errno;
25151       goto end_unlock;
25152     }
25153   }
25154   if( eFileLock==NO_LOCK ){
25155     /* Decrement the shared lock counter.  Release the lock using an
25156     ** OS call only when all threads in this same process have released
25157     ** the lock.
25158     */
25159     pInode->nShared--;
25160     if( pInode->nShared==0 ){
25161       lock.l_type = F_UNLCK;
25162       lock.l_whence = SEEK_SET;
25163       lock.l_start = lock.l_len = 0L;
25164       if( unixFileLock(pFile, &lock)==0 ){
25165         pInode->eFileLock = NO_LOCK;
25166       }else{
25167         rc = SQLITE_IOERR_UNLOCK;
25168         pFile->lastErrno = errno;
25169         pInode->eFileLock = NO_LOCK;
25170         pFile->eFileLock = NO_LOCK;
25171       }
25172     }
25173 
25174     /* Decrement the count of locks against this same file.  When the
25175     ** count reaches zero, close any other file descriptors whose close
25176     ** was deferred because of outstanding locks.
25177     */
25178     pInode->nLock--;
25179     assert( pInode->nLock>=0 );
25180     if( pInode->nLock==0 ){
25181       closePendingFds(pFile);
25182     }
25183   }
25184 
25185 end_unlock:
25186   unixLeaveMutex();
25187   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25188   return rc;
25189 }
25190 
25191 /*
25192 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25193 ** must be either NO_LOCK or SHARED_LOCK.
25194 **
25195 ** If the locking level of the file descriptor is already at or below
25196 ** the requested locking level, this routine is a no-op.
25197 */
25198 static int unixUnlock(sqlite3_file *id, int eFileLock){
25199 #if SQLITE_MAX_MMAP_SIZE>0
25200   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
25201 #endif
25202   return posixUnlock(id, eFileLock, 0);
25203 }
25204 
25205 #if SQLITE_MAX_MMAP_SIZE>0
25206 static int unixMapfile(unixFile *pFd, i64 nByte);
25207 static void unixUnmapfile(unixFile *pFd);
25208 #endif
25209 
25210 /*
25211 ** This function performs the parts of the "close file" operation 
25212 ** common to all locking schemes. It closes the directory and file
25213 ** handles, if they are valid, and sets all fields of the unixFile
25214 ** structure to 0.
25215 **
25216 ** It is *not* necessary to hold the mutex when this routine is called,
25217 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
25218 ** vxworksReleaseFileId() routine.
25219 */
25220 static int closeUnixFile(sqlite3_file *id){
25221   unixFile *pFile = (unixFile*)id;
25222 #if SQLITE_MAX_MMAP_SIZE>0
25223   unixUnmapfile(pFile);
25224 #endif
25225   if( pFile->h>=0 ){
25226     robust_close(pFile, pFile->h, __LINE__);
25227     pFile->h = -1;
25228   }
25229 #if OS_VXWORKS
25230   if( pFile->pId ){
25231     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
25232       osUnlink(pFile->pId->zCanonicalName);
25233     }
25234     vxworksReleaseFileId(pFile->pId);
25235     pFile->pId = 0;
25236   }
25237 #endif
25238   OSTRACE(("CLOSE   %-3d\n", pFile->h));
25239   OpenCounter(-1);
25240   sqlite3_free(pFile->pUnused);
25241   memset(pFile, 0, sizeof(unixFile));
25242   return SQLITE_OK;
25243 }
25244 
25245 /*
25246 ** Close a file.
25247 */
25248 static int unixClose(sqlite3_file *id){
25249   int rc = SQLITE_OK;
25250   unixFile *pFile = (unixFile *)id;
25251   verifyDbFile(pFile);
25252   unixUnlock(id, NO_LOCK);
25253   unixEnterMutex();
25254 
25255   /* unixFile.pInode is always valid here. Otherwise, a different close
25256   ** routine (e.g. nolockClose()) would be called instead.
25257   */
25258   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25259   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25260     /* If there are outstanding locks, do not actually close the file just
25261     ** yet because that would clear those locks.  Instead, add the file
25262     ** descriptor to pInode->pUnused list.  It will be automatically closed 
25263     ** when the last lock is cleared.
25264     */
25265     setPendingFd(pFile);
25266   }
25267   releaseInodeInfo(pFile);
25268   rc = closeUnixFile(id);
25269   unixLeaveMutex();
25270   return rc;
25271 }
25272 
25273 /************** End of the posix advisory lock implementation *****************
25274 ******************************************************************************/
25275 
25276 /******************************************************************************
25277 ****************************** No-op Locking **********************************
25278 **
25279 ** Of the various locking implementations available, this is by far the
25280 ** simplest:  locking is ignored.  No attempt is made to lock the database
25281 ** file for reading or writing.
25282 **
25283 ** This locking mode is appropriate for use on read-only databases
25284 ** (ex: databases that are burned into CD-ROM, for example.)  It can
25285 ** also be used if the application employs some external mechanism to
25286 ** prevent simultaneous access of the same database by two or more
25287 ** database connections.  But there is a serious risk of database
25288 ** corruption if this locking mode is used in situations where multiple
25289 ** database connections are accessing the same database file at the same
25290 ** time and one or more of those connections are writing.
25291 */
25292 
25293 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25294   UNUSED_PARAMETER(NotUsed);
25295   *pResOut = 0;
25296   return SQLITE_OK;
25297 }
25298 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25299   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25300   return SQLITE_OK;
25301 }
25302 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25303   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25304   return SQLITE_OK;
25305 }
25306 
25307 /*
25308 ** Close the file.
25309 */
25310 static int nolockClose(sqlite3_file *id) {
25311   return closeUnixFile(id);
25312 }
25313 
25314 /******************* End of the no-op lock implementation *********************
25315 ******************************************************************************/
25316 
25317 /******************************************************************************
25318 ************************* Begin dot-file Locking ******************************
25319 **
25320 ** The dotfile locking implementation uses the existence of separate lock
25321 ** files (really a directory) to control access to the database.  This works
25322 ** on just about every filesystem imaginable.  But there are serious downsides:
25323 **
25324 **    (1)  There is zero concurrency.  A single reader blocks all other
25325 **         connections from reading or writing the database.
25326 **
25327 **    (2)  An application crash or power loss can leave stale lock files
25328 **         sitting around that need to be cleared manually.
25329 **
25330 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25331 ** other locking strategy is available.
25332 **
25333 ** Dotfile locking works by creating a subdirectory in the same directory as
25334 ** the database and with the same name but with a ".lock" extension added.
25335 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
25336 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25337 */
25338 
25339 /*
25340 ** The file suffix added to the data base filename in order to create the
25341 ** lock directory.
25342 */
25343 #define DOTLOCK_SUFFIX ".lock"
25344 
25345 /*
25346 ** This routine checks if there is a RESERVED lock held on the specified
25347 ** file by this or any other process. If such a lock is held, set *pResOut
25348 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25349 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25350 **
25351 ** In dotfile locking, either a lock exists or it does not.  So in this
25352 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25353 ** is held on the file and false if the file is unlocked.
25354 */
25355 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25356   int rc = SQLITE_OK;
25357   int reserved = 0;
25358   unixFile *pFile = (unixFile*)id;
25359 
25360   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25361   
25362   assert( pFile );
25363 
25364   /* Check if a thread in this process holds such a lock */
25365   if( pFile->eFileLock>SHARED_LOCK ){
25366     /* Either this connection or some other connection in the same process
25367     ** holds a lock on the file.  No need to check further. */
25368     reserved = 1;
25369   }else{
25370     /* The lock is held if and only if the lockfile exists */
25371     const char *zLockFile = (const char*)pFile->lockingContext;
25372     reserved = osAccess(zLockFile, 0)==0;
25373   }
25374   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25375   *pResOut = reserved;
25376   return rc;
25377 }
25378 
25379 /*
25380 ** Lock the file with the lock specified by parameter eFileLock - one
25381 ** of the following:
25382 **
25383 **     (1) SHARED_LOCK
25384 **     (2) RESERVED_LOCK
25385 **     (3) PENDING_LOCK
25386 **     (4) EXCLUSIVE_LOCK
25387 **
25388 ** Sometimes when requesting one lock state, additional lock states
25389 ** are inserted in between.  The locking might fail on one of the later
25390 ** transitions leaving the lock state different from what it started but
25391 ** still short of its goal.  The following chart shows the allowed
25392 ** transitions and the inserted intermediate states:
25393 **
25394 **    UNLOCKED -> SHARED
25395 **    SHARED -> RESERVED
25396 **    SHARED -> (PENDING) -> EXCLUSIVE
25397 **    RESERVED -> (PENDING) -> EXCLUSIVE
25398 **    PENDING -> EXCLUSIVE
25399 **
25400 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25401 ** routine to lower a locking level.
25402 **
25403 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
25404 ** But we track the other locking levels internally.
25405 */
25406 static int dotlockLock(sqlite3_file *id, int eFileLock) {
25407   unixFile *pFile = (unixFile*)id;
25408   char *zLockFile = (char *)pFile->lockingContext;
25409   int rc = SQLITE_OK;
25410 
25411 
25412   /* If we have any lock, then the lock file already exists.  All we have
25413   ** to do is adjust our internal record of the lock level.
25414   */
25415   if( pFile->eFileLock > NO_LOCK ){
25416     pFile->eFileLock = eFileLock;
25417     /* Always update the timestamp on the old file */
25418 #ifdef HAVE_UTIME
25419     utime(zLockFile, NULL);
25420 #else
25421     utimes(zLockFile, NULL);
25422 #endif
25423     return SQLITE_OK;
25424   }
25425   
25426   /* grab an exclusive lock */
25427   rc = osMkdir(zLockFile, 0777);
25428   if( rc<0 ){
25429     /* failed to open/create the lock directory */
25430     int tErrno = errno;
25431     if( EEXIST == tErrno ){
25432       rc = SQLITE_BUSY;
25433     } else {
25434       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25435       if( IS_LOCK_ERROR(rc) ){
25436         pFile->lastErrno = tErrno;
25437       }
25438     }
25439     return rc;
25440   } 
25441   
25442   /* got it, set the type and return ok */
25443   pFile->eFileLock = eFileLock;
25444   return rc;
25445 }
25446 
25447 /*
25448 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25449 ** must be either NO_LOCK or SHARED_LOCK.
25450 **
25451 ** If the locking level of the file descriptor is already at or below
25452 ** the requested locking level, this routine is a no-op.
25453 **
25454 ** When the locking level reaches NO_LOCK, delete the lock file.
25455 */
25456 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
25457   unixFile *pFile = (unixFile*)id;
25458   char *zLockFile = (char *)pFile->lockingContext;
25459   int rc;
25460 
25461   assert( pFile );
25462   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
25463            pFile->eFileLock, getpid()));
25464   assert( eFileLock<=SHARED_LOCK );
25465   
25466   /* no-op if possible */
25467   if( pFile->eFileLock==eFileLock ){
25468     return SQLITE_OK;
25469   }
25470 
25471   /* To downgrade to shared, simply update our internal notion of the
25472   ** lock state.  No need to mess with the file on disk.
25473   */
25474   if( eFileLock==SHARED_LOCK ){
25475     pFile->eFileLock = SHARED_LOCK;
25476     return SQLITE_OK;
25477   }
25478   
25479   /* To fully unlock the database, delete the lock file */
25480   assert( eFileLock==NO_LOCK );
25481   rc = osRmdir(zLockFile);
25482   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25483   if( rc<0 ){
25484     int tErrno = errno;
25485     rc = 0;
25486     if( ENOENT != tErrno ){
25487       rc = SQLITE_IOERR_UNLOCK;
25488     }
25489     if( IS_LOCK_ERROR(rc) ){
25490       pFile->lastErrno = tErrno;
25491     }
25492     return rc; 
25493   }
25494   pFile->eFileLock = NO_LOCK;
25495   return SQLITE_OK;
25496 }
25497 
25498 /*
25499 ** Close a file.  Make sure the lock has been released before closing.
25500 */
25501 static int dotlockClose(sqlite3_file *id) {
25502   int rc = SQLITE_OK;
25503   if( id ){
25504     unixFile *pFile = (unixFile*)id;
25505     dotlockUnlock(id, NO_LOCK);
25506     sqlite3_free(pFile->lockingContext);
25507     rc = closeUnixFile(id);
25508   }
25509   return rc;
25510 }
25511 /****************** End of the dot-file lock implementation *******************
25512 ******************************************************************************/
25513 
25514 /******************************************************************************
25515 ************************** Begin flock Locking ********************************
25516 **
25517 ** Use the flock() system call to do file locking.
25518 **
25519 ** flock() locking is like dot-file locking in that the various
25520 ** fine-grain locking levels supported by SQLite are collapsed into
25521 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
25522 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25523 ** still works when you do this, but concurrency is reduced since
25524 ** only a single process can be reading the database at a time.
25525 **
25526 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25527 ** compiling for VXWORKS.
25528 */
25529 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25530 
25531 /*
25532 ** Retry flock() calls that fail with EINTR
25533 */
25534 #ifdef EINTR
25535 static int robust_flock(int fd, int op){
25536   int rc;
25537   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25538   return rc;
25539 }
25540 #else
25541 # define robust_flock(a,b) flock(a,b)
25542 #endif
25543      
25544 
25545 /*
25546 ** This routine checks if there is a RESERVED lock held on the specified
25547 ** file by this or any other process. If such a lock is held, set *pResOut
25548 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25549 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25550 */
25551 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25552   int rc = SQLITE_OK;
25553   int reserved = 0;
25554   unixFile *pFile = (unixFile*)id;
25555   
25556   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25557   
25558   assert( pFile );
25559   
25560   /* Check if a thread in this process holds such a lock */
25561   if( pFile->eFileLock>SHARED_LOCK ){
25562     reserved = 1;
25563   }
25564   
25565   /* Otherwise see if some other process holds it. */
25566   if( !reserved ){
25567     /* attempt to get the lock */
25568     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25569     if( !lrc ){
25570       /* got the lock, unlock it */
25571       lrc = robust_flock(pFile->h, LOCK_UN);
25572       if ( lrc ) {
25573         int tErrno = errno;
25574         /* unlock failed with an error */
25575         lrc = SQLITE_IOERR_UNLOCK; 
25576         if( IS_LOCK_ERROR(lrc) ){
25577           pFile->lastErrno = tErrno;
25578           rc = lrc;
25579         }
25580       }
25581     } else {
25582       int tErrno = errno;
25583       reserved = 1;
25584       /* someone else might have it reserved */
25585       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
25586       if( IS_LOCK_ERROR(lrc) ){
25587         pFile->lastErrno = tErrno;
25588         rc = lrc;
25589       }
25590     }
25591   }
25592   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25593 
25594 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25595   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25596     rc = SQLITE_OK;
25597     reserved=1;
25598   }
25599 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25600   *pResOut = reserved;
25601   return rc;
25602 }
25603 
25604 /*
25605 ** Lock the file with the lock specified by parameter eFileLock - one
25606 ** of the following:
25607 **
25608 **     (1) SHARED_LOCK
25609 **     (2) RESERVED_LOCK
25610 **     (3) PENDING_LOCK
25611 **     (4) EXCLUSIVE_LOCK
25612 **
25613 ** Sometimes when requesting one lock state, additional lock states
25614 ** are inserted in between.  The locking might fail on one of the later
25615 ** transitions leaving the lock state different from what it started but
25616 ** still short of its goal.  The following chart shows the allowed
25617 ** transitions and the inserted intermediate states:
25618 **
25619 **    UNLOCKED -> SHARED
25620 **    SHARED -> RESERVED
25621 **    SHARED -> (PENDING) -> EXCLUSIVE
25622 **    RESERVED -> (PENDING) -> EXCLUSIVE
25623 **    PENDING -> EXCLUSIVE
25624 **
25625 ** flock() only really support EXCLUSIVE locks.  We track intermediate
25626 ** lock states in the sqlite3_file structure, but all locks SHARED or
25627 ** above are really EXCLUSIVE locks and exclude all other processes from
25628 ** access the file.
25629 **
25630 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25631 ** routine to lower a locking level.
25632 */
25633 static int flockLock(sqlite3_file *id, int eFileLock) {
25634   int rc = SQLITE_OK;
25635   unixFile *pFile = (unixFile*)id;
25636 
25637   assert( pFile );
25638 
25639   /* if we already have a lock, it is exclusive.  
25640   ** Just adjust level and punt on outta here. */
25641   if (pFile->eFileLock > NO_LOCK) {
25642     pFile->eFileLock = eFileLock;
25643     return SQLITE_OK;
25644   }
25645   
25646   /* grab an exclusive lock */
25647   
25648   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25649     int tErrno = errno;
25650     /* didn't get, must be busy */
25651     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25652     if( IS_LOCK_ERROR(rc) ){
25653       pFile->lastErrno = tErrno;
25654     }
25655   } else {
25656     /* got it, set the type and return ok */
25657     pFile->eFileLock = eFileLock;
25658   }
25659   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
25660            rc==SQLITE_OK ? "ok" : "failed"));
25661 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25662   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25663     rc = SQLITE_BUSY;
25664   }
25665 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25666   return rc;
25667 }
25668 
25669 
25670 /*
25671 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25672 ** must be either NO_LOCK or SHARED_LOCK.
25673 **
25674 ** If the locking level of the file descriptor is already at or below
25675 ** the requested locking level, this routine is a no-op.
25676 */
25677 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25678   unixFile *pFile = (unixFile*)id;
25679   
25680   assert( pFile );
25681   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25682            pFile->eFileLock, getpid()));
25683   assert( eFileLock<=SHARED_LOCK );
25684   
25685   /* no-op if possible */
25686   if( pFile->eFileLock==eFileLock ){
25687     return SQLITE_OK;
25688   }
25689   
25690   /* shared can just be set because we always have an exclusive */
25691   if (eFileLock==SHARED_LOCK) {
25692     pFile->eFileLock = eFileLock;
25693     return SQLITE_OK;
25694   }
25695   
25696   /* no, really, unlock. */
25697   if( robust_flock(pFile->h, LOCK_UN) ){
25698 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25699     return SQLITE_OK;
25700 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25701     return SQLITE_IOERR_UNLOCK;
25702   }else{
25703     pFile->eFileLock = NO_LOCK;
25704     return SQLITE_OK;
25705   }
25706 }
25707 
25708 /*
25709 ** Close a file.
25710 */
25711 static int flockClose(sqlite3_file *id) {
25712   int rc = SQLITE_OK;
25713   if( id ){
25714     flockUnlock(id, NO_LOCK);
25715     rc = closeUnixFile(id);
25716   }
25717   return rc;
25718 }
25719 
25720 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25721 
25722 /******************* End of the flock lock implementation *********************
25723 ******************************************************************************/
25724 
25725 /******************************************************************************
25726 ************************ Begin Named Semaphore Locking ************************
25727 **
25728 ** Named semaphore locking is only supported on VxWorks.
25729 **
25730 ** Semaphore locking is like dot-lock and flock in that it really only
25731 ** supports EXCLUSIVE locking.  Only a single process can read or write
25732 ** the database file at a time.  This reduces potential concurrency, but
25733 ** makes the lock implementation much easier.
25734 */
25735 #if OS_VXWORKS
25736 
25737 /*
25738 ** This routine checks if there is a RESERVED lock held on the specified
25739 ** file by this or any other process. If such a lock is held, set *pResOut
25740 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25741 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25742 */
25743 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25744   int rc = SQLITE_OK;
25745   int reserved = 0;
25746   unixFile *pFile = (unixFile*)id;
25747 
25748   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25749   
25750   assert( pFile );
25751 
25752   /* Check if a thread in this process holds such a lock */
25753   if( pFile->eFileLock>SHARED_LOCK ){
25754     reserved = 1;
25755   }
25756   
25757   /* Otherwise see if some other process holds it. */
25758   if( !reserved ){
25759     sem_t *pSem = pFile->pInode->pSem;
25760     struct stat statBuf;
25761 
25762     if( sem_trywait(pSem)==-1 ){
25763       int tErrno = errno;
25764       if( EAGAIN != tErrno ){
25765         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25766         pFile->lastErrno = tErrno;
25767       } else {
25768         /* someone else has the lock when we are in NO_LOCK */
25769         reserved = (pFile->eFileLock < SHARED_LOCK);
25770       }
25771     }else{
25772       /* we could have it if we want it */
25773       sem_post(pSem);
25774     }
25775   }
25776   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25777 
25778   *pResOut = reserved;
25779   return rc;
25780 }
25781 
25782 /*
25783 ** Lock the file with the lock specified by parameter eFileLock - one
25784 ** of the following:
25785 **
25786 **     (1) SHARED_LOCK
25787 **     (2) RESERVED_LOCK
25788 **     (3) PENDING_LOCK
25789 **     (4) EXCLUSIVE_LOCK
25790 **
25791 ** Sometimes when requesting one lock state, additional lock states
25792 ** are inserted in between.  The locking might fail on one of the later
25793 ** transitions leaving the lock state different from what it started but
25794 ** still short of its goal.  The following chart shows the allowed
25795 ** transitions and the inserted intermediate states:
25796 **
25797 **    UNLOCKED -> SHARED
25798 **    SHARED -> RESERVED
25799 **    SHARED -> (PENDING) -> EXCLUSIVE
25800 **    RESERVED -> (PENDING) -> EXCLUSIVE
25801 **    PENDING -> EXCLUSIVE
25802 **
25803 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25804 ** lock states in the sqlite3_file structure, but all locks SHARED or
25805 ** above are really EXCLUSIVE locks and exclude all other processes from
25806 ** access the file.
25807 **
25808 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25809 ** routine to lower a locking level.
25810 */
25811 static int semLock(sqlite3_file *id, int eFileLock) {
25812   unixFile *pFile = (unixFile*)id;
25813   int fd;
25814   sem_t *pSem = pFile->pInode->pSem;
25815   int rc = SQLITE_OK;
25816 
25817   /* if we already have a lock, it is exclusive.  
25818   ** Just adjust level and punt on outta here. */
25819   if (pFile->eFileLock > NO_LOCK) {
25820     pFile->eFileLock = eFileLock;
25821     rc = SQLITE_OK;
25822     goto sem_end_lock;
25823   }
25824   
25825   /* lock semaphore now but bail out when already locked. */
25826   if( sem_trywait(pSem)==-1 ){
25827     rc = SQLITE_BUSY;
25828     goto sem_end_lock;
25829   }
25830 
25831   /* got it, set the type and return ok */
25832   pFile->eFileLock = eFileLock;
25833 
25834  sem_end_lock:
25835   return rc;
25836 }
25837 
25838 /*
25839 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25840 ** must be either NO_LOCK or SHARED_LOCK.
25841 **
25842 ** If the locking level of the file descriptor is already at or below
25843 ** the requested locking level, this routine is a no-op.
25844 */
25845 static int semUnlock(sqlite3_file *id, int eFileLock) {
25846   unixFile *pFile = (unixFile*)id;
25847   sem_t *pSem = pFile->pInode->pSem;
25848 
25849   assert( pFile );
25850   assert( pSem );
25851   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25852            pFile->eFileLock, getpid()));
25853   assert( eFileLock<=SHARED_LOCK );
25854   
25855   /* no-op if possible */
25856   if( pFile->eFileLock==eFileLock ){
25857     return SQLITE_OK;
25858   }
25859   
25860   /* shared can just be set because we always have an exclusive */
25861   if (eFileLock==SHARED_LOCK) {
25862     pFile->eFileLock = eFileLock;
25863     return SQLITE_OK;
25864   }
25865   
25866   /* no, really unlock. */
25867   if ( sem_post(pSem)==-1 ) {
25868     int rc, tErrno = errno;
25869     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25870     if( IS_LOCK_ERROR(rc) ){
25871       pFile->lastErrno = tErrno;
25872     }
25873     return rc; 
25874   }
25875   pFile->eFileLock = NO_LOCK;
25876   return SQLITE_OK;
25877 }
25878 
25879 /*
25880  ** Close a file.
25881  */
25882 static int semClose(sqlite3_file *id) {
25883   if( id ){
25884     unixFile *pFile = (unixFile*)id;
25885     semUnlock(id, NO_LOCK);
25886     assert( pFile );
25887     unixEnterMutex();
25888     releaseInodeInfo(pFile);
25889     unixLeaveMutex();
25890     closeUnixFile(id);
25891   }
25892   return SQLITE_OK;
25893 }
25894 
25895 #endif /* OS_VXWORKS */
25896 /*
25897 ** Named semaphore locking is only available on VxWorks.
25898 **
25899 *************** End of the named semaphore lock implementation ****************
25900 ******************************************************************************/
25901 
25902 
25903 /******************************************************************************
25904 *************************** Begin AFP Locking *********************************
25905 **
25906 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25907 ** on Apple Macintosh computers - both OS9 and OSX.
25908 **
25909 ** Third-party implementations of AFP are available.  But this code here
25910 ** only works on OSX.
25911 */
25912 
25913 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25914 /*
25915 ** The afpLockingContext structure contains all afp lock specific state
25916 */
25917 typedef struct afpLockingContext afpLockingContext;
25918 struct afpLockingContext {
25919   int reserved;
25920   const char *dbPath;             /* Name of the open file */
25921 };
25922 
25923 struct ByteRangeLockPB2
25924 {
25925   unsigned long long offset;        /* offset to first byte to lock */
25926   unsigned long long length;        /* nbr of bytes to lock */
25927   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25928   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25929   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25930   int fd;                           /* file desc to assoc this lock with */
25931 };
25932 
25933 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25934 
25935 /*
25936 ** This is a utility for setting or clearing a bit-range lock on an
25937 ** AFP filesystem.
25938 ** 
25939 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25940 */
25941 static int afpSetLock(
25942   const char *path,              /* Name of the file to be locked or unlocked */
25943   unixFile *pFile,               /* Open file descriptor on path */
25944   unsigned long long offset,     /* First byte to be locked */
25945   unsigned long long length,     /* Number of bytes to lock */
25946   int setLockFlag                /* True to set lock.  False to clear lock */
25947 ){
25948   struct ByteRangeLockPB2 pb;
25949   int err;
25950   
25951   pb.unLockFlag = setLockFlag ? 0 : 1;
25952   pb.startEndFlag = 0;
25953   pb.offset = offset;
25954   pb.length = length; 
25955   pb.fd = pFile->h;
25956   
25957   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25958     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25959     offset, length));
25960   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25961   if ( err==-1 ) {
25962     int rc;
25963     int tErrno = errno;
25964     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25965              path, tErrno, strerror(tErrno)));
25966 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25967     rc = SQLITE_BUSY;
25968 #else
25969     rc = sqliteErrorFromPosixError(tErrno,
25970                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25971 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25972     if( IS_LOCK_ERROR(rc) ){
25973       pFile->lastErrno = tErrno;
25974     }
25975     return rc;
25976   } else {
25977     return SQLITE_OK;
25978   }
25979 }
25980 
25981 /*
25982 ** This routine checks if there is a RESERVED lock held on the specified
25983 ** file by this or any other process. If such a lock is held, set *pResOut
25984 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25985 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25986 */
25987 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25988   int rc = SQLITE_OK;
25989   int reserved = 0;
25990   unixFile *pFile = (unixFile*)id;
25991   afpLockingContext *context;
25992   
25993   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25994   
25995   assert( pFile );
25996   context = (afpLockingContext *) pFile->lockingContext;
25997   if( context->reserved ){
25998     *pResOut = 1;
25999     return SQLITE_OK;
26000   }
26001   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26002   
26003   /* Check if a thread in this process holds such a lock */
26004   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26005     reserved = 1;
26006   }
26007   
26008   /* Otherwise see if some other process holds it.
26009    */
26010   if( !reserved ){
26011     /* lock the RESERVED byte */
26012     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
26013     if( SQLITE_OK==lrc ){
26014       /* if we succeeded in taking the reserved lock, unlock it to restore
26015       ** the original state */
26016       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26017     } else {
26018       /* if we failed to get the lock then someone else must have it */
26019       reserved = 1;
26020     }
26021     if( IS_LOCK_ERROR(lrc) ){
26022       rc=lrc;
26023     }
26024   }
26025   
26026   unixLeaveMutex();
26027   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26028   
26029   *pResOut = reserved;
26030   return rc;
26031 }
26032 
26033 /*
26034 ** Lock the file with the lock specified by parameter eFileLock - one
26035 ** of the following:
26036 **
26037 **     (1) SHARED_LOCK
26038 **     (2) RESERVED_LOCK
26039 **     (3) PENDING_LOCK
26040 **     (4) EXCLUSIVE_LOCK
26041 **
26042 ** Sometimes when requesting one lock state, additional lock states
26043 ** are inserted in between.  The locking might fail on one of the later
26044 ** transitions leaving the lock state different from what it started but
26045 ** still short of its goal.  The following chart shows the allowed
26046 ** transitions and the inserted intermediate states:
26047 **
26048 **    UNLOCKED -> SHARED
26049 **    SHARED -> RESERVED
26050 **    SHARED -> (PENDING) -> EXCLUSIVE
26051 **    RESERVED -> (PENDING) -> EXCLUSIVE
26052 **    PENDING -> EXCLUSIVE
26053 **
26054 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26055 ** routine to lower a locking level.
26056 */
26057 static int afpLock(sqlite3_file *id, int eFileLock){
26058   int rc = SQLITE_OK;
26059   unixFile *pFile = (unixFile*)id;
26060   unixInodeInfo *pInode = pFile->pInode;
26061   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26062   
26063   assert( pFile );
26064   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26065            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26066            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26067 
26068   /* If there is already a lock of this type or more restrictive on the
26069   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26070   ** unixEnterMutex() hasn't been called yet.
26071   */
26072   if( pFile->eFileLock>=eFileLock ){
26073     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
26074            azFileLock(eFileLock)));
26075     return SQLITE_OK;
26076   }
26077 
26078   /* Make sure the locking sequence is correct
26079   **  (1) We never move from unlocked to anything higher than shared lock.
26080   **  (2) SQLite never explicitly requests a pendig lock.
26081   **  (3) A shared lock is always held when a reserve lock is requested.
26082   */
26083   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26084   assert( eFileLock!=PENDING_LOCK );
26085   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26086   
26087   /* This mutex is needed because pFile->pInode is shared across threads
26088   */
26089   unixEnterMutex();
26090   pInode = pFile->pInode;
26091 
26092   /* If some thread using this PID has a lock via a different unixFile*
26093   ** handle that precludes the requested lock, return BUSY.
26094   */
26095   if( (pFile->eFileLock!=pInode->eFileLock && 
26096        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26097      ){
26098     rc = SQLITE_BUSY;
26099     goto afp_end_lock;
26100   }
26101   
26102   /* If a SHARED lock is requested, and some thread using this PID already
26103   ** has a SHARED or RESERVED lock, then increment reference counts and
26104   ** return SQLITE_OK.
26105   */
26106   if( eFileLock==SHARED_LOCK && 
26107      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26108     assert( eFileLock==SHARED_LOCK );
26109     assert( pFile->eFileLock==0 );
26110     assert( pInode->nShared>0 );
26111     pFile->eFileLock = SHARED_LOCK;
26112     pInode->nShared++;
26113     pInode->nLock++;
26114     goto afp_end_lock;
26115   }
26116     
26117   /* A PENDING lock is needed before acquiring a SHARED lock and before
26118   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26119   ** be released.
26120   */
26121   if( eFileLock==SHARED_LOCK 
26122       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26123   ){
26124     int failed;
26125     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26126     if (failed) {
26127       rc = failed;
26128       goto afp_end_lock;
26129     }
26130   }
26131   
26132   /* If control gets to this point, then actually go ahead and make
26133   ** operating system calls for the specified lock.
26134   */
26135   if( eFileLock==SHARED_LOCK ){
26136     int lrc1, lrc2, lrc1Errno = 0;
26137     long lk, mask;
26138     
26139     assert( pInode->nShared==0 );
26140     assert( pInode->eFileLock==0 );
26141         
26142     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26143     /* Now get the read-lock SHARED_LOCK */
26144     /* note that the quality of the randomness doesn't matter that much */
26145     lk = random(); 
26146     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26147     lrc1 = afpSetLock(context->dbPath, pFile, 
26148           SHARED_FIRST+pInode->sharedByte, 1, 1);
26149     if( IS_LOCK_ERROR(lrc1) ){
26150       lrc1Errno = pFile->lastErrno;
26151     }
26152     /* Drop the temporary PENDING lock */
26153     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26154     
26155     if( IS_LOCK_ERROR(lrc1) ) {
26156       pFile->lastErrno = lrc1Errno;
26157       rc = lrc1;
26158       goto afp_end_lock;
26159     } else if( IS_LOCK_ERROR(lrc2) ){
26160       rc = lrc2;
26161       goto afp_end_lock;
26162     } else if( lrc1 != SQLITE_OK ) {
26163       rc = lrc1;
26164     } else {
26165       pFile->eFileLock = SHARED_LOCK;
26166       pInode->nLock++;
26167       pInode->nShared = 1;
26168     }
26169   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26170     /* We are trying for an exclusive lock but another thread in this
26171      ** same process is still holding a shared lock. */
26172     rc = SQLITE_BUSY;
26173   }else{
26174     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26175     ** assumed that there is a SHARED or greater lock on the file
26176     ** already.
26177     */
26178     int failed = 0;
26179     assert( 0!=pFile->eFileLock );
26180     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26181         /* Acquire a RESERVED lock */
26182         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26183       if( !failed ){
26184         context->reserved = 1;
26185       }
26186     }
26187     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26188       /* Acquire an EXCLUSIVE lock */
26189         
26190       /* Remove the shared lock before trying the range.  we'll need to 
26191       ** reestablish the shared lock if we can't get the  afpUnlock
26192       */
26193       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26194                          pInode->sharedByte, 1, 0)) ){
26195         int failed2 = SQLITE_OK;
26196         /* now attemmpt to get the exclusive lock range */
26197         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
26198                                SHARED_SIZE, 1);
26199         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
26200                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26201           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
26202           ** a critical I/O error
26203           */
26204           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
26205                SQLITE_IOERR_LOCK;
26206           goto afp_end_lock;
26207         } 
26208       }else{
26209         rc = failed; 
26210       }
26211     }
26212     if( failed ){
26213       rc = failed;
26214     }
26215   }
26216   
26217   if( rc==SQLITE_OK ){
26218     pFile->eFileLock = eFileLock;
26219     pInode->eFileLock = eFileLock;
26220   }else if( eFileLock==EXCLUSIVE_LOCK ){
26221     pFile->eFileLock = PENDING_LOCK;
26222     pInode->eFileLock = PENDING_LOCK;
26223   }
26224   
26225 afp_end_lock:
26226   unixLeaveMutex();
26227   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
26228          rc==SQLITE_OK ? "ok" : "failed"));
26229   return rc;
26230 }
26231 
26232 /*
26233 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26234 ** must be either NO_LOCK or SHARED_LOCK.
26235 **
26236 ** If the locking level of the file descriptor is already at or below
26237 ** the requested locking level, this routine is a no-op.
26238 */
26239 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26240   int rc = SQLITE_OK;
26241   unixFile *pFile = (unixFile*)id;
26242   unixInodeInfo *pInode;
26243   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26244   int skipShared = 0;
26245 #ifdef SQLITE_TEST
26246   int h = pFile->h;
26247 #endif
26248 
26249   assert( pFile );
26250   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26251            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26252            getpid()));
26253 
26254   assert( eFileLock<=SHARED_LOCK );
26255   if( pFile->eFileLock<=eFileLock ){
26256     return SQLITE_OK;
26257   }
26258   unixEnterMutex();
26259   pInode = pFile->pInode;
26260   assert( pInode->nShared!=0 );
26261   if( pFile->eFileLock>SHARED_LOCK ){
26262     assert( pInode->eFileLock==pFile->eFileLock );
26263     SimulateIOErrorBenign(1);
26264     SimulateIOError( h=(-1) )
26265     SimulateIOErrorBenign(0);
26266     
26267 #ifdef SQLITE_DEBUG
26268     /* When reducing a lock such that other processes can start
26269     ** reading the database file again, make sure that the
26270     ** transaction counter was updated if any part of the database
26271     ** file changed.  If the transaction counter is not updated,
26272     ** other connections to the same file might not realize that
26273     ** the file has changed and hence might not know to flush their
26274     ** cache.  The use of a stale cache can lead to database corruption.
26275     */
26276     assert( pFile->inNormalWrite==0
26277            || pFile->dbUpdate==0
26278            || pFile->transCntrChng==1 );
26279     pFile->inNormalWrite = 0;
26280 #endif
26281     
26282     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26283       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26284       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26285         /* only re-establish the shared lock if necessary */
26286         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26287         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26288       } else {
26289         skipShared = 1;
26290       }
26291     }
26292     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26293       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26294     } 
26295     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26296       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26297       if( !rc ){ 
26298         context->reserved = 0; 
26299       }
26300     }
26301     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26302       pInode->eFileLock = SHARED_LOCK;
26303     }
26304   }
26305   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26306 
26307     /* Decrement the shared lock counter.  Release the lock using an
26308     ** OS call only when all threads in this same process have released
26309     ** the lock.
26310     */
26311     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26312     pInode->nShared--;
26313     if( pInode->nShared==0 ){
26314       SimulateIOErrorBenign(1);
26315       SimulateIOError( h=(-1) )
26316       SimulateIOErrorBenign(0);
26317       if( !skipShared ){
26318         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26319       }
26320       if( !rc ){
26321         pInode->eFileLock = NO_LOCK;
26322         pFile->eFileLock = NO_LOCK;
26323       }
26324     }
26325     if( rc==SQLITE_OK ){
26326       pInode->nLock--;
26327       assert( pInode->nLock>=0 );
26328       if( pInode->nLock==0 ){
26329         closePendingFds(pFile);
26330       }
26331     }
26332   }
26333   
26334   unixLeaveMutex();
26335   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26336   return rc;
26337 }
26338 
26339 /*
26340 ** Close a file & cleanup AFP specific locking context 
26341 */
26342 static int afpClose(sqlite3_file *id) {
26343   int rc = SQLITE_OK;
26344   if( id ){
26345     unixFile *pFile = (unixFile*)id;
26346     afpUnlock(id, NO_LOCK);
26347     unixEnterMutex();
26348     if( pFile->pInode && pFile->pInode->nLock ){
26349       /* If there are outstanding locks, do not actually close the file just
26350       ** yet because that would clear those locks.  Instead, add the file
26351       ** descriptor to pInode->aPending.  It will be automatically closed when
26352       ** the last lock is cleared.
26353       */
26354       setPendingFd(pFile);
26355     }
26356     releaseInodeInfo(pFile);
26357     sqlite3_free(pFile->lockingContext);
26358     rc = closeUnixFile(id);
26359     unixLeaveMutex();
26360   }
26361   return rc;
26362 }
26363 
26364 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26365 /*
26366 ** The code above is the AFP lock implementation.  The code is specific
26367 ** to MacOSX and does not work on other unix platforms.  No alternative
26368 ** is available.  If you don't compile for a mac, then the "unix-afp"
26369 ** VFS is not available.
26370 **
26371 ********************* End of the AFP lock implementation **********************
26372 ******************************************************************************/
26373 
26374 /******************************************************************************
26375 *************************** Begin NFS Locking ********************************/
26376 
26377 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26378 /*
26379  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26380  ** must be either NO_LOCK or SHARED_LOCK.
26381  **
26382  ** If the locking level of the file descriptor is already at or below
26383  ** the requested locking level, this routine is a no-op.
26384  */
26385 static int nfsUnlock(sqlite3_file *id, int eFileLock){
26386   return posixUnlock(id, eFileLock, 1);
26387 }
26388 
26389 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26390 /*
26391 ** The code above is the NFS lock implementation.  The code is specific
26392 ** to MacOSX and does not work on other unix platforms.  No alternative
26393 ** is available.  
26394 **
26395 ********************* End of the NFS lock implementation **********************
26396 ******************************************************************************/
26397 
26398 /******************************************************************************
26399 **************** Non-locking sqlite3_file methods *****************************
26400 **
26401 ** The next division contains implementations for all methods of the 
26402 ** sqlite3_file object other than the locking methods.  The locking
26403 ** methods were defined in divisions above (one locking method per
26404 ** division).  Those methods that are common to all locking modes
26405 ** are gather together into this division.
26406 */
26407 
26408 /*
26409 ** Seek to the offset passed as the second argument, then read cnt 
26410 ** bytes into pBuf. Return the number of bytes actually read.
26411 **
26412 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
26413 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
26414 ** one system to another.  Since SQLite does not define USE_PREAD
26415 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
26416 ** See tickets #2741 and #2681.
26417 **
26418 ** To avoid stomping the errno value on a failed read the lastErrno value
26419 ** is set before returning.
26420 */
26421 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
26422   int got;
26423   int prior = 0;
26424 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26425   i64 newOffset;
26426 #endif
26427   TIMER_START;
26428   assert( cnt==(cnt&0x1ffff) );
26429   assert( id->h>2 );
26430   cnt &= 0x1ffff;
26431   do{
26432 #if defined(USE_PREAD)
26433     got = osPread(id->h, pBuf, cnt, offset);
26434     SimulateIOError( got = -1 );
26435 #elif defined(USE_PREAD64)
26436     got = osPread64(id->h, pBuf, cnt, offset);
26437     SimulateIOError( got = -1 );
26438 #else
26439     newOffset = lseek(id->h, offset, SEEK_SET);
26440     SimulateIOError( newOffset-- );
26441     if( newOffset!=offset ){
26442       if( newOffset == -1 ){
26443         ((unixFile*)id)->lastErrno = errno;
26444       }else{
26445         ((unixFile*)id)->lastErrno = 0;
26446       }
26447       return -1;
26448     }
26449     got = osRead(id->h, pBuf, cnt);
26450 #endif
26451     if( got==cnt ) break;
26452     if( got<0 ){
26453       if( errno==EINTR ){ got = 1; continue; }
26454       prior = 0;
26455       ((unixFile*)id)->lastErrno = errno;
26456       break;
26457     }else if( got>0 ){
26458       cnt -= got;
26459       offset += got;
26460       prior += got;
26461       pBuf = (void*)(got + (char*)pBuf);
26462     }
26463   }while( got>0 );
26464   TIMER_END;
26465   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
26466             id->h, got+prior, offset-prior, TIMER_ELAPSED));
26467   return got+prior;
26468 }
26469 
26470 /*
26471 ** Read data from a file into a buffer.  Return SQLITE_OK if all
26472 ** bytes were read successfully and SQLITE_IOERR if anything goes
26473 ** wrong.
26474 */
26475 static int unixRead(
26476   sqlite3_file *id, 
26477   void *pBuf, 
26478   int amt,
26479   sqlite3_int64 offset
26480 ){
26481   unixFile *pFile = (unixFile *)id;
26482   int got;
26483   assert( id );
26484   assert( offset>=0 );
26485   assert( amt>0 );
26486 
26487   /* If this is a database file (not a journal, master-journal or temp
26488   ** file), the bytes in the locking range should never be read or written. */
26489 #if 0
26490   assert( pFile->pUnused==0
26491        || offset>=PENDING_BYTE+512
26492        || offset+amt<=PENDING_BYTE 
26493   );
26494 #endif
26495 
26496 #if SQLITE_MAX_MMAP_SIZE>0
26497   /* Deal with as much of this read request as possible by transfering
26498   ** data from the memory mapping using memcpy().  */
26499   if( offset<pFile->mmapSize ){
26500     if( offset+amt <= pFile->mmapSize ){
26501       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
26502       return SQLITE_OK;
26503     }else{
26504       int nCopy = pFile->mmapSize - offset;
26505       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
26506       pBuf = &((u8 *)pBuf)[nCopy];
26507       amt -= nCopy;
26508       offset += nCopy;
26509     }
26510   }
26511 #endif
26512 
26513   got = seekAndRead(pFile, offset, pBuf, amt);
26514   if( got==amt ){
26515     return SQLITE_OK;
26516   }else if( got<0 ){
26517     /* lastErrno set by seekAndRead */
26518     return SQLITE_IOERR_READ;
26519   }else{
26520     pFile->lastErrno = 0; /* not a system error */
26521     /* Unread parts of the buffer must be zero-filled */
26522     memset(&((char*)pBuf)[got], 0, amt-got);
26523     return SQLITE_IOERR_SHORT_READ;
26524   }
26525 }
26526 
26527 /*
26528 ** Attempt to seek the file-descriptor passed as the first argument to
26529 ** absolute offset iOff, then attempt to write nBuf bytes of data from
26530 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
26531 ** return the actual number of bytes written (which may be less than
26532 ** nBuf).
26533 */
26534 static int seekAndWriteFd(
26535   int fd,                         /* File descriptor to write to */
26536   i64 iOff,                       /* File offset to begin writing at */
26537   const void *pBuf,               /* Copy data from this buffer to the file */
26538   int nBuf,                       /* Size of buffer pBuf in bytes */
26539   int *piErrno                    /* OUT: Error number if error occurs */
26540 ){
26541   int rc = 0;                     /* Value returned by system call */
26542 
26543   assert( nBuf==(nBuf&0x1ffff) );
26544   assert( fd>2 );
26545   nBuf &= 0x1ffff;
26546   TIMER_START;
26547 
26548 #if defined(USE_PREAD)
26549   do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
26550 #elif defined(USE_PREAD64)
26551   do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
26552 #else
26553   do{
26554     i64 iSeek = lseek(fd, iOff, SEEK_SET);
26555     SimulateIOError( iSeek-- );
26556 
26557     if( iSeek!=iOff ){
26558       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
26559       return -1;
26560     }
26561     rc = osWrite(fd, pBuf, nBuf);
26562   }while( rc<0 && errno==EINTR );
26563 #endif
26564 
26565   TIMER_END;
26566   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
26567 
26568   if( rc<0 && piErrno ) *piErrno = errno;
26569   return rc;
26570 }
26571 
26572 
26573 /*
26574 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26575 ** Return the number of bytes actually read.  Update the offset.
26576 **
26577 ** To avoid stomping the errno value on a failed write the lastErrno value
26578 ** is set before returning.
26579 */
26580 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26581   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
26582 }
26583 
26584 
26585 /*
26586 ** Write data from a buffer into a file.  Return SQLITE_OK on success
26587 ** or some other error code on failure.
26588 */
26589 static int unixWrite(
26590   sqlite3_file *id, 
26591   const void *pBuf, 
26592   int amt,
26593   sqlite3_int64 offset 
26594 ){
26595   unixFile *pFile = (unixFile*)id;
26596   int wrote = 0;
26597   assert( id );
26598   assert( amt>0 );
26599 
26600   /* If this is a database file (not a journal, master-journal or temp
26601   ** file), the bytes in the locking range should never be read or written. */
26602 #if 0
26603   assert( pFile->pUnused==0
26604        || offset>=PENDING_BYTE+512
26605        || offset+amt<=PENDING_BYTE 
26606   );
26607 #endif
26608 
26609 #ifdef SQLITE_DEBUG
26610   /* If we are doing a normal write to a database file (as opposed to
26611   ** doing a hot-journal rollback or a write to some file other than a
26612   ** normal database file) then record the fact that the database
26613   ** has changed.  If the transaction counter is modified, record that
26614   ** fact too.
26615   */
26616   if( pFile->inNormalWrite ){
26617     pFile->dbUpdate = 1;  /* The database has been modified */
26618     if( offset<=24 && offset+amt>=27 ){
26619       int rc;
26620       char oldCntr[4];
26621       SimulateIOErrorBenign(1);
26622       rc = seekAndRead(pFile, 24, oldCntr, 4);
26623       SimulateIOErrorBenign(0);
26624       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26625         pFile->transCntrChng = 1;  /* The transaction counter has changed */
26626       }
26627     }
26628   }
26629 #endif
26630 
26631 #if SQLITE_MAX_MMAP_SIZE>0
26632   /* Deal with as much of this write request as possible by transfering
26633   ** data from the memory mapping using memcpy().  */
26634   if( offset<pFile->mmapSize ){
26635     if( offset+amt <= pFile->mmapSize ){
26636       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
26637       return SQLITE_OK;
26638     }else{
26639       int nCopy = pFile->mmapSize - offset;
26640       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
26641       pBuf = &((u8 *)pBuf)[nCopy];
26642       amt -= nCopy;
26643       offset += nCopy;
26644     }
26645   }
26646 #endif
26647 
26648   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26649     amt -= wrote;
26650     offset += wrote;
26651     pBuf = &((char*)pBuf)[wrote];
26652   }
26653   SimulateIOError(( wrote=(-1), amt=1 ));
26654   SimulateDiskfullError(( wrote=0, amt=1 ));
26655 
26656   if( amt>0 ){
26657     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26658       /* lastErrno set by seekAndWrite */
26659       return SQLITE_IOERR_WRITE;
26660     }else{
26661       pFile->lastErrno = 0; /* not a system error */
26662       return SQLITE_FULL;
26663     }
26664   }
26665 
26666   return SQLITE_OK;
26667 }
26668 
26669 #ifdef SQLITE_TEST
26670 /*
26671 ** Count the number of fullsyncs and normal syncs.  This is used to test
26672 ** that syncs and fullsyncs are occurring at the right times.
26673 */
26674 SQLITE_API int sqlite3_sync_count = 0;
26675 SQLITE_API int sqlite3_fullsync_count = 0;
26676 #endif
26677 
26678 /*
26679 ** We do not trust systems to provide a working fdatasync().  Some do.
26680 ** Others do no.  To be safe, we will stick with the (slightly slower)
26681 ** fsync(). If you know that your system does support fdatasync() correctly,
26682 ** then simply compile with -Dfdatasync=fdatasync
26683 */
26684 #if !defined(fdatasync)
26685 # define fdatasync fsync
26686 #endif
26687 
26688 /*
26689 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26690 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26691 ** only available on Mac OS X.  But that could change.
26692 */
26693 #ifdef F_FULLFSYNC
26694 # define HAVE_FULLFSYNC 1
26695 #else
26696 # define HAVE_FULLFSYNC 0
26697 #endif
26698 
26699 
26700 /*
26701 ** The fsync() system call does not work as advertised on many
26702 ** unix systems.  The following procedure is an attempt to make
26703 ** it work better.
26704 **
26705 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26706 ** for testing when we want to run through the test suite quickly.
26707 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26708 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26709 ** or power failure will likely corrupt the database file.
26710 **
26711 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26712 ** The idea behind dataOnly is that it should only write the file content
26713 ** to disk, not the inode.  We only set dataOnly if the file size is 
26714 ** unchanged since the file size is part of the inode.  However, 
26715 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26716 ** file size has changed.  The only real difference between fdatasync()
26717 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26718 ** inode if the mtime or owner or other inode attributes have changed.
26719 ** We only care about the file size, not the other file attributes, so
26720 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26721 ** So, we always use fdatasync() if it is available, regardless of
26722 ** the value of the dataOnly flag.
26723 */
26724 static int full_fsync(int fd, int fullSync, int dataOnly){
26725   int rc;
26726 
26727   /* The following "ifdef/elif/else/" block has the same structure as
26728   ** the one below. It is replicated here solely to avoid cluttering 
26729   ** up the real code with the UNUSED_PARAMETER() macros.
26730   */
26731 #ifdef SQLITE_NO_SYNC
26732   UNUSED_PARAMETER(fd);
26733   UNUSED_PARAMETER(fullSync);
26734   UNUSED_PARAMETER(dataOnly);
26735 #elif HAVE_FULLFSYNC
26736   UNUSED_PARAMETER(dataOnly);
26737 #else
26738   UNUSED_PARAMETER(fullSync);
26739   UNUSED_PARAMETER(dataOnly);
26740 #endif
26741 
26742   /* Record the number of times that we do a normal fsync() and 
26743   ** FULLSYNC.  This is used during testing to verify that this procedure
26744   ** gets called with the correct arguments.
26745   */
26746 #ifdef SQLITE_TEST
26747   if( fullSync ) sqlite3_fullsync_count++;
26748   sqlite3_sync_count++;
26749 #endif
26750 
26751   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26752   ** no-op
26753   */
26754 #ifdef SQLITE_NO_SYNC
26755   rc = SQLITE_OK;
26756 #elif HAVE_FULLFSYNC
26757   if( fullSync ){
26758     rc = osFcntl(fd, F_FULLFSYNC, 0);
26759   }else{
26760     rc = 1;
26761   }
26762   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26763   ** It shouldn't be possible for fullfsync to fail on the local 
26764   ** file system (on OSX), so failure indicates that FULLFSYNC
26765   ** isn't supported for this file system. So, attempt an fsync 
26766   ** and (for now) ignore the overhead of a superfluous fcntl call.  
26767   ** It'd be better to detect fullfsync support once and avoid 
26768   ** the fcntl call every time sync is called.
26769   */
26770   if( rc ) rc = fsync(fd);
26771 
26772 #elif defined(__APPLE__)
26773   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26774   ** so currently we default to the macro that redefines fdatasync to fsync
26775   */
26776   rc = fsync(fd);
26777 #else 
26778   rc = fdatasync(fd);
26779 #if OS_VXWORKS
26780   if( rc==-1 && errno==ENOTSUP ){
26781     rc = fsync(fd);
26782   }
26783 #endif /* OS_VXWORKS */
26784 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26785 
26786   if( OS_VXWORKS && rc!= -1 ){
26787     rc = 0;
26788   }
26789   return rc;
26790 }
26791 
26792 /*
26793 ** Open a file descriptor to the directory containing file zFilename.
26794 ** If successful, *pFd is set to the opened file descriptor and
26795 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26796 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26797 ** value.
26798 **
26799 ** The directory file descriptor is used for only one thing - to
26800 ** fsync() a directory to make sure file creation and deletion events
26801 ** are flushed to disk.  Such fsyncs are not needed on newer
26802 ** journaling filesystems, but are required on older filesystems.
26803 **
26804 ** This routine can be overridden using the xSetSysCall interface.
26805 ** The ability to override this routine was added in support of the
26806 ** chromium sandbox.  Opening a directory is a security risk (we are
26807 ** told) so making it overrideable allows the chromium sandbox to
26808 ** replace this routine with a harmless no-op.  To make this routine
26809 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26810 ** *pFd set to a negative number.
26811 **
26812 ** If SQLITE_OK is returned, the caller is responsible for closing
26813 ** the file descriptor *pFd using close().
26814 */
26815 static int openDirectory(const char *zFilename, int *pFd){
26816   int ii;
26817   int fd = -1;
26818   char zDirname[MAX_PATHNAME+1];
26819 
26820   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26821   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26822   if( ii>0 ){
26823     zDirname[ii] = '\0';
26824     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26825     if( fd>=0 ){
26826       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26827     }
26828   }
26829   *pFd = fd;
26830   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26831 }
26832 
26833 /*
26834 ** Make sure all writes to a particular file are committed to disk.
26835 **
26836 ** If dataOnly==0 then both the file itself and its metadata (file
26837 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26838 ** file data is synced.
26839 **
26840 ** Under Unix, also make sure that the directory entry for the file
26841 ** has been created by fsync-ing the directory that contains the file.
26842 ** If we do not do this and we encounter a power failure, the directory
26843 ** entry for the journal might not exist after we reboot.  The next
26844 ** SQLite to access the file will not know that the journal exists (because
26845 ** the directory entry for the journal was never created) and the transaction
26846 ** will not roll back - possibly leading to database corruption.
26847 */
26848 static int unixSync(sqlite3_file *id, int flags){
26849   int rc;
26850   unixFile *pFile = (unixFile*)id;
26851 
26852   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26853   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26854 
26855   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26856   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26857       || (flags&0x0F)==SQLITE_SYNC_FULL
26858   );
26859 
26860   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26861   ** line is to test that doing so does not cause any problems.
26862   */
26863   SimulateDiskfullError( return SQLITE_FULL );
26864 
26865   assert( pFile );
26866   OSTRACE(("SYNC    %-3d\n", pFile->h));
26867   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26868   SimulateIOError( rc=1 );
26869   if( rc ){
26870     pFile->lastErrno = errno;
26871     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26872   }
26873 
26874   /* Also fsync the directory containing the file if the DIRSYNC flag
26875   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
26876   ** are unable to fsync a directory, so ignore errors on the fsync.
26877   */
26878   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26879     int dirfd;
26880     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26881             HAVE_FULLFSYNC, isFullsync));
26882     rc = osOpenDirectory(pFile->zPath, &dirfd);
26883     if( rc==SQLITE_OK && dirfd>=0 ){
26884       full_fsync(dirfd, 0, 0);
26885       robust_close(pFile, dirfd, __LINE__);
26886     }else if( rc==SQLITE_CANTOPEN ){
26887       rc = SQLITE_OK;
26888     }
26889     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26890   }
26891   return rc;
26892 }
26893 
26894 /*
26895 ** Truncate an open file to a specified size
26896 */
26897 static int unixTruncate(sqlite3_file *id, i64 nByte){
26898   unixFile *pFile = (unixFile *)id;
26899   int rc;
26900   assert( pFile );
26901   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26902 
26903   /* If the user has configured a chunk-size for this file, truncate the
26904   ** file so that it consists of an integer number of chunks (i.e. the
26905   ** actual file size after the operation may be larger than the requested
26906   ** size).
26907   */
26908   if( pFile->szChunk>0 ){
26909     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26910   }
26911 
26912   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26913   if( rc ){
26914     pFile->lastErrno = errno;
26915     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26916   }else{
26917 #ifdef SQLITE_DEBUG
26918     /* If we are doing a normal write to a database file (as opposed to
26919     ** doing a hot-journal rollback or a write to some file other than a
26920     ** normal database file) and we truncate the file to zero length,
26921     ** that effectively updates the change counter.  This might happen
26922     ** when restoring a database using the backup API from a zero-length
26923     ** source.
26924     */
26925     if( pFile->inNormalWrite && nByte==0 ){
26926       pFile->transCntrChng = 1;
26927     }
26928 #endif
26929 
26930 #if SQLITE_MAX_MMAP_SIZE>0
26931     /* If the file was just truncated to a size smaller than the currently
26932     ** mapped region, reduce the effective mapping size as well. SQLite will
26933     ** use read() and write() to access data beyond this point from now on.  
26934     */
26935     if( nByte<pFile->mmapSize ){
26936       pFile->mmapSize = nByte;
26937     }
26938 #endif
26939 
26940     return SQLITE_OK;
26941   }
26942 }
26943 
26944 /*
26945 ** Determine the current size of a file in bytes
26946 */
26947 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26948   int rc;
26949   struct stat buf;
26950   assert( id );
26951   rc = osFstat(((unixFile*)id)->h, &buf);
26952   SimulateIOError( rc=1 );
26953   if( rc!=0 ){
26954     ((unixFile*)id)->lastErrno = errno;
26955     return SQLITE_IOERR_FSTAT;
26956   }
26957   *pSize = buf.st_size;
26958 
26959   /* When opening a zero-size database, the findInodeInfo() procedure
26960   ** writes a single byte into that file in order to work around a bug
26961   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26962   ** layers, we need to report this file size as zero even though it is
26963   ** really 1.   Ticket #3260.
26964   */
26965   if( *pSize==1 ) *pSize = 0;
26966 
26967 
26968   return SQLITE_OK;
26969 }
26970 
26971 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26972 /*
26973 ** Handler for proxy-locking file-control verbs.  Defined below in the
26974 ** proxying locking division.
26975 */
26976 static int proxyFileControl(sqlite3_file*,int,void*);
26977 #endif
26978 
26979 /* 
26980 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26981 ** file-control operation.  Enlarge the database to nBytes in size
26982 ** (rounded up to the next chunk-size).  If the database is already
26983 ** nBytes or larger, this routine is a no-op.
26984 */
26985 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26986   if( pFile->szChunk>0 ){
26987     i64 nSize;                    /* Required file size */
26988     struct stat buf;              /* Used to hold return values of fstat() */
26989    
26990     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26991 
26992     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26993     if( nSize>(i64)buf.st_size ){
26994 
26995 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26996       /* The code below is handling the return value of osFallocate() 
26997       ** correctly. posix_fallocate() is defined to "returns zero on success, 
26998       ** or an error number on  failure". See the manpage for details. */
26999       int err;
27000       do{
27001         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27002       }while( err==EINTR );
27003       if( err ) return SQLITE_IOERR_WRITE;
27004 #else
27005       /* If the OS does not have posix_fallocate(), fake it. First use
27006       ** ftruncate() to set the file size, then write a single byte to
27007       ** the last byte in each block within the extended region. This
27008       ** is the same technique used by glibc to implement posix_fallocate()
27009       ** on systems that do not have a real fallocate() system call.
27010       */
27011       int nBlk = buf.st_blksize;  /* File-system block size */
27012       i64 iWrite;                 /* Next offset to write to */
27013 
27014       if( robust_ftruncate(pFile->h, nSize) ){
27015         pFile->lastErrno = errno;
27016         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27017       }
27018       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27019       while( iWrite<nSize ){
27020         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27021         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27022         iWrite += nBlk;
27023       }
27024 #endif
27025     }
27026   }
27027 
27028 #if SQLITE_MAX_MMAP_SIZE>0
27029   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
27030     int rc;
27031     if( pFile->szChunk<=0 ){
27032       if( robust_ftruncate(pFile->h, nByte) ){
27033         pFile->lastErrno = errno;
27034         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27035       }
27036     }
27037 
27038     rc = unixMapfile(pFile, nByte);
27039     return rc;
27040   }
27041 #endif
27042 
27043   return SQLITE_OK;
27044 }
27045 
27046 /*
27047 ** If *pArg is inititially negative then this is a query.  Set *pArg to
27048 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
27049 **
27050 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
27051 */
27052 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
27053   if( *pArg<0 ){
27054     *pArg = (pFile->ctrlFlags & mask)!=0;
27055   }else if( (*pArg)==0 ){
27056     pFile->ctrlFlags &= ~mask;
27057   }else{
27058     pFile->ctrlFlags |= mask;
27059   }
27060 }
27061 
27062 /* Forward declaration */
27063 static int unixGetTempname(int nBuf, char *zBuf);
27064 
27065 /*
27066 ** Information and control of an open file handle.
27067 */
27068 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27069   unixFile *pFile = (unixFile*)id;
27070   switch( op ){
27071     case SQLITE_FCNTL_LOCKSTATE: {
27072       *(int*)pArg = pFile->eFileLock;
27073       return SQLITE_OK;
27074     }
27075     case SQLITE_LAST_ERRNO: {
27076       *(int*)pArg = pFile->lastErrno;
27077       return SQLITE_OK;
27078     }
27079     case SQLITE_FCNTL_CHUNK_SIZE: {
27080       pFile->szChunk = *(int *)pArg;
27081       return SQLITE_OK;
27082     }
27083     case SQLITE_FCNTL_SIZE_HINT: {
27084       int rc;
27085       SimulateIOErrorBenign(1);
27086       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
27087       SimulateIOErrorBenign(0);
27088       return rc;
27089     }
27090     case SQLITE_FCNTL_PERSIST_WAL: {
27091       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
27092       return SQLITE_OK;
27093     }
27094     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
27095       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
27096       return SQLITE_OK;
27097     }
27098     case SQLITE_FCNTL_VFSNAME: {
27099       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
27100       return SQLITE_OK;
27101     }
27102     case SQLITE_FCNTL_TEMPFILENAME: {
27103       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
27104       if( zTFile ){
27105         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
27106         *(char**)pArg = zTFile;
27107       }
27108       return SQLITE_OK;
27109     }
27110 #if SQLITE_MAX_MMAP_SIZE>0
27111     case SQLITE_FCNTL_MMAP_SIZE: {
27112       i64 newLimit = *(i64*)pArg;
27113       int rc = SQLITE_OK;
27114       if( newLimit>sqlite3GlobalConfig.mxMmap ){
27115         newLimit = sqlite3GlobalConfig.mxMmap;
27116       }
27117       *(i64*)pArg = pFile->mmapSizeMax;
27118       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
27119         pFile->mmapSizeMax = newLimit;
27120         if( pFile->mmapSize>0 ){
27121           unixUnmapfile(pFile);
27122           rc = unixMapfile(pFile, -1);
27123         }
27124       }
27125       return rc;
27126     }
27127 #endif
27128 #ifdef SQLITE_DEBUG
27129     /* The pager calls this method to signal that it has done
27130     ** a rollback and that the database is therefore unchanged and
27131     ** it hence it is OK for the transaction change counter to be
27132     ** unchanged.
27133     */
27134     case SQLITE_FCNTL_DB_UNCHANGED: {
27135       ((unixFile*)id)->dbUpdate = 0;
27136       return SQLITE_OK;
27137     }
27138 #endif
27139 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27140     case SQLITE_SET_LOCKPROXYFILE:
27141     case SQLITE_GET_LOCKPROXYFILE: {
27142       return proxyFileControl(id,op,pArg);
27143     }
27144 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27145   }
27146   return SQLITE_NOTFOUND;
27147 }
27148 
27149 /*
27150 ** Return the sector size in bytes of the underlying block device for
27151 ** the specified file. This is almost always 512 bytes, but may be
27152 ** larger for some devices.
27153 **
27154 ** SQLite code assumes this function cannot fail. It also assumes that
27155 ** if two files are created in the same file-system directory (i.e.
27156 ** a database and its journal file) that the sector size will be the
27157 ** same for both.
27158 */
27159 #ifndef __QNXNTO__ 
27160 static int unixSectorSize(sqlite3_file *NotUsed){
27161   UNUSED_PARAMETER(NotUsed);
27162   return SQLITE_DEFAULT_SECTOR_SIZE;
27163 }
27164 #endif
27165 
27166 /*
27167 ** The following version of unixSectorSize() is optimized for QNX.
27168 */
27169 #ifdef __QNXNTO__
27170 #include <sys/dcmd_blk.h>
27171 #include <sys/statvfs.h>
27172 static int unixSectorSize(sqlite3_file *id){
27173   unixFile *pFile = (unixFile*)id;
27174   if( pFile->sectorSize == 0 ){
27175     struct statvfs fsInfo;
27176        
27177     /* Set defaults for non-supported filesystems */
27178     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27179     pFile->deviceCharacteristics = 0;
27180     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
27181       return pFile->sectorSize;
27182     }
27183 
27184     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
27185       pFile->sectorSize = fsInfo.f_bsize;
27186       pFile->deviceCharacteristics =
27187         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
27188         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27189                                       ** the write succeeds */
27190         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27191                                       ** so it is ordered */
27192         0;
27193     }else if( strstr(fsInfo.f_basetype, "etfs") ){
27194       pFile->sectorSize = fsInfo.f_bsize;
27195       pFile->deviceCharacteristics =
27196         /* etfs cluster size writes are atomic */
27197         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
27198         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27199                                       ** the write succeeds */
27200         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27201                                       ** so it is ordered */
27202         0;
27203     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
27204       pFile->sectorSize = fsInfo.f_bsize;
27205       pFile->deviceCharacteristics =
27206         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
27207         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27208                                       ** the write succeeds */
27209         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27210                                       ** so it is ordered */
27211         0;
27212     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
27213       pFile->sectorSize = fsInfo.f_bsize;
27214       pFile->deviceCharacteristics =
27215         /* full bitset of atomics from max sector size and smaller */
27216         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27217         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27218                                       ** so it is ordered */
27219         0;
27220     }else if( strstr(fsInfo.f_basetype, "dos") ){
27221       pFile->sectorSize = fsInfo.f_bsize;
27222       pFile->deviceCharacteristics =
27223         /* full bitset of atomics from max sector size and smaller */
27224         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27225         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27226                                       ** so it is ordered */
27227         0;
27228     }else{
27229       pFile->deviceCharacteristics =
27230         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
27231         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27232                                       ** the write succeeds */
27233         0;
27234     }
27235   }
27236   /* Last chance verification.  If the sector size isn't a multiple of 512
27237   ** then it isn't valid.*/
27238   if( pFile->sectorSize % 512 != 0 ){
27239     pFile->deviceCharacteristics = 0;
27240     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27241   }
27242   return pFile->sectorSize;
27243 }
27244 #endif /* __QNXNTO__ */
27245 
27246 /*
27247 ** Return the device characteristics for the file.
27248 **
27249 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
27250 ** However, that choice is contraversial since technically the underlying
27251 ** file system does not always provide powersafe overwrites.  (In other
27252 ** words, after a power-loss event, parts of the file that were never
27253 ** written might end up being altered.)  However, non-PSOW behavior is very,
27254 ** very rare.  And asserting PSOW makes a large reduction in the amount
27255 ** of required I/O for journaling, since a lot of padding is eliminated.
27256 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
27257 ** available to turn it off and URI query parameter available to turn it off.
27258 */
27259 static int unixDeviceCharacteristics(sqlite3_file *id){
27260   unixFile *p = (unixFile*)id;
27261   int rc = 0;
27262 #ifdef __QNXNTO__
27263   if( p->sectorSize==0 ) unixSectorSize(id);
27264   rc = p->deviceCharacteristics;
27265 #endif
27266   if( p->ctrlFlags & UNIXFILE_PSOW ){
27267     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
27268   }
27269   return rc;
27270 }
27271 
27272 #ifndef SQLITE_OMIT_WAL
27273 
27274 
27275 /*
27276 ** Object used to represent an shared memory buffer.  
27277 **
27278 ** When multiple threads all reference the same wal-index, each thread
27279 ** has its own unixShm object, but they all point to a single instance
27280 ** of this unixShmNode object.  In other words, each wal-index is opened
27281 ** only once per process.
27282 **
27283 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27284 ** We could coalesce this object into unixInodeInfo, but that would mean
27285 ** every open file that does not use shared memory (in other words, most
27286 ** open files) would have to carry around this extra information.  So
27287 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27288 ** and the unixShmNode object is created only when needed.
27289 **
27290 ** unixMutexHeld() must be true when creating or destroying
27291 ** this object or while reading or writing the following fields:
27292 **
27293 **      nRef
27294 **
27295 ** The following fields are read-only after the object is created:
27296 ** 
27297 **      fid
27298 **      zFilename
27299 **
27300 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27301 ** unixMutexHeld() is true when reading or writing any other field
27302 ** in this structure.
27303 */
27304 struct unixShmNode {
27305   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27306   sqlite3_mutex *mutex;      /* Mutex to access this object */
27307   char *zFilename;           /* Name of the mmapped file */
27308   int h;                     /* Open file descriptor */
27309   int szRegion;              /* Size of shared-memory regions */
27310   u16 nRegion;               /* Size of array apRegion */
27311   u8 isReadonly;             /* True if read-only */
27312   char **apRegion;           /* Array of mapped shared-memory regions */
27313   int nRef;                  /* Number of unixShm objects pointing to this */
27314   unixShm *pFirst;           /* All unixShm objects pointing to this */
27315 #ifdef SQLITE_DEBUG
27316   u8 exclMask;               /* Mask of exclusive locks held */
27317   u8 sharedMask;             /* Mask of shared locks held */
27318   u8 nextShmId;              /* Next available unixShm.id value */
27319 #endif
27320 };
27321 
27322 /*
27323 ** Structure used internally by this VFS to record the state of an
27324 ** open shared memory connection.
27325 **
27326 ** The following fields are initialized when this object is created and
27327 ** are read-only thereafter:
27328 **
27329 **    unixShm.pFile
27330 **    unixShm.id
27331 **
27332 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
27333 ** while accessing any read/write fields.
27334 */
27335 struct unixShm {
27336   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27337   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27338   u8 hasMutex;               /* True if holding the unixShmNode mutex */
27339   u8 id;                     /* Id of this connection within its unixShmNode */
27340   u16 sharedMask;            /* Mask of shared locks held */
27341   u16 exclMask;              /* Mask of exclusive locks held */
27342 };
27343 
27344 /*
27345 ** Constants used for locking
27346 */
27347 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27348 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27349 
27350 /*
27351 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27352 **
27353 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27354 ** otherwise.
27355 */
27356 static int unixShmSystemLock(
27357   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27358   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27359   int ofst,              /* First byte of the locking range */
27360   int n                  /* Number of bytes to lock */
27361 ){
27362   struct flock f;       /* The posix advisory locking structure */
27363   int rc = SQLITE_OK;   /* Result code form fcntl() */
27364 
27365   /* Access to the unixShmNode object is serialized by the caller */
27366   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27367 
27368   /* Shared locks never span more than one byte */
27369   assert( n==1 || lockType!=F_RDLCK );
27370 
27371   /* Locks are within range */
27372   assert( n>=1 && n<SQLITE_SHM_NLOCK );
27373 
27374   if( pShmNode->h>=0 ){
27375     /* Initialize the locking parameters */
27376     memset(&f, 0, sizeof(f));
27377     f.l_type = lockType;
27378     f.l_whence = SEEK_SET;
27379     f.l_start = ofst;
27380     f.l_len = n;
27381 
27382     rc = osFcntl(pShmNode->h, F_SETLK, &f);
27383     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27384   }
27385 
27386   /* Update the global lock state and do debug tracing */
27387 #ifdef SQLITE_DEBUG
27388   { u16 mask;
27389   OSTRACE(("SHM-LOCK "));
27390   mask = ofst>31 ? 0xffffffff : (1<<(ofst+n)) - (1<<ofst);
27391   if( rc==SQLITE_OK ){
27392     if( lockType==F_UNLCK ){
27393       OSTRACE(("unlock %d ok", ofst));
27394       pShmNode->exclMask &= ~mask;
27395       pShmNode->sharedMask &= ~mask;
27396     }else if( lockType==F_RDLCK ){
27397       OSTRACE(("read-lock %d ok", ofst));
27398       pShmNode->exclMask &= ~mask;
27399       pShmNode->sharedMask |= mask;
27400     }else{
27401       assert( lockType==F_WRLCK );
27402       OSTRACE(("write-lock %d ok", ofst));
27403       pShmNode->exclMask |= mask;
27404       pShmNode->sharedMask &= ~mask;
27405     }
27406   }else{
27407     if( lockType==F_UNLCK ){
27408       OSTRACE(("unlock %d failed", ofst));
27409     }else if( lockType==F_RDLCK ){
27410       OSTRACE(("read-lock failed"));
27411     }else{
27412       assert( lockType==F_WRLCK );
27413       OSTRACE(("write-lock %d failed", ofst));
27414     }
27415   }
27416   OSTRACE((" - afterwards %03x,%03x\n",
27417            pShmNode->sharedMask, pShmNode->exclMask));
27418   }
27419 #endif
27420 
27421   return rc;        
27422 }
27423 
27424 
27425 /*
27426 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27427 **
27428 ** This is not a VFS shared-memory method; it is a utility function called
27429 ** by VFS shared-memory methods.
27430 */
27431 static void unixShmPurge(unixFile *pFd){
27432   unixShmNode *p = pFd->pInode->pShmNode;
27433   assert( unixMutexHeld() );
27434   if( p && p->nRef==0 ){
27435     int i;
27436     assert( p->pInode==pFd->pInode );
27437     sqlite3_mutex_free(p->mutex);
27438     for(i=0; i<p->nRegion; i++){
27439       if( p->h>=0 ){
27440         osMunmap(p->apRegion[i], p->szRegion);
27441       }else{
27442         sqlite3_free(p->apRegion[i]);
27443       }
27444     }
27445     sqlite3_free(p->apRegion);
27446     if( p->h>=0 ){
27447       robust_close(pFd, p->h, __LINE__);
27448       p->h = -1;
27449     }
27450     p->pInode->pShmNode = 0;
27451     sqlite3_free(p);
27452   }
27453 }
27454 
27455 /*
27456 ** Open a shared-memory area associated with open database file pDbFd.  
27457 ** This particular implementation uses mmapped files.
27458 **
27459 ** The file used to implement shared-memory is in the same directory
27460 ** as the open database file and has the same name as the open database
27461 ** file with the "-shm" suffix added.  For example, if the database file
27462 ** is "/home/user1/config.db" then the file that is created and mmapped
27463 ** for shared memory will be called "/home/user1/config.db-shm".  
27464 **
27465 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27466 ** some other tmpfs mount. But if a file in a different directory
27467 ** from the database file is used, then differing access permissions
27468 ** or a chroot() might cause two different processes on the same
27469 ** database to end up using different files for shared memory - 
27470 ** meaning that their memory would not really be shared - resulting
27471 ** in database corruption.  Nevertheless, this tmpfs file usage
27472 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27473 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27474 ** option results in an incompatible build of SQLite;  builds of SQLite
27475 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27476 ** same database file at the same time, database corruption will likely
27477 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27478 ** "unsupported" and may go away in a future SQLite release.
27479 **
27480 ** When opening a new shared-memory file, if no other instances of that
27481 ** file are currently open, in this process or in other processes, then
27482 ** the file must be truncated to zero length or have its header cleared.
27483 **
27484 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27485 ** that means that an exclusive lock is held on the database file and
27486 ** that no other processes are able to read or write the database.  In
27487 ** that case, we do not really need shared memory.  No shared memory
27488 ** file is created.  The shared memory will be simulated with heap memory.
27489 */
27490 static int unixOpenSharedMemory(unixFile *pDbFd){
27491   struct unixShm *p = 0;          /* The connection to be opened */
27492   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27493   int rc;                         /* Result code */
27494   unixInodeInfo *pInode;          /* The inode of fd */
27495   char *zShmFilename;             /* Name of the file used for SHM */
27496   int nShmFilename;               /* Size of the SHM filename in bytes */
27497 
27498   /* Allocate space for the new unixShm object. */
27499   p = sqlite3_malloc( sizeof(*p) );
27500   if( p==0 ) return SQLITE_NOMEM;
27501   memset(p, 0, sizeof(*p));
27502   assert( pDbFd->pShm==0 );
27503 
27504   /* Check to see if a unixShmNode object already exists. Reuse an existing
27505   ** one if present. Create a new one if necessary.
27506   */
27507   unixEnterMutex();
27508   pInode = pDbFd->pInode;
27509   pShmNode = pInode->pShmNode;
27510   if( pShmNode==0 ){
27511     struct stat sStat;                 /* fstat() info for database file */
27512 
27513     /* Call fstat() to figure out the permissions on the database file. If
27514     ** a new *-shm file is created, an attempt will be made to create it
27515     ** with the same permissions.
27516     */
27517     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27518       rc = SQLITE_IOERR_FSTAT;
27519       goto shm_open_err;
27520     }
27521 
27522 #ifdef SQLITE_SHM_DIRECTORY
27523     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
27524 #else
27525     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
27526 #endif
27527     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27528     if( pShmNode==0 ){
27529       rc = SQLITE_NOMEM;
27530       goto shm_open_err;
27531     }
27532     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
27533     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27534 #ifdef SQLITE_SHM_DIRECTORY
27535     sqlite3_snprintf(nShmFilename, zShmFilename, 
27536                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27537                      (u32)sStat.st_ino, (u32)sStat.st_dev);
27538 #else
27539     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27540     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
27541 #endif
27542     pShmNode->h = -1;
27543     pDbFd->pInode->pShmNode = pShmNode;
27544     pShmNode->pInode = pDbFd->pInode;
27545     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27546     if( pShmNode->mutex==0 ){
27547       rc = SQLITE_NOMEM;
27548       goto shm_open_err;
27549     }
27550 
27551     if( pInode->bProcessLock==0 ){
27552       int openFlags = O_RDWR | O_CREAT;
27553       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
27554         openFlags = O_RDONLY;
27555         pShmNode->isReadonly = 1;
27556       }
27557       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
27558       if( pShmNode->h<0 ){
27559         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27560         goto shm_open_err;
27561       }
27562 
27563       /* If this process is running as root, make sure that the SHM file
27564       ** is owned by the same user that owns the original database.  Otherwise,
27565       ** the original owner will not be able to connect.
27566       */
27567       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27568   
27569       /* Check to see if another process is holding the dead-man switch.
27570       ** If not, truncate the file to zero length. 
27571       */
27572       rc = SQLITE_OK;
27573       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27574         if( robust_ftruncate(pShmNode->h, 0) ){
27575           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27576         }
27577       }
27578       if( rc==SQLITE_OK ){
27579         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27580       }
27581       if( rc ) goto shm_open_err;
27582     }
27583   }
27584 
27585   /* Make the new connection a child of the unixShmNode */
27586   p->pShmNode = pShmNode;
27587 #ifdef SQLITE_DEBUG
27588   p->id = pShmNode->nextShmId++;
27589 #endif
27590   pShmNode->nRef++;
27591   pDbFd->pShm = p;
27592   unixLeaveMutex();
27593 
27594   /* The reference count on pShmNode has already been incremented under
27595   ** the cover of the unixEnterMutex() mutex and the pointer from the
27596   ** new (struct unixShm) object to the pShmNode has been set. All that is
27597   ** left to do is to link the new object into the linked list starting
27598   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
27599   ** mutex.
27600   */
27601   sqlite3_mutex_enter(pShmNode->mutex);
27602   p->pNext = pShmNode->pFirst;
27603   pShmNode->pFirst = p;
27604   sqlite3_mutex_leave(pShmNode->mutex);
27605   return SQLITE_OK;
27606 
27607   /* Jump here on any error */
27608 shm_open_err:
27609   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27610   sqlite3_free(p);
27611   unixLeaveMutex();
27612   return rc;
27613 }
27614 
27615 /*
27616 ** This function is called to obtain a pointer to region iRegion of the 
27617 ** shared-memory associated with the database file fd. Shared-memory regions 
27618 ** are numbered starting from zero. Each shared-memory region is szRegion 
27619 ** bytes in size.
27620 **
27621 ** If an error occurs, an error code is returned and *pp is set to NULL.
27622 **
27623 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27624 ** region has not been allocated (by any client, including one running in a
27625 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27626 ** bExtend is non-zero and the requested shared-memory region has not yet 
27627 ** been allocated, it is allocated by this function.
27628 **
27629 ** If the shared-memory region has already been allocated or is allocated by
27630 ** this call as described above, then it is mapped into this processes 
27631 ** address space (if it is not already), *pp is set to point to the mapped 
27632 ** memory and SQLITE_OK returned.
27633 */
27634 static int unixShmMap(
27635   sqlite3_file *fd,               /* Handle open on database file */
27636   int iRegion,                    /* Region to retrieve */
27637   int szRegion,                   /* Size of regions */
27638   int bExtend,                    /* True to extend file if necessary */
27639   void volatile **pp              /* OUT: Mapped memory */
27640 ){
27641   unixFile *pDbFd = (unixFile*)fd;
27642   unixShm *p;
27643   unixShmNode *pShmNode;
27644   int rc = SQLITE_OK;
27645 
27646   /* If the shared-memory file has not yet been opened, open it now. */
27647   if( pDbFd->pShm==0 ){
27648     rc = unixOpenSharedMemory(pDbFd);
27649     if( rc!=SQLITE_OK ) return rc;
27650   }
27651 
27652   p = pDbFd->pShm;
27653   pShmNode = p->pShmNode;
27654   sqlite3_mutex_enter(pShmNode->mutex);
27655   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27656   assert( pShmNode->pInode==pDbFd->pInode );
27657   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27658   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27659 
27660   if( pShmNode->nRegion<=iRegion ){
27661     char **apNew;                      /* New apRegion[] array */
27662     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27663     struct stat sStat;                 /* Used by fstat() */
27664 
27665     pShmNode->szRegion = szRegion;
27666 
27667     if( pShmNode->h>=0 ){
27668       /* The requested region is not mapped into this processes address space.
27669       ** Check to see if it has been allocated (i.e. if the wal-index file is
27670       ** large enough to contain the requested region).
27671       */
27672       if( osFstat(pShmNode->h, &sStat) ){
27673         rc = SQLITE_IOERR_SHMSIZE;
27674         goto shmpage_out;
27675       }
27676   
27677       if( sStat.st_size<nByte ){
27678         /* The requested memory region does not exist. If bExtend is set to
27679         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27680         */
27681         if( !bExtend ){
27682           goto shmpage_out;
27683         }
27684 
27685         /* Alternatively, if bExtend is true, extend the file. Do this by
27686         ** writing a single byte to the end of each (OS) page being
27687         ** allocated or extended. Technically, we need only write to the
27688         ** last page in order to extend the file. But writing to all new
27689         ** pages forces the OS to allocate them immediately, which reduces
27690         ** the chances of SIGBUS while accessing the mapped region later on.
27691         */
27692         else{
27693           static const int pgsz = 4096;
27694           int iPg;
27695 
27696           /* Write to the last byte of each newly allocated or extended page */
27697           assert( (nByte % pgsz)==0 );
27698           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
27699             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
27700               const char *zFile = pShmNode->zFilename;
27701               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
27702               goto shmpage_out;
27703             }
27704           }
27705         }
27706       }
27707     }
27708 
27709     /* Map the requested memory region into this processes address space. */
27710     apNew = (char **)sqlite3_realloc(
27711         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27712     );
27713     if( !apNew ){
27714       rc = SQLITE_IOERR_NOMEM;
27715       goto shmpage_out;
27716     }
27717     pShmNode->apRegion = apNew;
27718     while(pShmNode->nRegion<=iRegion){
27719       void *pMem;
27720       if( pShmNode->h>=0 ){
27721         pMem = osMmap(0, szRegion,
27722             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
27723             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27724         );
27725         if( pMem==MAP_FAILED ){
27726           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27727           goto shmpage_out;
27728         }
27729       }else{
27730         pMem = sqlite3_malloc(szRegion);
27731         if( pMem==0 ){
27732           rc = SQLITE_NOMEM;
27733           goto shmpage_out;
27734         }
27735         memset(pMem, 0, szRegion);
27736       }
27737       pShmNode->apRegion[pShmNode->nRegion] = pMem;
27738       pShmNode->nRegion++;
27739     }
27740   }
27741 
27742 shmpage_out:
27743   if( pShmNode->nRegion>iRegion ){
27744     *pp = pShmNode->apRegion[iRegion];
27745   }else{
27746     *pp = 0;
27747   }
27748   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27749   sqlite3_mutex_leave(pShmNode->mutex);
27750   return rc;
27751 }
27752 
27753 /*
27754 ** Change the lock state for a shared-memory segment.
27755 **
27756 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27757 ** different here than in posix.  In xShmLock(), one can go from unlocked
27758 ** to shared and back or from unlocked to exclusive and back.  But one may
27759 ** not go from shared to exclusive or from exclusive to shared.
27760 */
27761 static int unixShmLock(
27762   sqlite3_file *fd,          /* Database file holding the shared memory */
27763   int ofst,                  /* First lock to acquire or release */
27764   int n,                     /* Number of locks to acquire or release */
27765   int flags                  /* What to do with the lock */
27766 ){
27767   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27768   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27769   unixShm *pX;                          /* For looping over all siblings */
27770   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27771   int rc = SQLITE_OK;                   /* Result code */
27772   u16 mask;                             /* Mask of locks to take or release */
27773 
27774   assert( pShmNode==pDbFd->pInode->pShmNode );
27775   assert( pShmNode->pInode==pDbFd->pInode );
27776   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27777   assert( n>=1 );
27778   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27779        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27780        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27781        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27782   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27783   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27784   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27785 
27786   mask = (1<<(ofst+n)) - (1<<ofst);
27787   assert( n>1 || mask==(1<<ofst) );
27788   sqlite3_mutex_enter(pShmNode->mutex);
27789   if( flags & SQLITE_SHM_UNLOCK ){
27790     u16 allMask = 0; /* Mask of locks held by siblings */
27791 
27792     /* See if any siblings hold this same lock */
27793     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27794       if( pX==p ) continue;
27795       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27796       allMask |= pX->sharedMask;
27797     }
27798 
27799     /* Unlock the system-level locks */
27800     if( (mask & allMask)==0 ){
27801       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27802     }else{
27803       rc = SQLITE_OK;
27804     }
27805 
27806     /* Undo the local locks */
27807     if( rc==SQLITE_OK ){
27808       p->exclMask &= ~mask;
27809       p->sharedMask &= ~mask;
27810     } 
27811   }else if( flags & SQLITE_SHM_SHARED ){
27812     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27813 
27814     /* Find out which shared locks are already held by sibling connections.
27815     ** If any sibling already holds an exclusive lock, go ahead and return
27816     ** SQLITE_BUSY.
27817     */
27818     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27819       if( (pX->exclMask & mask)!=0 ){
27820         rc = SQLITE_BUSY;
27821         break;
27822       }
27823       allShared |= pX->sharedMask;
27824     }
27825 
27826     /* Get shared locks at the system level, if necessary */
27827     if( rc==SQLITE_OK ){
27828       if( (allShared & mask)==0 ){
27829         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27830       }else{
27831         rc = SQLITE_OK;
27832       }
27833     }
27834 
27835     /* Get the local shared locks */
27836     if( rc==SQLITE_OK ){
27837       p->sharedMask |= mask;
27838     }
27839   }else{
27840     /* Make sure no sibling connections hold locks that will block this
27841     ** lock.  If any do, return SQLITE_BUSY right away.
27842     */
27843     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27844       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27845         rc = SQLITE_BUSY;
27846         break;
27847       }
27848     }
27849   
27850     /* Get the exclusive locks at the system level.  Then if successful
27851     ** also mark the local connection as being locked.
27852     */
27853     if( rc==SQLITE_OK ){
27854       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27855       if( rc==SQLITE_OK ){
27856         assert( (p->sharedMask & mask)==0 );
27857         p->exclMask |= mask;
27858       }
27859     }
27860   }
27861   sqlite3_mutex_leave(pShmNode->mutex);
27862   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27863            p->id, getpid(), p->sharedMask, p->exclMask));
27864   return rc;
27865 }
27866 
27867 /*
27868 ** Implement a memory barrier or memory fence on shared memory.  
27869 **
27870 ** All loads and stores begun before the barrier must complete before
27871 ** any load or store begun after the barrier.
27872 */
27873 static void unixShmBarrier(
27874   sqlite3_file *fd                /* Database file holding the shared memory */
27875 ){
27876   UNUSED_PARAMETER(fd);
27877   unixEnterMutex();
27878   unixLeaveMutex();
27879 }
27880 
27881 /*
27882 ** Close a connection to shared-memory.  Delete the underlying 
27883 ** storage if deleteFlag is true.
27884 **
27885 ** If there is no shared memory associated with the connection then this
27886 ** routine is a harmless no-op.
27887 */
27888 static int unixShmUnmap(
27889   sqlite3_file *fd,               /* The underlying database file */
27890   int deleteFlag                  /* Delete shared-memory if true */
27891 ){
27892   unixShm *p;                     /* The connection to be closed */
27893   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27894   unixShm **pp;                   /* For looping over sibling connections */
27895   unixFile *pDbFd;                /* The underlying database file */
27896 
27897   pDbFd = (unixFile*)fd;
27898   p = pDbFd->pShm;
27899   if( p==0 ) return SQLITE_OK;
27900   pShmNode = p->pShmNode;
27901 
27902   assert( pShmNode==pDbFd->pInode->pShmNode );
27903   assert( pShmNode->pInode==pDbFd->pInode );
27904 
27905   /* Remove connection p from the set of connections associated
27906   ** with pShmNode */
27907   sqlite3_mutex_enter(pShmNode->mutex);
27908   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27909   *pp = p->pNext;
27910 
27911   /* Free the connection p */
27912   sqlite3_free(p);
27913   pDbFd->pShm = 0;
27914   sqlite3_mutex_leave(pShmNode->mutex);
27915 
27916   /* If pShmNode->nRef has reached 0, then close the underlying
27917   ** shared-memory file, too */
27918   unixEnterMutex();
27919   assert( pShmNode->nRef>0 );
27920   pShmNode->nRef--;
27921   if( pShmNode->nRef==0 ){
27922     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27923     unixShmPurge(pDbFd);
27924   }
27925   unixLeaveMutex();
27926 
27927   return SQLITE_OK;
27928 }
27929 
27930 
27931 #else
27932 # define unixShmMap     0
27933 # define unixShmLock    0
27934 # define unixShmBarrier 0
27935 # define unixShmUnmap   0
27936 #endif /* #ifndef SQLITE_OMIT_WAL */
27937 
27938 #if SQLITE_MAX_MMAP_SIZE>0
27939 /*
27940 ** If it is currently memory mapped, unmap file pFd.
27941 */
27942 static void unixUnmapfile(unixFile *pFd){
27943   assert( pFd->nFetchOut==0 );
27944   if( pFd->pMapRegion ){
27945     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
27946     pFd->pMapRegion = 0;
27947     pFd->mmapSize = 0;
27948     pFd->mmapSizeActual = 0;
27949   }
27950 }
27951 
27952 /*
27953 ** Return the system page size.
27954 */
27955 static int unixGetPagesize(void){
27956 #if HAVE_MREMAP
27957   return 512;
27958 #elif defined(_BSD_SOURCE)
27959   return getpagesize();
27960 #else
27961   return (int)sysconf(_SC_PAGESIZE);
27962 #endif
27963 }
27964 
27965 /*
27966 ** Attempt to set the size of the memory mapping maintained by file 
27967 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
27968 **
27969 ** If successful, this function sets the following variables:
27970 **
27971 **       unixFile.pMapRegion
27972 **       unixFile.mmapSize
27973 **       unixFile.mmapSizeActual
27974 **
27975 ** If unsuccessful, an error message is logged via sqlite3_log() and
27976 ** the three variables above are zeroed. In this case SQLite should
27977 ** continue accessing the database using the xRead() and xWrite()
27978 ** methods.
27979 */
27980 static void unixRemapfile(
27981   unixFile *pFd,                  /* File descriptor object */
27982   i64 nNew                        /* Required mapping size */
27983 ){
27984   const char *zErr = "mmap";
27985   int h = pFd->h;                      /* File descriptor open on db file */
27986   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
27987   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
27988   u8 *pNew = 0;                        /* Location of new mapping */
27989   int flags = PROT_READ;               /* Flags to pass to mmap() */
27990 
27991   assert( pFd->nFetchOut==0 );
27992   assert( nNew>pFd->mmapSize );
27993   assert( nNew<=pFd->mmapSizeMax );
27994   assert( nNew>0 );
27995   assert( pFd->mmapSizeActual>=pFd->mmapSize );
27996   assert( MAP_FAILED!=0 );
27997 
27998   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
27999 
28000   if( pOrig ){
28001     const int szSyspage = unixGetPagesize();
28002     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
28003     u8 *pReq = &pOrig[nReuse];
28004 
28005     /* Unmap any pages of the existing mapping that cannot be reused. */
28006     if( nReuse!=nOrig ){
28007       osMunmap(pReq, nOrig-nReuse);
28008     }
28009 
28010 #if HAVE_MREMAP
28011     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
28012     zErr = "mremap";
28013 #else
28014     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
28015     if( pNew!=MAP_FAILED ){
28016       if( pNew!=pReq ){
28017         osMunmap(pNew, nNew - nReuse);
28018         pNew = 0;
28019       }else{
28020         pNew = pOrig;
28021       }
28022     }
28023 #endif
28024 
28025     /* The attempt to extend the existing mapping failed. Free it. */
28026     if( pNew==MAP_FAILED || pNew==0 ){
28027       osMunmap(pOrig, nReuse);
28028     }
28029   }
28030 
28031   /* If pNew is still NULL, try to create an entirely new mapping. */
28032   if( pNew==0 ){
28033     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
28034   }
28035 
28036   if( pNew==MAP_FAILED ){
28037     pNew = 0;
28038     nNew = 0;
28039     unixLogError(SQLITE_OK, zErr, pFd->zPath);
28040 
28041     /* If the mmap() above failed, assume that all subsequent mmap() calls
28042     ** will probably fail too. Fall back to using xRead/xWrite exclusively
28043     ** in this case.  */
28044     pFd->mmapSizeMax = 0;
28045   }
28046   pFd->pMapRegion = (void *)pNew;
28047   pFd->mmapSize = pFd->mmapSizeActual = nNew;
28048 }
28049 
28050 /*
28051 ** Memory map or remap the file opened by file-descriptor pFd (if the file
28052 ** is already mapped, the existing mapping is replaced by the new). Or, if 
28053 ** there already exists a mapping for this file, and there are still 
28054 ** outstanding xFetch() references to it, this function is a no-op.
28055 **
28056 ** If parameter nByte is non-negative, then it is the requested size of 
28057 ** the mapping to create. Otherwise, if nByte is less than zero, then the 
28058 ** requested size is the size of the file on disk. The actual size of the
28059 ** created mapping is either the requested size or the value configured 
28060 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
28061 **
28062 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
28063 ** recreated as a result of outstanding references) or an SQLite error
28064 ** code otherwise.
28065 */
28066 static int unixMapfile(unixFile *pFd, i64 nByte){
28067   i64 nMap = nByte;
28068   int rc;
28069 
28070   assert( nMap>=0 || pFd->nFetchOut==0 );
28071   if( pFd->nFetchOut>0 ) return SQLITE_OK;
28072 
28073   if( nMap<0 ){
28074     struct stat statbuf;          /* Low-level file information */
28075     rc = osFstat(pFd->h, &statbuf);
28076     if( rc!=SQLITE_OK ){
28077       return SQLITE_IOERR_FSTAT;
28078     }
28079     nMap = statbuf.st_size;
28080   }
28081   if( nMap>pFd->mmapSizeMax ){
28082     nMap = pFd->mmapSizeMax;
28083   }
28084 
28085   if( nMap!=pFd->mmapSize ){
28086     if( nMap>0 ){
28087       unixRemapfile(pFd, nMap);
28088     }else{
28089       unixUnmapfile(pFd);
28090     }
28091   }
28092 
28093   return SQLITE_OK;
28094 }
28095 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
28096 
28097 /*
28098 ** If possible, return a pointer to a mapping of file fd starting at offset
28099 ** iOff. The mapping must be valid for at least nAmt bytes.
28100 **
28101 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
28102 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
28103 ** Finally, if an error does occur, return an SQLite error code. The final
28104 ** value of *pp is undefined in this case.
28105 **
28106 ** If this function does return a pointer, the caller must eventually 
28107 ** release the reference by calling unixUnfetch().
28108 */
28109 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
28110 #if SQLITE_MAX_MMAP_SIZE>0
28111   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
28112 #endif
28113   *pp = 0;
28114 
28115 #if SQLITE_MAX_MMAP_SIZE>0
28116   if( pFd->mmapSizeMax>0 ){
28117     if( pFd->pMapRegion==0 ){
28118       int rc = unixMapfile(pFd, -1);
28119       if( rc!=SQLITE_OK ) return rc;
28120     }
28121     if( pFd->mmapSize >= iOff+nAmt ){
28122       *pp = &((u8 *)pFd->pMapRegion)[iOff];
28123       pFd->nFetchOut++;
28124     }
28125   }
28126 #endif
28127   return SQLITE_OK;
28128 }
28129 
28130 /*
28131 ** If the third argument is non-NULL, then this function releases a 
28132 ** reference obtained by an earlier call to unixFetch(). The second
28133 ** argument passed to this function must be the same as the corresponding
28134 ** argument that was passed to the unixFetch() invocation. 
28135 **
28136 ** Or, if the third argument is NULL, then this function is being called 
28137 ** to inform the VFS layer that, according to POSIX, any existing mapping 
28138 ** may now be invalid and should be unmapped.
28139 */
28140 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
28141   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
28142   UNUSED_PARAMETER(iOff);
28143 
28144 #if SQLITE_MAX_MMAP_SIZE>0
28145   /* If p==0 (unmap the entire file) then there must be no outstanding 
28146   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
28147   ** then there must be at least one outstanding.  */
28148   assert( (p==0)==(pFd->nFetchOut==0) );
28149 
28150   /* If p!=0, it must match the iOff value. */
28151   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
28152 
28153   if( p ){
28154     pFd->nFetchOut--;
28155   }else{
28156     unixUnmapfile(pFd);
28157   }
28158 
28159   assert( pFd->nFetchOut>=0 );
28160 #endif
28161   return SQLITE_OK;
28162 }
28163 
28164 /*
28165 ** Here ends the implementation of all sqlite3_file methods.
28166 **
28167 ********************** End sqlite3_file Methods *******************************
28168 ******************************************************************************/
28169 
28170 /*
28171 ** This division contains definitions of sqlite3_io_methods objects that
28172 ** implement various file locking strategies.  It also contains definitions
28173 ** of "finder" functions.  A finder-function is used to locate the appropriate
28174 ** sqlite3_io_methods object for a particular database file.  The pAppData
28175 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28176 ** the correct finder-function for that VFS.
28177 **
28178 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28179 ** object.  The only interesting finder-function is autolockIoFinder, which
28180 ** looks at the filesystem type and tries to guess the best locking
28181 ** strategy from that.
28182 **
28183 ** For finder-funtion F, two objects are created:
28184 **
28185 **    (1) The real finder-function named "FImpt()".
28186 **
28187 **    (2) A constant pointer to this function named just "F".
28188 **
28189 **
28190 ** A pointer to the F pointer is used as the pAppData value for VFS
28191 ** objects.  We have to do this instead of letting pAppData point
28192 ** directly at the finder-function since C90 rules prevent a void*
28193 ** from be cast into a function pointer.
28194 **
28195 **
28196 ** Each instance of this macro generates two objects:
28197 **
28198 **   *  A constant sqlite3_io_methods object call METHOD that has locking
28199 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28200 **
28201 **   *  An I/O method finder function called FINDER that returns a pointer
28202 **      to the METHOD object in the previous bullet.
28203 */
28204 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28205 static const sqlite3_io_methods METHOD = {                                   \
28206    VERSION,                    /* iVersion */                                \
28207    CLOSE,                      /* xClose */                                  \
28208    unixRead,                   /* xRead */                                   \
28209    unixWrite,                  /* xWrite */                                  \
28210    unixTruncate,               /* xTruncate */                               \
28211    unixSync,                   /* xSync */                                   \
28212    unixFileSize,               /* xFileSize */                               \
28213    LOCK,                       /* xLock */                                   \
28214    UNLOCK,                     /* xUnlock */                                 \
28215    CKLOCK,                     /* xCheckReservedLock */                      \
28216    unixFileControl,            /* xFileControl */                            \
28217    unixSectorSize,             /* xSectorSize */                             \
28218    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28219    unixShmMap,                 /* xShmMap */                                 \
28220    unixShmLock,                /* xShmLock */                                \
28221    unixShmBarrier,             /* xShmBarrier */                             \
28222    unixShmUnmap,               /* xShmUnmap */                               \
28223    unixFetch,                  /* xFetch */                                  \
28224    unixUnfetch,                /* xUnfetch */                                \
28225 };                                                                           \
28226 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28227   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28228   return &METHOD;                                                            \
28229 }                                                                            \
28230 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28231     = FINDER##Impl;
28232 
28233 /*
28234 ** Here are all of the sqlite3_io_methods objects for each of the
28235 ** locking strategies.  Functions that return pointers to these methods
28236 ** are also created.
28237 */
28238 IOMETHODS(
28239   posixIoFinder,            /* Finder function name */
28240   posixIoMethods,           /* sqlite3_io_methods object name */
28241   3,                        /* shared memory and mmap are enabled */
28242   unixClose,                /* xClose method */
28243   unixLock,                 /* xLock method */
28244   unixUnlock,               /* xUnlock method */
28245   unixCheckReservedLock     /* xCheckReservedLock method */
28246 )
28247 IOMETHODS(
28248   nolockIoFinder,           /* Finder function name */
28249   nolockIoMethods,          /* sqlite3_io_methods object name */
28250   1,                        /* shared memory is disabled */
28251   nolockClose,              /* xClose method */
28252   nolockLock,               /* xLock method */
28253   nolockUnlock,             /* xUnlock method */
28254   nolockCheckReservedLock   /* xCheckReservedLock method */
28255 )
28256 IOMETHODS(
28257   dotlockIoFinder,          /* Finder function name */
28258   dotlockIoMethods,         /* sqlite3_io_methods object name */
28259   1,                        /* shared memory is disabled */
28260   dotlockClose,             /* xClose method */
28261   dotlockLock,              /* xLock method */
28262   dotlockUnlock,            /* xUnlock method */
28263   dotlockCheckReservedLock  /* xCheckReservedLock method */
28264 )
28265 
28266 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28267 IOMETHODS(
28268   flockIoFinder,            /* Finder function name */
28269   flockIoMethods,           /* sqlite3_io_methods object name */
28270   1,                        /* shared memory is disabled */
28271   flockClose,               /* xClose method */
28272   flockLock,                /* xLock method */
28273   flockUnlock,              /* xUnlock method */
28274   flockCheckReservedLock    /* xCheckReservedLock method */
28275 )
28276 #endif
28277 
28278 #if OS_VXWORKS
28279 IOMETHODS(
28280   semIoFinder,              /* Finder function name */
28281   semIoMethods,             /* sqlite3_io_methods object name */
28282   1,                        /* shared memory is disabled */
28283   semClose,                 /* xClose method */
28284   semLock,                  /* xLock method */
28285   semUnlock,                /* xUnlock method */
28286   semCheckReservedLock      /* xCheckReservedLock method */
28287 )
28288 #endif
28289 
28290 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28291 IOMETHODS(
28292   afpIoFinder,              /* Finder function name */
28293   afpIoMethods,             /* sqlite3_io_methods object name */
28294   1,                        /* shared memory is disabled */
28295   afpClose,                 /* xClose method */
28296   afpLock,                  /* xLock method */
28297   afpUnlock,                /* xUnlock method */
28298   afpCheckReservedLock      /* xCheckReservedLock method */
28299 )
28300 #endif
28301 
28302 /*
28303 ** The proxy locking method is a "super-method" in the sense that it
28304 ** opens secondary file descriptors for the conch and lock files and
28305 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28306 ** secondary files.  For this reason, the division that implements
28307 ** proxy locking is located much further down in the file.  But we need
28308 ** to go ahead and define the sqlite3_io_methods and finder function
28309 ** for proxy locking here.  So we forward declare the I/O methods.
28310 */
28311 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28312 static int proxyClose(sqlite3_file*);
28313 static int proxyLock(sqlite3_file*, int);
28314 static int proxyUnlock(sqlite3_file*, int);
28315 static int proxyCheckReservedLock(sqlite3_file*, int*);
28316 IOMETHODS(
28317   proxyIoFinder,            /* Finder function name */
28318   proxyIoMethods,           /* sqlite3_io_methods object name */
28319   1,                        /* shared memory is disabled */
28320   proxyClose,               /* xClose method */
28321   proxyLock,                /* xLock method */
28322   proxyUnlock,              /* xUnlock method */
28323   proxyCheckReservedLock    /* xCheckReservedLock method */
28324 )
28325 #endif
28326 
28327 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28328 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28329 IOMETHODS(
28330   nfsIoFinder,               /* Finder function name */
28331   nfsIoMethods,              /* sqlite3_io_methods object name */
28332   1,                         /* shared memory is disabled */
28333   unixClose,                 /* xClose method */
28334   unixLock,                  /* xLock method */
28335   nfsUnlock,                 /* xUnlock method */
28336   unixCheckReservedLock      /* xCheckReservedLock method */
28337 )
28338 #endif
28339 
28340 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28341 /* 
28342 ** This "finder" function attempts to determine the best locking strategy 
28343 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28344 ** object that implements that strategy.
28345 **
28346 ** This is for MacOSX only.
28347 */
28348 static const sqlite3_io_methods *autolockIoFinderImpl(
28349   const char *filePath,    /* name of the database file */
28350   unixFile *pNew           /* open file object for the database file */
28351 ){
28352   static const struct Mapping {
28353     const char *zFilesystem;              /* Filesystem type name */
28354     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28355   } aMap[] = {
28356     { "hfs",    &posixIoMethods },
28357     { "ufs",    &posixIoMethods },
28358     { "afpfs",  &afpIoMethods },
28359     { "smbfs",  &afpIoMethods },
28360     { "webdav", &nolockIoMethods },
28361     { 0, 0 }
28362   };
28363   int i;
28364   struct statfs fsInfo;
28365   struct flock lockInfo;
28366 
28367   if( !filePath ){
28368     /* If filePath==NULL that means we are dealing with a transient file
28369     ** that does not need to be locked. */
28370     return &nolockIoMethods;
28371   }
28372   if( statfs(filePath, &fsInfo) != -1 ){
28373     if( fsInfo.f_flags & MNT_RDONLY ){
28374       return &nolockIoMethods;
28375     }
28376     for(i=0; aMap[i].zFilesystem; i++){
28377       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28378         return aMap[i].pMethods;
28379       }
28380     }
28381   }
28382 
28383   /* Default case. Handles, amongst others, "nfs".
28384   ** Test byte-range lock using fcntl(). If the call succeeds, 
28385   ** assume that the file-system supports POSIX style locks. 
28386   */
28387   lockInfo.l_len = 1;
28388   lockInfo.l_start = 0;
28389   lockInfo.l_whence = SEEK_SET;
28390   lockInfo.l_type = F_RDLCK;
28391   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28392     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28393       return &nfsIoMethods;
28394     } else {
28395       return &posixIoMethods;
28396     }
28397   }else{
28398     return &dotlockIoMethods;
28399   }
28400 }
28401 static const sqlite3_io_methods 
28402   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28403 
28404 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28405 
28406 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28407 /* 
28408 ** This "finder" function attempts to determine the best locking strategy 
28409 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28410 ** object that implements that strategy.
28411 **
28412 ** This is for VXWorks only.
28413 */
28414 static const sqlite3_io_methods *autolockIoFinderImpl(
28415   const char *filePath,    /* name of the database file */
28416   unixFile *pNew           /* the open file object */
28417 ){
28418   struct flock lockInfo;
28419 
28420   if( !filePath ){
28421     /* If filePath==NULL that means we are dealing with a transient file
28422     ** that does not need to be locked. */
28423     return &nolockIoMethods;
28424   }
28425 
28426   /* Test if fcntl() is supported and use POSIX style locks.
28427   ** Otherwise fall back to the named semaphore method.
28428   */
28429   lockInfo.l_len = 1;
28430   lockInfo.l_start = 0;
28431   lockInfo.l_whence = SEEK_SET;
28432   lockInfo.l_type = F_RDLCK;
28433   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28434     return &posixIoMethods;
28435   }else{
28436     return &semIoMethods;
28437   }
28438 }
28439 static const sqlite3_io_methods 
28440   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28441 
28442 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28443 
28444 /*
28445 ** An abstract type for a pointer to a IO method finder function:
28446 */
28447 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28448 
28449 
28450 /****************************************************************************
28451 **************************** sqlite3_vfs methods ****************************
28452 **
28453 ** This division contains the implementation of methods on the
28454 ** sqlite3_vfs object.
28455 */
28456 
28457 /*
28458 ** Initialize the contents of the unixFile structure pointed to by pId.
28459 */
28460 static int fillInUnixFile(
28461   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28462   int h,                  /* Open file descriptor of file being opened */
28463   sqlite3_file *pId,      /* Write to the unixFile structure here */
28464   const char *zFilename,  /* Name of the file being opened */
28465   int ctrlFlags           /* Zero or more UNIXFILE_* values */
28466 ){
28467   const sqlite3_io_methods *pLockingStyle;
28468   unixFile *pNew = (unixFile *)pId;
28469   int rc = SQLITE_OK;
28470 
28471   assert( pNew->pInode==NULL );
28472 
28473   /* Usually the path zFilename should not be a relative pathname. The
28474   ** exception is when opening the proxy "conch" file in builds that
28475   ** include the special Apple locking styles.
28476   */
28477 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28478   assert( zFilename==0 || zFilename[0]=='/' 
28479     || pVfs->pAppData==(void*)&autolockIoFinder );
28480 #else
28481   assert( zFilename==0 || zFilename[0]=='/' );
28482 #endif
28483 
28484   /* No locking occurs in temporary files */
28485   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
28486 
28487   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28488   pNew->h = h;
28489   pNew->pVfs = pVfs;
28490   pNew->zPath = zFilename;
28491   pNew->ctrlFlags = (u8)ctrlFlags;
28492 #if SQLITE_MAX_MMAP_SIZE>0
28493   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28494 #endif
28495   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28496                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28497     pNew->ctrlFlags |= UNIXFILE_PSOW;
28498   }
28499   if( strcmp(pVfs->zName,"unix-excl")==0 ){
28500     pNew->ctrlFlags |= UNIXFILE_EXCL;
28501   }
28502 
28503 #if OS_VXWORKS
28504   pNew->pId = vxworksFindFileId(zFilename);
28505   if( pNew->pId==0 ){
28506     ctrlFlags |= UNIXFILE_NOLOCK;
28507     rc = SQLITE_NOMEM;
28508   }
28509 #endif
28510 
28511   if( ctrlFlags & UNIXFILE_NOLOCK ){
28512     pLockingStyle = &nolockIoMethods;
28513   }else{
28514     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28515 #if SQLITE_ENABLE_LOCKING_STYLE
28516     /* Cache zFilename in the locking context (AFP and dotlock override) for
28517     ** proxyLock activation is possible (remote proxy is based on db name)
28518     ** zFilename remains valid until file is closed, to support */
28519     pNew->lockingContext = (void*)zFilename;
28520 #endif
28521   }
28522 
28523   if( pLockingStyle == &posixIoMethods
28524 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28525     || pLockingStyle == &nfsIoMethods
28526 #endif
28527   ){
28528     unixEnterMutex();
28529     rc = findInodeInfo(pNew, &pNew->pInode);
28530     if( rc!=SQLITE_OK ){
28531       /* If an error occurred in findInodeInfo(), close the file descriptor
28532       ** immediately, before releasing the mutex. findInodeInfo() may fail
28533       ** in two scenarios:
28534       **
28535       **   (a) A call to fstat() failed.
28536       **   (b) A malloc failed.
28537       **
28538       ** Scenario (b) may only occur if the process is holding no other
28539       ** file descriptors open on the same file. If there were other file
28540       ** descriptors on this file, then no malloc would be required by
28541       ** findInodeInfo(). If this is the case, it is quite safe to close
28542       ** handle h - as it is guaranteed that no posix locks will be released
28543       ** by doing so.
28544       **
28545       ** If scenario (a) caused the error then things are not so safe. The
28546       ** implicit assumption here is that if fstat() fails, things are in
28547       ** such bad shape that dropping a lock or two doesn't matter much.
28548       */
28549       robust_close(pNew, h, __LINE__);
28550       h = -1;
28551     }
28552     unixLeaveMutex();
28553   }
28554 
28555 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28556   else if( pLockingStyle == &afpIoMethods ){
28557     /* AFP locking uses the file path so it needs to be included in
28558     ** the afpLockingContext.
28559     */
28560     afpLockingContext *pCtx;
28561     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28562     if( pCtx==0 ){
28563       rc = SQLITE_NOMEM;
28564     }else{
28565       /* NB: zFilename exists and remains valid until the file is closed
28566       ** according to requirement F11141.  So we do not need to make a
28567       ** copy of the filename. */
28568       pCtx->dbPath = zFilename;
28569       pCtx->reserved = 0;
28570       srandomdev();
28571       unixEnterMutex();
28572       rc = findInodeInfo(pNew, &pNew->pInode);
28573       if( rc!=SQLITE_OK ){
28574         sqlite3_free(pNew->lockingContext);
28575         robust_close(pNew, h, __LINE__);
28576         h = -1;
28577       }
28578       unixLeaveMutex();        
28579     }
28580   }
28581 #endif
28582 
28583   else if( pLockingStyle == &dotlockIoMethods ){
28584     /* Dotfile locking uses the file path so it needs to be included in
28585     ** the dotlockLockingContext 
28586     */
28587     char *zLockFile;
28588     int nFilename;
28589     assert( zFilename!=0 );
28590     nFilename = (int)strlen(zFilename) + 6;
28591     zLockFile = (char *)sqlite3_malloc(nFilename);
28592     if( zLockFile==0 ){
28593       rc = SQLITE_NOMEM;
28594     }else{
28595       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28596     }
28597     pNew->lockingContext = zLockFile;
28598   }
28599 
28600 #if OS_VXWORKS
28601   else if( pLockingStyle == &semIoMethods ){
28602     /* Named semaphore locking uses the file path so it needs to be
28603     ** included in the semLockingContext
28604     */
28605     unixEnterMutex();
28606     rc = findInodeInfo(pNew, &pNew->pInode);
28607     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28608       char *zSemName = pNew->pInode->aSemName;
28609       int n;
28610       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28611                        pNew->pId->zCanonicalName);
28612       for( n=1; zSemName[n]; n++ )
28613         if( zSemName[n]=='/' ) zSemName[n] = '_';
28614       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28615       if( pNew->pInode->pSem == SEM_FAILED ){
28616         rc = SQLITE_NOMEM;
28617         pNew->pInode->aSemName[0] = '\0';
28618       }
28619     }
28620     unixLeaveMutex();
28621   }
28622 #endif
28623   
28624   pNew->lastErrno = 0;
28625 #if OS_VXWORKS
28626   if( rc!=SQLITE_OK ){
28627     if( h>=0 ) robust_close(pNew, h, __LINE__);
28628     h = -1;
28629     osUnlink(zFilename);
28630     pNew->ctrlFlags |= UNIXFILE_DELETE;
28631   }
28632 #endif
28633   if( rc!=SQLITE_OK ){
28634     if( h>=0 ) robust_close(pNew, h, __LINE__);
28635   }else{
28636     pNew->pMethod = pLockingStyle;
28637     OpenCounter(+1);
28638     verifyDbFile(pNew);
28639   }
28640   return rc;
28641 }
28642 
28643 /*
28644 ** Return the name of a directory in which to put temporary files.
28645 ** If no suitable temporary file directory can be found, return NULL.
28646 */
28647 static const char *unixTempFileDir(void){
28648   static const char *azDirs[] = {
28649      0,
28650      0,
28651      0,
28652      "/var/tmp",
28653      "/usr/tmp",
28654      "/tmp",
28655      0        /* List terminator */
28656   };
28657   unsigned int i;
28658   struct stat buf;
28659   const char *zDir = 0;
28660 
28661   azDirs[0] = sqlite3_temp_directory;
28662   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
28663   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
28664   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28665     if( zDir==0 ) continue;
28666     if( osStat(zDir, &buf) ) continue;
28667     if( !S_ISDIR(buf.st_mode) ) continue;
28668     if( osAccess(zDir, 07) ) continue;
28669     break;
28670   }
28671   return zDir;
28672 }
28673 
28674 /*
28675 ** Create a temporary file name in zBuf.  zBuf must be allocated
28676 ** by the calling process and must be big enough to hold at least
28677 ** pVfs->mxPathname bytes.
28678 */
28679 static int unixGetTempname(int nBuf, char *zBuf){
28680   static const unsigned char zChars[] =
28681     "abcdefghijklmnopqrstuvwxyz"
28682     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28683     "0123456789";
28684   unsigned int i, j;
28685   const char *zDir;
28686 
28687   /* It's odd to simulate an io-error here, but really this is just
28688   ** using the io-error infrastructure to test that SQLite handles this
28689   ** function failing. 
28690   */
28691   SimulateIOError( return SQLITE_IOERR );
28692 
28693   zDir = unixTempFileDir();
28694   if( zDir==0 ) zDir = ".";
28695 
28696   /* Check that the output buffer is large enough for the temporary file 
28697   ** name. If it is not, return SQLITE_ERROR.
28698   */
28699   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
28700     return SQLITE_ERROR;
28701   }
28702 
28703   do{
28704     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28705     j = (int)strlen(zBuf);
28706     sqlite3_randomness(15, &zBuf[j]);
28707     for(i=0; i<15; i++, j++){
28708       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28709     }
28710     zBuf[j] = 0;
28711     zBuf[j+1] = 0;
28712   }while( osAccess(zBuf,0)==0 );
28713   return SQLITE_OK;
28714 }
28715 
28716 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28717 /*
28718 ** Routine to transform a unixFile into a proxy-locking unixFile.
28719 ** Implementation in the proxy-lock division, but used by unixOpen()
28720 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28721 */
28722 static int proxyTransformUnixFile(unixFile*, const char*);
28723 #endif
28724 
28725 /*
28726 ** Search for an unused file descriptor that was opened on the database 
28727 ** file (not a journal or master-journal file) identified by pathname
28728 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28729 ** argument to this function.
28730 **
28731 ** Such a file descriptor may exist if a database connection was closed
28732 ** but the associated file descriptor could not be closed because some
28733 ** other file descriptor open on the same file is holding a file-lock.
28734 ** Refer to comments in the unixClose() function and the lengthy comment
28735 ** describing "Posix Advisory Locking" at the start of this file for 
28736 ** further details. Also, ticket #4018.
28737 **
28738 ** If a suitable file descriptor is found, then it is returned. If no
28739 ** such file descriptor is located, -1 is returned.
28740 */
28741 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28742   UnixUnusedFd *pUnused = 0;
28743 
28744   /* Do not search for an unused file descriptor on vxworks. Not because
28745   ** vxworks would not benefit from the change (it might, we're not sure),
28746   ** but because no way to test it is currently available. It is better 
28747   ** not to risk breaking vxworks support for the sake of such an obscure 
28748   ** feature.  */
28749 #if !OS_VXWORKS
28750   struct stat sStat;                   /* Results of stat() call */
28751 
28752   /* A stat() call may fail for various reasons. If this happens, it is
28753   ** almost certain that an open() call on the same path will also fail.
28754   ** For this reason, if an error occurs in the stat() call here, it is
28755   ** ignored and -1 is returned. The caller will try to open a new file
28756   ** descriptor on the same path, fail, and return an error to SQLite.
28757   **
28758   ** Even if a subsequent open() call does succeed, the consequences of
28759   ** not searching for a resusable file descriptor are not dire.  */
28760   if( 0==osStat(zPath, &sStat) ){
28761     unixInodeInfo *pInode;
28762 
28763     unixEnterMutex();
28764     pInode = inodeList;
28765     while( pInode && (pInode->fileId.dev!=sStat.st_dev
28766                      || pInode->fileId.ino!=sStat.st_ino) ){
28767        pInode = pInode->pNext;
28768     }
28769     if( pInode ){
28770       UnixUnusedFd **pp;
28771       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28772       pUnused = *pp;
28773       if( pUnused ){
28774         *pp = pUnused->pNext;
28775       }
28776     }
28777     unixLeaveMutex();
28778   }
28779 #endif    /* if !OS_VXWORKS */
28780   return pUnused;
28781 }
28782 
28783 /*
28784 ** This function is called by unixOpen() to determine the unix permissions
28785 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28786 ** and a value suitable for passing as the third argument to open(2) is
28787 ** written to *pMode. If an IO error occurs, an SQLite error code is 
28788 ** returned and the value of *pMode is not modified.
28789 **
28790 ** In most cases cases, this routine sets *pMode to 0, which will become
28791 ** an indication to robust_open() to create the file using
28792 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
28793 ** But if the file being opened is a WAL or regular journal file, then 
28794 ** this function queries the file-system for the permissions on the 
28795 ** corresponding database file and sets *pMode to this value. Whenever 
28796 ** possible, WAL and journal files are created using the same permissions 
28797 ** as the associated database file.
28798 **
28799 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
28800 ** original filename is unavailable.  But 8_3_NAMES is only used for
28801 ** FAT filesystems and permissions do not matter there, so just use
28802 ** the default permissions.
28803 */
28804 static int findCreateFileMode(
28805   const char *zPath,              /* Path of file (possibly) being created */
28806   int flags,                      /* Flags passed as 4th argument to xOpen() */
28807   mode_t *pMode,                  /* OUT: Permissions to open file with */
28808   uid_t *pUid,                    /* OUT: uid to set on the file */
28809   gid_t *pGid                     /* OUT: gid to set on the file */
28810 ){
28811   int rc = SQLITE_OK;             /* Return Code */
28812   *pMode = 0;
28813   *pUid = 0;
28814   *pGid = 0;
28815   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28816     char zDb[MAX_PATHNAME+1];     /* Database file path */
28817     int nDb;                      /* Number of valid bytes in zDb */
28818     struct stat sStat;            /* Output of stat() on database file */
28819 
28820     /* zPath is a path to a WAL or journal file. The following block derives
28821     ** the path to the associated database file from zPath. This block handles
28822     ** the following naming conventions:
28823     **
28824     **   "<path to db>-journal"
28825     **   "<path to db>-wal"
28826     **   "<path to db>-journalNN"
28827     **   "<path to db>-walNN"
28828     **
28829     ** where NN is a decimal number. The NN naming schemes are 
28830     ** used by the test_multiplex.c module.
28831     */
28832     nDb = sqlite3Strlen30(zPath) - 1; 
28833 #ifdef SQLITE_ENABLE_8_3_NAMES
28834     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28835     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28836 #else
28837     while( zPath[nDb]!='-' ){
28838       assert( nDb>0 );
28839       assert( zPath[nDb]!='\n' );
28840       nDb--;
28841     }
28842 #endif
28843     memcpy(zDb, zPath, nDb);
28844     zDb[nDb] = '\0';
28845 
28846     if( 0==osStat(zDb, &sStat) ){
28847       *pMode = sStat.st_mode & 0777;
28848       *pUid = sStat.st_uid;
28849       *pGid = sStat.st_gid;
28850     }else{
28851       rc = SQLITE_IOERR_FSTAT;
28852     }
28853   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28854     *pMode = 0600;
28855   }
28856   return rc;
28857 }
28858 
28859 /*
28860 ** Open the file zPath.
28861 ** 
28862 ** Previously, the SQLite OS layer used three functions in place of this
28863 ** one:
28864 **
28865 **     sqlite3OsOpenReadWrite();
28866 **     sqlite3OsOpenReadOnly();
28867 **     sqlite3OsOpenExclusive();
28868 **
28869 ** These calls correspond to the following combinations of flags:
28870 **
28871 **     ReadWrite() ->     (READWRITE | CREATE)
28872 **     ReadOnly()  ->     (READONLY) 
28873 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28874 **
28875 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28876 ** true, the file was configured to be automatically deleted when the
28877 ** file handle closed. To achieve the same effect using this new 
28878 ** interface, add the DELETEONCLOSE flag to those specified above for 
28879 ** OpenExclusive().
28880 */
28881 static int unixOpen(
28882   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28883   const char *zPath,           /* Pathname of file to be opened */
28884   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28885   int flags,                   /* Input flags to control the opening */
28886   int *pOutFlags               /* Output flags returned to SQLite core */
28887 ){
28888   unixFile *p = (unixFile *)pFile;
28889   int fd = -1;                   /* File descriptor returned by open() */
28890   int openFlags = 0;             /* Flags to pass to open() */
28891   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28892   int noLock;                    /* True to omit locking primitives */
28893   int rc = SQLITE_OK;            /* Function Return Code */
28894   int ctrlFlags = 0;             /* UNIXFILE_* flags */
28895 
28896   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28897   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28898   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28899   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28900   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28901 #if SQLITE_ENABLE_LOCKING_STYLE
28902   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28903 #endif
28904 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28905   struct statfs fsInfo;
28906 #endif
28907 
28908   /* If creating a master or main-file journal, this function will open
28909   ** a file-descriptor on the directory too. The first time unixSync()
28910   ** is called the directory file descriptor will be fsync()ed and close()d.
28911   */
28912   int syncDir = (isCreate && (
28913         eType==SQLITE_OPEN_MASTER_JOURNAL 
28914      || eType==SQLITE_OPEN_MAIN_JOURNAL 
28915      || eType==SQLITE_OPEN_WAL
28916   ));
28917 
28918   /* If argument zPath is a NULL pointer, this function is required to open
28919   ** a temporary file. Use this buffer to store the file name in.
28920   */
28921   char zTmpname[MAX_PATHNAME+2];
28922   const char *zName = zPath;
28923 
28924   /* Check the following statements are true: 
28925   **
28926   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
28927   **   (b) if CREATE is set, then READWRITE must also be set, and
28928   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28929   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28930   */
28931   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28932   assert(isCreate==0 || isReadWrite);
28933   assert(isExclusive==0 || isCreate);
28934   assert(isDelete==0 || isCreate);
28935 
28936   /* The main DB, main journal, WAL file and master journal are never 
28937   ** automatically deleted. Nor are they ever temporary files.  */
28938   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28939   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28940   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28941   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28942 
28943   /* Assert that the upper layer has set one of the "file-type" flags. */
28944   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
28945        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
28946        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
28947        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28948   );
28949 
28950   memset(p, 0, sizeof(unixFile));
28951 
28952   if( eType==SQLITE_OPEN_MAIN_DB ){
28953     UnixUnusedFd *pUnused;
28954     pUnused = findReusableFd(zName, flags);
28955     if( pUnused ){
28956       fd = pUnused->fd;
28957     }else{
28958       pUnused = sqlite3_malloc(sizeof(*pUnused));
28959       if( !pUnused ){
28960         return SQLITE_NOMEM;
28961       }
28962     }
28963     p->pUnused = pUnused;
28964 
28965     /* Database filenames are double-zero terminated if they are not
28966     ** URIs with parameters.  Hence, they can always be passed into
28967     ** sqlite3_uri_parameter(). */
28968     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28969 
28970   }else if( !zName ){
28971     /* If zName is NULL, the upper layer is requesting a temp file. */
28972     assert(isDelete && !syncDir);
28973     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28974     if( rc!=SQLITE_OK ){
28975       return rc;
28976     }
28977     zName = zTmpname;
28978 
28979     /* Generated temporary filenames are always double-zero terminated
28980     ** for use by sqlite3_uri_parameter(). */
28981     assert( zName[strlen(zName)+1]==0 );
28982   }
28983 
28984   /* Determine the value of the flags parameter passed to POSIX function
28985   ** open(). These must be calculated even if open() is not called, as
28986   ** they may be stored as part of the file handle and used by the 
28987   ** 'conch file' locking functions later on.  */
28988   if( isReadonly )  openFlags |= O_RDONLY;
28989   if( isReadWrite ) openFlags |= O_RDWR;
28990   if( isCreate )    openFlags |= O_CREAT;
28991   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28992   openFlags |= (O_LARGEFILE|O_BINARY);
28993 
28994   if( fd<0 ){
28995     mode_t openMode;              /* Permissions to create file with */
28996     uid_t uid;                    /* Userid for the file */
28997     gid_t gid;                    /* Groupid for the file */
28998     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28999     if( rc!=SQLITE_OK ){
29000       assert( !p->pUnused );
29001       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29002       return rc;
29003     }
29004     fd = robust_open(zName, openFlags, openMode);
29005     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29006     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29007       /* Failed to open the file for read/write access. Try read-only. */
29008       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29009       openFlags &= ~(O_RDWR|O_CREAT);
29010       flags |= SQLITE_OPEN_READONLY;
29011       openFlags |= O_RDONLY;
29012       isReadonly = 1;
29013       fd = robust_open(zName, openFlags, openMode);
29014     }
29015     if( fd<0 ){
29016       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29017       goto open_finished;
29018     }
29019 
29020     /* If this process is running as root and if creating a new rollback
29021     ** journal or WAL file, set the ownership of the journal or WAL to be
29022     ** the same as the original database.
29023     */
29024     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29025       osFchown(fd, uid, gid);
29026     }
29027   }
29028   assert( fd>=0 );
29029   if( pOutFlags ){
29030     *pOutFlags = flags;
29031   }
29032 
29033   if( p->pUnused ){
29034     p->pUnused->fd = fd;
29035     p->pUnused->flags = flags;
29036   }
29037 
29038   if( isDelete ){
29039 #if OS_VXWORKS
29040     zPath = zName;
29041 #else
29042     osUnlink(zName);
29043 #endif
29044   }
29045 #if SQLITE_ENABLE_LOCKING_STYLE
29046   else{
29047     p->openFlags = openFlags;
29048   }
29049 #endif
29050 
29051   noLock = eType!=SQLITE_OPEN_MAIN_DB;
29052 
29053   
29054 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29055   if( fstatfs(fd, &fsInfo) == -1 ){
29056     ((unixFile*)pFile)->lastErrno = errno;
29057     robust_close(p, fd, __LINE__);
29058     return SQLITE_IOERR_ACCESS;
29059   }
29060   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29061     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29062   }
29063 #endif
29064 
29065   /* Set up appropriate ctrlFlags */
29066   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
29067   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
29068   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
29069   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
29070   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
29071 
29072 #if SQLITE_ENABLE_LOCKING_STYLE
29073 #if SQLITE_PREFER_PROXY_LOCKING
29074   isAutoProxy = 1;
29075 #endif
29076   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29077     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29078     int useProxy = 0;
29079 
29080     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
29081     ** never use proxy, NULL means use proxy for non-local files only.  */
29082     if( envforce!=NULL ){
29083       useProxy = atoi(envforce)>0;
29084     }else{
29085       if( statfs(zPath, &fsInfo) == -1 ){
29086         /* In theory, the close(fd) call is sub-optimal. If the file opened
29087         ** with fd is a database file, and there are other connections open
29088         ** on that file that are currently holding advisory locks on it,
29089         ** then the call to close() will cancel those locks. In practice,
29090         ** we're assuming that statfs() doesn't fail very often. At least
29091         ** not while other file descriptors opened by the same process on
29092         ** the same file are working.  */
29093         p->lastErrno = errno;
29094         robust_close(p, fd, __LINE__);
29095         rc = SQLITE_IOERR_ACCESS;
29096         goto open_finished;
29097       }
29098       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29099     }
29100     if( useProxy ){
29101       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29102       if( rc==SQLITE_OK ){
29103         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29104         if( rc!=SQLITE_OK ){
29105           /* Use unixClose to clean up the resources added in fillInUnixFile 
29106           ** and clear all the structure's references.  Specifically, 
29107           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
29108           */
29109           unixClose(pFile);
29110           return rc;
29111         }
29112       }
29113       goto open_finished;
29114     }
29115   }
29116 #endif
29117   
29118   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29119 
29120 open_finished:
29121   if( rc!=SQLITE_OK ){
29122     sqlite3_free(p->pUnused);
29123   }
29124   return rc;
29125 }
29126 
29127 
29128 /*
29129 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29130 ** the directory after deleting the file.
29131 */
29132 static int unixDelete(
29133   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29134   const char *zPath,        /* Name of file to be deleted */
29135   int dirSync               /* If true, fsync() directory after deleting file */
29136 ){
29137   int rc = SQLITE_OK;
29138   UNUSED_PARAMETER(NotUsed);
29139   SimulateIOError(return SQLITE_IOERR_DELETE);
29140   if( osUnlink(zPath)==(-1) ){
29141     if( errno==ENOENT ){
29142       rc = SQLITE_IOERR_DELETE_NOENT;
29143     }else{
29144       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29145     }
29146     return rc;
29147   }
29148 #ifndef SQLITE_DISABLE_DIRSYNC
29149   if( (dirSync & 1)!=0 ){
29150     int fd;
29151     rc = osOpenDirectory(zPath, &fd);
29152     if( rc==SQLITE_OK ){
29153 #if OS_VXWORKS
29154       if( fsync(fd)==-1 )
29155 #else
29156       if( fsync(fd) )
29157 #endif
29158       {
29159         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29160       }
29161       robust_close(0, fd, __LINE__);
29162     }else if( rc==SQLITE_CANTOPEN ){
29163       rc = SQLITE_OK;
29164     }
29165   }
29166 #endif
29167   return rc;
29168 }
29169 
29170 /*
29171 ** Test the existence of or access permissions of file zPath. The
29172 ** test performed depends on the value of flags:
29173 **
29174 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29175 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29176 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29177 **
29178 ** Otherwise return 0.
29179 */
29180 static int unixAccess(
29181   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29182   const char *zPath,      /* Path of the file to examine */
29183   int flags,              /* What do we want to learn about the zPath file? */
29184   int *pResOut            /* Write result boolean here */
29185 ){
29186   int amode = 0;
29187   UNUSED_PARAMETER(NotUsed);
29188   SimulateIOError( return SQLITE_IOERR_ACCESS; );
29189   switch( flags ){
29190     case SQLITE_ACCESS_EXISTS:
29191       amode = F_OK;
29192       break;
29193     case SQLITE_ACCESS_READWRITE:
29194       amode = W_OK|R_OK;
29195       break;
29196     case SQLITE_ACCESS_READ:
29197       amode = R_OK;
29198       break;
29199 
29200     default:
29201       assert(!"Invalid flags argument");
29202   }
29203   *pResOut = (osAccess(zPath, amode)==0);
29204   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29205     struct stat buf;
29206     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29207       *pResOut = 0;
29208     }
29209   }
29210   return SQLITE_OK;
29211 }
29212 
29213 
29214 /*
29215 ** Turn a relative pathname into a full pathname. The relative path
29216 ** is stored as a nul-terminated string in the buffer pointed to by
29217 ** zPath. 
29218 **
29219 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
29220 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29221 ** this buffer before returning.
29222 */
29223 static int unixFullPathname(
29224   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29225   const char *zPath,            /* Possibly relative input path */
29226   int nOut,                     /* Size of output buffer in bytes */
29227   char *zOut                    /* Output buffer */
29228 ){
29229 
29230   /* It's odd to simulate an io-error here, but really this is just
29231   ** using the io-error infrastructure to test that SQLite handles this
29232   ** function failing. This function could fail if, for example, the
29233   ** current working directory has been unlinked.
29234   */
29235   SimulateIOError( return SQLITE_ERROR );
29236 
29237   assert( pVfs->mxPathname==MAX_PATHNAME );
29238   UNUSED_PARAMETER(pVfs);
29239 
29240   zOut[nOut-1] = '\0';
29241   if( zPath[0]=='/' ){
29242     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29243   }else{
29244     int nCwd;
29245     if( osGetcwd(zOut, nOut-1)==0 ){
29246       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29247     }
29248     nCwd = (int)strlen(zOut);
29249     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29250   }
29251   return SQLITE_OK;
29252 }
29253 
29254 
29255 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29256 /*
29257 ** Interfaces for opening a shared library, finding entry points
29258 ** within the shared library, and closing the shared library.
29259 */
29260 #include <dlfcn.h>
29261 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29262   UNUSED_PARAMETER(NotUsed);
29263   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29264 }
29265 
29266 /*
29267 ** SQLite calls this function immediately after a call to unixDlSym() or
29268 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29269 ** message is available, it is written to zBufOut. If no error message
29270 ** is available, zBufOut is left unmodified and SQLite uses a default
29271 ** error message.
29272 */
29273 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29274   const char *zErr;
29275   UNUSED_PARAMETER(NotUsed);
29276   unixEnterMutex();
29277   zErr = dlerror();
29278   if( zErr ){
29279     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29280   }
29281   unixLeaveMutex();
29282 }
29283 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29284   /* 
29285   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29286   ** cast into a pointer to a function.  And yet the library dlsym() routine
29287   ** returns a void* which is really a pointer to a function.  So how do we
29288   ** use dlsym() with -pedantic-errors?
29289   **
29290   ** Variable x below is defined to be a pointer to a function taking
29291   ** parameters void* and const char* and returning a pointer to a function.
29292   ** We initialize x by assigning it a pointer to the dlsym() function.
29293   ** (That assignment requires a cast.)  Then we call the function that
29294   ** x points to.  
29295   **
29296   ** This work-around is unlikely to work correctly on any system where
29297   ** you really cannot cast a function pointer into void*.  But then, on the
29298   ** other hand, dlsym() will not work on such a system either, so we have
29299   ** not really lost anything.
29300   */
29301   void (*(*x)(void*,const char*))(void);
29302   UNUSED_PARAMETER(NotUsed);
29303   x = (void(*(*)(void*,const char*))(void))dlsym;
29304   return (*x)(p, zSym);
29305 }
29306 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29307   UNUSED_PARAMETER(NotUsed);
29308   dlclose(pHandle);
29309 }
29310 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29311   #define unixDlOpen  0
29312   #define unixDlError 0
29313   #define unixDlSym   0
29314   #define unixDlClose 0
29315 #endif
29316 
29317 /*
29318 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29319 */
29320 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29321   UNUSED_PARAMETER(NotUsed);
29322   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29323 
29324   /* We have to initialize zBuf to prevent valgrind from reporting
29325   ** errors.  The reports issued by valgrind are incorrect - we would
29326   ** prefer that the randomness be increased by making use of the
29327   ** uninitialized space in zBuf - but valgrind errors tend to worry
29328   ** some users.  Rather than argue, it seems easier just to initialize
29329   ** the whole array and silence valgrind, even if that means less randomness
29330   ** in the random seed.
29331   **
29332   ** When testing, initializing zBuf[] to zero is all we do.  That means
29333   ** that we always use the same random number sequence.  This makes the
29334   ** tests repeatable.
29335   */
29336   memset(zBuf, 0, nBuf);
29337 #if !defined(SQLITE_TEST)
29338   {
29339     int pid, fd, got;
29340     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29341     if( fd<0 ){
29342       time_t t;
29343       time(&t);
29344       memcpy(zBuf, &t, sizeof(t));
29345       pid = getpid();
29346       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29347       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29348       nBuf = sizeof(t) + sizeof(pid);
29349     }else{
29350       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
29351       robust_close(0, fd, __LINE__);
29352     }
29353   }
29354 #endif
29355   return nBuf;
29356 }
29357 
29358 
29359 /*
29360 ** Sleep for a little while.  Return the amount of time slept.
29361 ** The argument is the number of microseconds we want to sleep.
29362 ** The return value is the number of microseconds of sleep actually
29363 ** requested from the underlying operating system, a number which
29364 ** might be greater than or equal to the argument, but not less
29365 ** than the argument.
29366 */
29367 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29368 #if OS_VXWORKS
29369   struct timespec sp;
29370 
29371   sp.tv_sec = microseconds / 1000000;
29372   sp.tv_nsec = (microseconds % 1000000) * 1000;
29373   nanosleep(&sp, NULL);
29374   UNUSED_PARAMETER(NotUsed);
29375   return microseconds;
29376 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29377   usleep(microseconds);
29378   UNUSED_PARAMETER(NotUsed);
29379   return microseconds;
29380 #else
29381   int seconds = (microseconds+999999)/1000000;
29382   sleep(seconds);
29383   UNUSED_PARAMETER(NotUsed);
29384   return seconds*1000000;
29385 #endif
29386 }
29387 
29388 /*
29389 ** The following variable, if set to a non-zero value, is interpreted as
29390 ** the number of seconds since 1970 and is used to set the result of
29391 ** sqlite3OsCurrentTime() during testing.
29392 */
29393 #ifdef SQLITE_TEST
29394 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29395 #endif
29396 
29397 /*
29398 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29399 ** the current time and date as a Julian Day number times 86_400_000.  In
29400 ** other words, write into *piNow the number of milliseconds since the Julian
29401 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29402 ** proleptic Gregorian calendar.
29403 **
29404 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
29405 ** cannot be found.
29406 */
29407 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29408   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29409   int rc = SQLITE_OK;
29410 #if defined(NO_GETTOD)
29411   time_t t;
29412   time(&t);
29413   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29414 #elif OS_VXWORKS
29415   struct timespec sNow;
29416   clock_gettime(CLOCK_REALTIME, &sNow);
29417   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29418 #else
29419   struct timeval sNow;
29420   if( gettimeofday(&sNow, 0)==0 ){
29421     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29422   }else{
29423     rc = SQLITE_ERROR;
29424   }
29425 #endif
29426 
29427 #ifdef SQLITE_TEST
29428   if( sqlite3_current_time ){
29429     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29430   }
29431 #endif
29432   UNUSED_PARAMETER(NotUsed);
29433   return rc;
29434 }
29435 
29436 /*
29437 ** Find the current time (in Universal Coordinated Time).  Write the
29438 ** current time and date as a Julian Day number into *prNow and
29439 ** return 0.  Return 1 if the time and date cannot be found.
29440 */
29441 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29442   sqlite3_int64 i = 0;
29443   int rc;
29444   UNUSED_PARAMETER(NotUsed);
29445   rc = unixCurrentTimeInt64(0, &i);
29446   *prNow = i/86400000.0;
29447   return rc;
29448 }
29449 
29450 /*
29451 ** We added the xGetLastError() method with the intention of providing
29452 ** better low-level error messages when operating-system problems come up
29453 ** during SQLite operation.  But so far, none of that has been implemented
29454 ** in the core.  So this routine is never called.  For now, it is merely
29455 ** a place-holder.
29456 */
29457 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29458   UNUSED_PARAMETER(NotUsed);
29459   UNUSED_PARAMETER(NotUsed2);
29460   UNUSED_PARAMETER(NotUsed3);
29461   return 0;
29462 }
29463 
29464 
29465 /*
29466 ************************ End of sqlite3_vfs methods ***************************
29467 ******************************************************************************/
29468 
29469 /******************************************************************************
29470 ************************** Begin Proxy Locking ********************************
29471 **
29472 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29473 ** other locking methods on secondary lock files.  Proxy locking is a
29474 ** meta-layer over top of the primitive locking implemented above.  For
29475 ** this reason, the division that implements of proxy locking is deferred
29476 ** until late in the file (here) after all of the other I/O methods have
29477 ** been defined - so that the primitive locking methods are available
29478 ** as services to help with the implementation of proxy locking.
29479 **
29480 ****
29481 **
29482 ** The default locking schemes in SQLite use byte-range locks on the
29483 ** database file to coordinate safe, concurrent access by multiple readers
29484 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29485 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29486 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29487 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29488 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29489 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29490 ** address in the shared range is taken for a SHARED lock, the entire
29491 ** shared range is taken for an EXCLUSIVE lock):
29492 **
29493 **      PENDING_BYTE        0x40000000
29494 **      RESERVED_BYTE       0x40000001
29495 **      SHARED_RANGE        0x40000002 -> 0x40000200
29496 **
29497 ** This works well on the local file system, but shows a nearly 100x
29498 ** slowdown in read performance on AFP because the AFP client disables
29499 ** the read cache when byte-range locks are present.  Enabling the read
29500 ** cache exposes a cache coherency problem that is present on all OS X
29501 ** supported network file systems.  NFS and AFP both observe the
29502 ** close-to-open semantics for ensuring cache coherency
29503 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29504 ** address the requirements for concurrent database access by multiple
29505 ** readers and writers
29506 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29507 **
29508 ** To address the performance and cache coherency issues, proxy file locking
29509 ** changes the way database access is controlled by limiting access to a
29510 ** single host at a time and moving file locks off of the database file
29511 ** and onto a proxy file on the local file system.  
29512 **
29513 **
29514 ** Using proxy locks
29515 ** -----------------
29516 **
29517 ** C APIs
29518 **
29519 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29520 **                       <proxy_path> | ":auto:");
29521 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29522 **
29523 **
29524 ** SQL pragmas
29525 **
29526 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29527 **  PRAGMA [database.]lock_proxy_file
29528 **
29529 ** Specifying ":auto:" means that if there is a conch file with a matching
29530 ** host ID in it, the proxy path in the conch file will be used, otherwise
29531 ** a proxy path based on the user's temp dir
29532 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29533 ** actual proxy file name is generated from the name and path of the
29534 ** database file.  For example:
29535 **
29536 **       For database path "/Users/me/foo.db" 
29537 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29538 **
29539 ** Once a lock proxy is configured for a database connection, it can not
29540 ** be removed, however it may be switched to a different proxy path via
29541 ** the above APIs (assuming the conch file is not being held by another
29542 ** connection or process). 
29543 **
29544 **
29545 ** How proxy locking works
29546 ** -----------------------
29547 **
29548 ** Proxy file locking relies primarily on two new supporting files: 
29549 **
29550 **   *  conch file to limit access to the database file to a single host
29551 **      at a time
29552 **
29553 **   *  proxy file to act as a proxy for the advisory locks normally
29554 **      taken on the database
29555 **
29556 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29557 ** by taking an sqlite-style shared lock on the conch file, reading the
29558 ** contents and comparing the host's unique host ID (see below) and lock
29559 ** proxy path against the values stored in the conch.  The conch file is
29560 ** stored in the same directory as the database file and the file name
29561 ** is patterned after the database file name as ".<databasename>-conch".
29562 ** If the conch file does not exist, or it's contents do not match the
29563 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29564 ** lock and the conch file contents is updated with the host ID and proxy
29565 ** path and the lock is downgraded to a shared lock again.  If the conch
29566 ** is held by another process (with a shared lock), the exclusive lock
29567 ** will fail and SQLITE_BUSY is returned.
29568 **
29569 ** The proxy file - a single-byte file used for all advisory file locks
29570 ** normally taken on the database file.   This allows for safe sharing
29571 ** of the database file for multiple readers and writers on the same
29572 ** host (the conch ensures that they all use the same local lock file).
29573 **
29574 ** Requesting the lock proxy does not immediately take the conch, it is
29575 ** only taken when the first request to lock database file is made.  
29576 ** This matches the semantics of the traditional locking behavior, where
29577 ** opening a connection to a database file does not take a lock on it.
29578 ** The shared lock and an open file descriptor are maintained until 
29579 ** the connection to the database is closed. 
29580 **
29581 ** The proxy file and the lock file are never deleted so they only need
29582 ** to be created the first time they are used.
29583 **
29584 ** Configuration options
29585 ** ---------------------
29586 **
29587 **  SQLITE_PREFER_PROXY_LOCKING
29588 **
29589 **       Database files accessed on non-local file systems are
29590 **       automatically configured for proxy locking, lock files are
29591 **       named automatically using the same logic as
29592 **       PRAGMA lock_proxy_file=":auto:"
29593 **    
29594 **  SQLITE_PROXY_DEBUG
29595 **
29596 **       Enables the logging of error messages during host id file
29597 **       retrieval and creation
29598 **
29599 **  LOCKPROXYDIR
29600 **
29601 **       Overrides the default directory used for lock proxy files that
29602 **       are named automatically via the ":auto:" setting
29603 **
29604 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29605 **
29606 **       Permissions to use when creating a directory for storing the
29607 **       lock proxy files, only used when LOCKPROXYDIR is not set.
29608 **    
29609 **    
29610 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29611 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29612 ** force proxy locking to be used for every database file opened, and 0
29613 ** will force automatic proxy locking to be disabled for all database
29614 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29615 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29616 */
29617 
29618 /*
29619 ** Proxy locking is only available on MacOSX 
29620 */
29621 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29622 
29623 /*
29624 ** The proxyLockingContext has the path and file structures for the remote 
29625 ** and local proxy files in it
29626 */
29627 typedef struct proxyLockingContext proxyLockingContext;
29628 struct proxyLockingContext {
29629   unixFile *conchFile;         /* Open conch file */
29630   char *conchFilePath;         /* Name of the conch file */
29631   unixFile *lockProxy;         /* Open proxy lock file */
29632   char *lockProxyPath;         /* Name of the proxy lock file */
29633   char *dbPath;                /* Name of the open file */
29634   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29635   void *oldLockingContext;     /* Original lockingcontext to restore on close */
29636   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29637 };
29638 
29639 /* 
29640 ** The proxy lock file path for the database at dbPath is written into lPath, 
29641 ** which must point to valid, writable memory large enough for a maxLen length
29642 ** file path. 
29643 */
29644 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29645   int len;
29646   int dbLen;
29647   int i;
29648 
29649 #ifdef LOCKPROXYDIR
29650   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29651 #else
29652 # ifdef _CS_DARWIN_USER_TEMP_DIR
29653   {
29654     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29655       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29656                lPath, errno, getpid()));
29657       return SQLITE_IOERR_LOCK;
29658     }
29659     len = strlcat(lPath, "sqliteplocks", maxLen);    
29660   }
29661 # else
29662   len = strlcpy(lPath, "/tmp/", maxLen);
29663 # endif
29664 #endif
29665 
29666   if( lPath[len-1]!='/' ){
29667     len = strlcat(lPath, "/", maxLen);
29668   }
29669   
29670   /* transform the db path to a unique cache name */
29671   dbLen = (int)strlen(dbPath);
29672   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29673     char c = dbPath[i];
29674     lPath[i+len] = (c=='/')?'_':c;
29675   }
29676   lPath[i+len]='\0';
29677   strlcat(lPath, ":auto:", maxLen);
29678   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29679   return SQLITE_OK;
29680 }
29681 
29682 /* 
29683  ** Creates the lock file and any missing directories in lockPath
29684  */
29685 static int proxyCreateLockPath(const char *lockPath){
29686   int i, len;
29687   char buf[MAXPATHLEN];
29688   int start = 0;
29689   
29690   assert(lockPath!=NULL);
29691   /* try to create all the intermediate directories */
29692   len = (int)strlen(lockPath);
29693   buf[0] = lockPath[0];
29694   for( i=1; i<len; i++ ){
29695     if( lockPath[i] == '/' && (i - start > 0) ){
29696       /* only mkdir if leaf dir != "." or "/" or ".." */
29697       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
29698          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29699         buf[i]='\0';
29700         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29701           int err=errno;
29702           if( err!=EEXIST ) {
29703             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29704                      "'%s' proxy lock path=%s pid=%d\n",
29705                      buf, strerror(err), lockPath, getpid()));
29706             return err;
29707           }
29708         }
29709       }
29710       start=i+1;
29711     }
29712     buf[i] = lockPath[i];
29713   }
29714   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29715   return 0;
29716 }
29717 
29718 /*
29719 ** Create a new VFS file descriptor (stored in memory obtained from
29720 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29721 **
29722 ** The caller is responsible not only for closing the file descriptor
29723 ** but also for freeing the memory associated with the file descriptor.
29724 */
29725 static int proxyCreateUnixFile(
29726     const char *path,        /* path for the new unixFile */
29727     unixFile **ppFile,       /* unixFile created and returned by ref */
29728     int islockfile           /* if non zero missing dirs will be created */
29729 ) {
29730   int fd = -1;
29731   unixFile *pNew;
29732   int rc = SQLITE_OK;
29733   int openFlags = O_RDWR | O_CREAT;
29734   sqlite3_vfs dummyVfs;
29735   int terrno = 0;
29736   UnixUnusedFd *pUnused = NULL;
29737 
29738   /* 1. first try to open/create the file
29739   ** 2. if that fails, and this is a lock file (not-conch), try creating
29740   ** the parent directories and then try again.
29741   ** 3. if that fails, try to open the file read-only
29742   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29743   */
29744   pUnused = findReusableFd(path, openFlags);
29745   if( pUnused ){
29746     fd = pUnused->fd;
29747   }else{
29748     pUnused = sqlite3_malloc(sizeof(*pUnused));
29749     if( !pUnused ){
29750       return SQLITE_NOMEM;
29751     }
29752   }
29753   if( fd<0 ){
29754     fd = robust_open(path, openFlags, 0);
29755     terrno = errno;
29756     if( fd<0 && errno==ENOENT && islockfile ){
29757       if( proxyCreateLockPath(path) == SQLITE_OK ){
29758         fd = robust_open(path, openFlags, 0);
29759       }
29760     }
29761   }
29762   if( fd<0 ){
29763     openFlags = O_RDONLY;
29764     fd = robust_open(path, openFlags, 0);
29765     terrno = errno;
29766   }
29767   if( fd<0 ){
29768     if( islockfile ){
29769       return SQLITE_BUSY;
29770     }
29771     switch (terrno) {
29772       case EACCES:
29773         return SQLITE_PERM;
29774       case EIO: 
29775         return SQLITE_IOERR_LOCK; /* even though it is the conch */
29776       default:
29777         return SQLITE_CANTOPEN_BKPT;
29778     }
29779   }
29780   
29781   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29782   if( pNew==NULL ){
29783     rc = SQLITE_NOMEM;
29784     goto end_create_proxy;
29785   }
29786   memset(pNew, 0, sizeof(unixFile));
29787   pNew->openFlags = openFlags;
29788   memset(&dummyVfs, 0, sizeof(dummyVfs));
29789   dummyVfs.pAppData = (void*)&autolockIoFinder;
29790   dummyVfs.zName = "dummy";
29791   pUnused->fd = fd;
29792   pUnused->flags = openFlags;
29793   pNew->pUnused = pUnused;
29794   
29795   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
29796   if( rc==SQLITE_OK ){
29797     *ppFile = pNew;
29798     return SQLITE_OK;
29799   }
29800 end_create_proxy:    
29801   robust_close(pNew, fd, __LINE__);
29802   sqlite3_free(pNew);
29803   sqlite3_free(pUnused);
29804   return rc;
29805 }
29806 
29807 #ifdef SQLITE_TEST
29808 /* simulate multiple hosts by creating unique hostid file paths */
29809 SQLITE_API int sqlite3_hostid_num = 0;
29810 #endif
29811 
29812 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29813 
29814 /* Not always defined in the headers as it ought to be */
29815 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29816 
29817 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
29818 ** bytes of writable memory.
29819 */
29820 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29821   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29822   memset(pHostID, 0, PROXY_HOSTIDLEN);
29823 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29824                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29825   {
29826     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29827     if( gethostuuid(pHostID, &timeout) ){
29828       int err = errno;
29829       if( pError ){
29830         *pError = err;
29831       }
29832       return SQLITE_IOERR;
29833     }
29834   }
29835 #else
29836   UNUSED_PARAMETER(pError);
29837 #endif
29838 #ifdef SQLITE_TEST
29839   /* simulate multiple hosts by creating unique hostid file paths */
29840   if( sqlite3_hostid_num != 0){
29841     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29842   }
29843 #endif
29844   
29845   return SQLITE_OK;
29846 }
29847 
29848 /* The conch file contains the header, host id and lock file path
29849  */
29850 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29851 #define PROXY_HEADERLEN    1   /* conch file header length */
29852 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29853 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29854 
29855 /* 
29856 ** Takes an open conch file, copies the contents to a new path and then moves 
29857 ** it back.  The newly created file's file descriptor is assigned to the
29858 ** conch file structure and finally the original conch file descriptor is 
29859 ** closed.  Returns zero if successful.
29860 */
29861 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29862   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29863   unixFile *conchFile = pCtx->conchFile;
29864   char tPath[MAXPATHLEN];
29865   char buf[PROXY_MAXCONCHLEN];
29866   char *cPath = pCtx->conchFilePath;
29867   size_t readLen = 0;
29868   size_t pathLen = 0;
29869   char errmsg[64] = "";
29870   int fd = -1;
29871   int rc = -1;
29872   UNUSED_PARAMETER(myHostID);
29873 
29874   /* create a new path by replace the trailing '-conch' with '-break' */
29875   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29876   if( pathLen>MAXPATHLEN || pathLen<6 || 
29877      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29878     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29879     goto end_breaklock;
29880   }
29881   /* read the conch content */
29882   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29883   if( readLen<PROXY_PATHINDEX ){
29884     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29885     goto end_breaklock;
29886   }
29887   /* write it out to the temporary break file */
29888   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29889   if( fd<0 ){
29890     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29891     goto end_breaklock;
29892   }
29893   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29894     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29895     goto end_breaklock;
29896   }
29897   if( rename(tPath, cPath) ){
29898     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29899     goto end_breaklock;
29900   }
29901   rc = 0;
29902   fprintf(stderr, "broke stale lock on %s\n", cPath);
29903   robust_close(pFile, conchFile->h, __LINE__);
29904   conchFile->h = fd;
29905   conchFile->openFlags = O_RDWR | O_CREAT;
29906 
29907 end_breaklock:
29908   if( rc ){
29909     if( fd>=0 ){
29910       osUnlink(tPath);
29911       robust_close(pFile, fd, __LINE__);
29912     }
29913     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29914   }
29915   return rc;
29916 }
29917 
29918 /* Take the requested lock on the conch file and break a stale lock if the 
29919 ** host id matches.
29920 */
29921 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29922   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29923   unixFile *conchFile = pCtx->conchFile;
29924   int rc = SQLITE_OK;
29925   int nTries = 0;
29926   struct timespec conchModTime;
29927   
29928   memset(&conchModTime, 0, sizeof(conchModTime));
29929   do {
29930     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29931     nTries ++;
29932     if( rc==SQLITE_BUSY ){
29933       /* If the lock failed (busy):
29934        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
29935        * 2nd try: fail if the mod time changed or host id is different, wait 
29936        *           10 sec and try again
29937        * 3rd try: break the lock unless the mod time has changed.
29938        */
29939       struct stat buf;
29940       if( osFstat(conchFile->h, &buf) ){
29941         pFile->lastErrno = errno;
29942         return SQLITE_IOERR_LOCK;
29943       }
29944       
29945       if( nTries==1 ){
29946         conchModTime = buf.st_mtimespec;
29947         usleep(500000); /* wait 0.5 sec and try the lock again*/
29948         continue;  
29949       }
29950 
29951       assert( nTries>1 );
29952       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
29953          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29954         return SQLITE_BUSY;
29955       }
29956       
29957       if( nTries==2 ){  
29958         char tBuf[PROXY_MAXCONCHLEN];
29959         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29960         if( len<0 ){
29961           pFile->lastErrno = errno;
29962           return SQLITE_IOERR_LOCK;
29963         }
29964         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29965           /* don't break the lock if the host id doesn't match */
29966           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29967             return SQLITE_BUSY;
29968           }
29969         }else{
29970           /* don't break the lock on short read or a version mismatch */
29971           return SQLITE_BUSY;
29972         }
29973         usleep(10000000); /* wait 10 sec and try the lock again */
29974         continue; 
29975       }
29976       
29977       assert( nTries==3 );
29978       if( 0==proxyBreakConchLock(pFile, myHostID) ){
29979         rc = SQLITE_OK;
29980         if( lockType==EXCLUSIVE_LOCK ){
29981           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
29982         }
29983         if( !rc ){
29984           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29985         }
29986       }
29987     }
29988   } while( rc==SQLITE_BUSY && nTries<3 );
29989   
29990   return rc;
29991 }
29992 
29993 /* Takes the conch by taking a shared lock and read the contents conch, if 
29994 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
29995 ** lockPath means that the lockPath in the conch file will be used if the 
29996 ** host IDs match, or a new lock path will be generated automatically 
29997 ** and written to the conch file.
29998 */
29999 static int proxyTakeConch(unixFile *pFile){
30000   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30001   
30002   if( pCtx->conchHeld!=0 ){
30003     return SQLITE_OK;
30004   }else{
30005     unixFile *conchFile = pCtx->conchFile;
30006     uuid_t myHostID;
30007     int pError = 0;
30008     char readBuf[PROXY_MAXCONCHLEN];
30009     char lockPath[MAXPATHLEN];
30010     char *tempLockPath = NULL;
30011     int rc = SQLITE_OK;
30012     int createConch = 0;
30013     int hostIdMatch = 0;
30014     int readLen = 0;
30015     int tryOldLockPath = 0;
30016     int forceNewLockPath = 0;
30017     
30018     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30019              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30020 
30021     rc = proxyGetHostID(myHostID, &pError);
30022     if( (rc&0xff)==SQLITE_IOERR ){
30023       pFile->lastErrno = pError;
30024       goto end_takeconch;
30025     }
30026     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30027     if( rc!=SQLITE_OK ){
30028       goto end_takeconch;
30029     }
30030     /* read the existing conch file */
30031     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30032     if( readLen<0 ){
30033       /* I/O error: lastErrno set by seekAndRead */
30034       pFile->lastErrno = conchFile->lastErrno;
30035       rc = SQLITE_IOERR_READ;
30036       goto end_takeconch;
30037     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
30038              readBuf[0]!=(char)PROXY_CONCHVERSION ){
30039       /* a short read or version format mismatch means we need to create a new 
30040       ** conch file. 
30041       */
30042       createConch = 1;
30043     }
30044     /* if the host id matches and the lock path already exists in the conch
30045     ** we'll try to use the path there, if we can't open that path, we'll 
30046     ** retry with a new auto-generated path 
30047     */
30048     do { /* in case we need to try again for an :auto: named lock file */
30049 
30050       if( !createConch && !forceNewLockPath ){
30051         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
30052                                   PROXY_HOSTIDLEN);
30053         /* if the conch has data compare the contents */
30054         if( !pCtx->lockProxyPath ){
30055           /* for auto-named local lock file, just check the host ID and we'll
30056            ** use the local lock file path that's already in there
30057            */
30058           if( hostIdMatch ){
30059             size_t pathLen = (readLen - PROXY_PATHINDEX);
30060             
30061             if( pathLen>=MAXPATHLEN ){
30062               pathLen=MAXPATHLEN-1;
30063             }
30064             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30065             lockPath[pathLen] = 0;
30066             tempLockPath = lockPath;
30067             tryOldLockPath = 1;
30068             /* create a copy of the lock path if the conch is taken */
30069             goto end_takeconch;
30070           }
30071         }else if( hostIdMatch
30072                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30073                            readLen-PROXY_PATHINDEX)
30074         ){
30075           /* conch host and lock path match */
30076           goto end_takeconch; 
30077         }
30078       }
30079       
30080       /* if the conch isn't writable and doesn't match, we can't take it */
30081       if( (conchFile->openFlags&O_RDWR) == 0 ){
30082         rc = SQLITE_BUSY;
30083         goto end_takeconch;
30084       }
30085       
30086       /* either the conch didn't match or we need to create a new one */
30087       if( !pCtx->lockProxyPath ){
30088         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30089         tempLockPath = lockPath;
30090         /* create a copy of the lock path _only_ if the conch is taken */
30091       }
30092       
30093       /* update conch with host and path (this will fail if other process
30094       ** has a shared lock already), if the host id matches, use the big
30095       ** stick.
30096       */
30097       futimes(conchFile->h, NULL);
30098       if( hostIdMatch && !createConch ){
30099         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30100           /* We are trying for an exclusive lock but another thread in this
30101            ** same process is still holding a shared lock. */
30102           rc = SQLITE_BUSY;
30103         } else {          
30104           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30105         }
30106       }else{
30107         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30108       }
30109       if( rc==SQLITE_OK ){
30110         char writeBuffer[PROXY_MAXCONCHLEN];
30111         int writeSize = 0;
30112         
30113         writeBuffer[0] = (char)PROXY_CONCHVERSION;
30114         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30115         if( pCtx->lockProxyPath!=NULL ){
30116           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30117         }else{
30118           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30119         }
30120         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30121         robust_ftruncate(conchFile->h, writeSize);
30122         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30123         fsync(conchFile->h);
30124         /* If we created a new conch file (not just updated the contents of a 
30125          ** valid conch file), try to match the permissions of the database 
30126          */
30127         if( rc==SQLITE_OK && createConch ){
30128           struct stat buf;
30129           int err = osFstat(pFile->h, &buf);
30130           if( err==0 ){
30131             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30132                                         S_IROTH|S_IWOTH);
30133             /* try to match the database file R/W permissions, ignore failure */
30134 #ifndef SQLITE_PROXY_DEBUG
30135             osFchmod(conchFile->h, cmode);
30136 #else
30137             do{
30138               rc = osFchmod(conchFile->h, cmode);
30139             }while( rc==(-1) && errno==EINTR );
30140             if( rc!=0 ){
30141               int code = errno;
30142               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30143                       cmode, code, strerror(code));
30144             } else {
30145               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30146             }
30147           }else{
30148             int code = errno;
30149             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
30150                     err, code, strerror(code));
30151 #endif
30152           }
30153         }
30154       }
30155       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30156       
30157     end_takeconch:
30158       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30159       if( rc==SQLITE_OK && pFile->openFlags ){
30160         int fd;
30161         if( pFile->h>=0 ){
30162           robust_close(pFile, pFile->h, __LINE__);
30163         }
30164         pFile->h = -1;
30165         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
30166         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30167         if( fd>=0 ){
30168           pFile->h = fd;
30169         }else{
30170           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30171            during locking */
30172         }
30173       }
30174       if( rc==SQLITE_OK && !pCtx->lockProxy ){
30175         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30176         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30177         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30178           /* we couldn't create the proxy lock file with the old lock file path
30179            ** so try again via auto-naming 
30180            */
30181           forceNewLockPath = 1;
30182           tryOldLockPath = 0;
30183           continue; /* go back to the do {} while start point, try again */
30184         }
30185       }
30186       if( rc==SQLITE_OK ){
30187         /* Need to make a copy of path if we extracted the value
30188          ** from the conch file or the path was allocated on the stack
30189          */
30190         if( tempLockPath ){
30191           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30192           if( !pCtx->lockProxyPath ){
30193             rc = SQLITE_NOMEM;
30194           }
30195         }
30196       }
30197       if( rc==SQLITE_OK ){
30198         pCtx->conchHeld = 1;
30199         
30200         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30201           afpLockingContext *afpCtx;
30202           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30203           afpCtx->dbPath = pCtx->lockProxyPath;
30204         }
30205       } else {
30206         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30207       }
30208       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30209                rc==SQLITE_OK?"ok":"failed"));
30210       return rc;
30211     } while (1); /* in case we need to retry the :auto: lock file - 
30212                  ** we should never get here except via the 'continue' call. */
30213   }
30214 }
30215 
30216 /*
30217 ** If pFile holds a lock on a conch file, then release that lock.
30218 */
30219 static int proxyReleaseConch(unixFile *pFile){
30220   int rc = SQLITE_OK;         /* Subroutine return code */
30221   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30222   unixFile *conchFile;        /* Name of the conch file */
30223 
30224   pCtx = (proxyLockingContext *)pFile->lockingContext;
30225   conchFile = pCtx->conchFile;
30226   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30227            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
30228            getpid()));
30229   if( pCtx->conchHeld>0 ){
30230     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30231   }
30232   pCtx->conchHeld = 0;
30233   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30234            (rc==SQLITE_OK ? "ok" : "failed")));
30235   return rc;
30236 }
30237 
30238 /*
30239 ** Given the name of a database file, compute the name of its conch file.
30240 ** Store the conch filename in memory obtained from sqlite3_malloc().
30241 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30242 ** or SQLITE_NOMEM if unable to obtain memory.
30243 **
30244 ** The caller is responsible for ensuring that the allocated memory
30245 ** space is eventually freed.
30246 **
30247 ** *pConchPath is set to NULL if a memory allocation error occurs.
30248 */
30249 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30250   int i;                        /* Loop counter */
30251   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30252   char *conchPath;              /* buffer in which to construct conch name */
30253 
30254   /* Allocate space for the conch filename and initialize the name to
30255   ** the name of the original database file. */  
30256   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30257   if( conchPath==0 ){
30258     return SQLITE_NOMEM;
30259   }
30260   memcpy(conchPath, dbPath, len+1);
30261   
30262   /* now insert a "." before the last / character */
30263   for( i=(len-1); i>=0; i-- ){
30264     if( conchPath[i]=='/' ){
30265       i++;
30266       break;
30267     }
30268   }
30269   conchPath[i]='.';
30270   while ( i<len ){
30271     conchPath[i+1]=dbPath[i];
30272     i++;
30273   }
30274 
30275   /* append the "-conch" suffix to the file */
30276   memcpy(&conchPath[i+1], "-conch", 7);
30277   assert( (int)strlen(conchPath) == len+7 );
30278 
30279   return SQLITE_OK;
30280 }
30281 
30282 
30283 /* Takes a fully configured proxy locking-style unix file and switches
30284 ** the local lock file path 
30285 */
30286 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30287   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30288   char *oldPath = pCtx->lockProxyPath;
30289   int rc = SQLITE_OK;
30290 
30291   if( pFile->eFileLock!=NO_LOCK ){
30292     return SQLITE_BUSY;
30293   }  
30294 
30295   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30296   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30297     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30298     return SQLITE_OK;
30299   }else{
30300     unixFile *lockProxy = pCtx->lockProxy;
30301     pCtx->lockProxy=NULL;
30302     pCtx->conchHeld = 0;
30303     if( lockProxy!=NULL ){
30304       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30305       if( rc ) return rc;
30306       sqlite3_free(lockProxy);
30307     }
30308     sqlite3_free(oldPath);
30309     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30310   }
30311   
30312   return rc;
30313 }
30314 
30315 /*
30316 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30317 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30318 **
30319 ** This routine find the filename associated with pFile and writes it
30320 ** int dbPath.
30321 */
30322 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30323 #if defined(__APPLE__)
30324   if( pFile->pMethod == &afpIoMethods ){
30325     /* afp style keeps a reference to the db path in the filePath field 
30326     ** of the struct */
30327     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30328     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30329   } else
30330 #endif
30331   if( pFile->pMethod == &dotlockIoMethods ){
30332     /* dot lock style uses the locking context to store the dot lock
30333     ** file path */
30334     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30335     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30336   }else{
30337     /* all other styles use the locking context to store the db file path */
30338     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30339     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30340   }
30341   return SQLITE_OK;
30342 }
30343 
30344 /*
30345 ** Takes an already filled in unix file and alters it so all file locking 
30346 ** will be performed on the local proxy lock file.  The following fields
30347 ** are preserved in the locking context so that they can be restored and 
30348 ** the unix structure properly cleaned up at close time:
30349 **  ->lockingContext
30350 **  ->pMethod
30351 */
30352 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30353   proxyLockingContext *pCtx;
30354   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30355   char *lockPath=NULL;
30356   int rc = SQLITE_OK;
30357   
30358   if( pFile->eFileLock!=NO_LOCK ){
30359     return SQLITE_BUSY;
30360   }
30361   proxyGetDbPathForUnixFile(pFile, dbPath);
30362   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30363     lockPath=NULL;
30364   }else{
30365     lockPath=(char *)path;
30366   }
30367   
30368   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30369            (lockPath ? lockPath : ":auto:"), getpid()));
30370 
30371   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30372   if( pCtx==0 ){
30373     return SQLITE_NOMEM;
30374   }
30375   memset(pCtx, 0, sizeof(*pCtx));
30376 
30377   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30378   if( rc==SQLITE_OK ){
30379     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30380     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30381       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30382       ** (c) the file system is read-only, then enable no-locking access.
30383       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30384       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30385       */
30386       struct statfs fsInfo;
30387       struct stat conchInfo;
30388       int goLockless = 0;
30389 
30390       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30391         int err = errno;
30392         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30393           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30394         }
30395       }
30396       if( goLockless ){
30397         pCtx->conchHeld = -1; /* read only FS/ lockless */
30398         rc = SQLITE_OK;
30399       }
30400     }
30401   }  
30402   if( rc==SQLITE_OK && lockPath ){
30403     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30404   }
30405 
30406   if( rc==SQLITE_OK ){
30407     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30408     if( pCtx->dbPath==NULL ){
30409       rc = SQLITE_NOMEM;
30410     }
30411   }
30412   if( rc==SQLITE_OK ){
30413     /* all memory is allocated, proxys are created and assigned, 
30414     ** switch the locking context and pMethod then return.
30415     */
30416     pCtx->oldLockingContext = pFile->lockingContext;
30417     pFile->lockingContext = pCtx;
30418     pCtx->pOldMethod = pFile->pMethod;
30419     pFile->pMethod = &proxyIoMethods;
30420   }else{
30421     if( pCtx->conchFile ){ 
30422       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30423       sqlite3_free(pCtx->conchFile);
30424     }
30425     sqlite3DbFree(0, pCtx->lockProxyPath);
30426     sqlite3_free(pCtx->conchFilePath); 
30427     sqlite3_free(pCtx);
30428   }
30429   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30430            (rc==SQLITE_OK ? "ok" : "failed")));
30431   return rc;
30432 }
30433 
30434 
30435 /*
30436 ** This routine handles sqlite3_file_control() calls that are specific
30437 ** to proxy locking.
30438 */
30439 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30440   switch( op ){
30441     case SQLITE_GET_LOCKPROXYFILE: {
30442       unixFile *pFile = (unixFile*)id;
30443       if( pFile->pMethod == &proxyIoMethods ){
30444         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30445         proxyTakeConch(pFile);
30446         if( pCtx->lockProxyPath ){
30447           *(const char **)pArg = pCtx->lockProxyPath;
30448         }else{
30449           *(const char **)pArg = ":auto: (not held)";
30450         }
30451       } else {
30452         *(const char **)pArg = NULL;
30453       }
30454       return SQLITE_OK;
30455     }
30456     case SQLITE_SET_LOCKPROXYFILE: {
30457       unixFile *pFile = (unixFile*)id;
30458       int rc = SQLITE_OK;
30459       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30460       if( pArg==NULL || (const char *)pArg==0 ){
30461         if( isProxyStyle ){
30462           /* turn off proxy locking - not supported */
30463           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30464         }else{
30465           /* turn off proxy locking - already off - NOOP */
30466           rc = SQLITE_OK;
30467         }
30468       }else{
30469         const char *proxyPath = (const char *)pArg;
30470         if( isProxyStyle ){
30471           proxyLockingContext *pCtx = 
30472             (proxyLockingContext*)pFile->lockingContext;
30473           if( !strcmp(pArg, ":auto:") 
30474            || (pCtx->lockProxyPath &&
30475                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30476           ){
30477             rc = SQLITE_OK;
30478           }else{
30479             rc = switchLockProxyPath(pFile, proxyPath);
30480           }
30481         }else{
30482           /* turn on proxy file locking */
30483           rc = proxyTransformUnixFile(pFile, proxyPath);
30484         }
30485       }
30486       return rc;
30487     }
30488     default: {
30489       assert( 0 );  /* The call assures that only valid opcodes are sent */
30490     }
30491   }
30492   /*NOTREACHED*/
30493   return SQLITE_ERROR;
30494 }
30495 
30496 /*
30497 ** Within this division (the proxying locking implementation) the procedures
30498 ** above this point are all utilities.  The lock-related methods of the
30499 ** proxy-locking sqlite3_io_method object follow.
30500 */
30501 
30502 
30503 /*
30504 ** This routine checks if there is a RESERVED lock held on the specified
30505 ** file by this or any other process. If such a lock is held, set *pResOut
30506 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30507 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30508 */
30509 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30510   unixFile *pFile = (unixFile*)id;
30511   int rc = proxyTakeConch(pFile);
30512   if( rc==SQLITE_OK ){
30513     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30514     if( pCtx->conchHeld>0 ){
30515       unixFile *proxy = pCtx->lockProxy;
30516       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30517     }else{ /* conchHeld < 0 is lockless */
30518       pResOut=0;
30519     }
30520   }
30521   return rc;
30522 }
30523 
30524 /*
30525 ** Lock the file with the lock specified by parameter eFileLock - one
30526 ** of the following:
30527 **
30528 **     (1) SHARED_LOCK
30529 **     (2) RESERVED_LOCK
30530 **     (3) PENDING_LOCK
30531 **     (4) EXCLUSIVE_LOCK
30532 **
30533 ** Sometimes when requesting one lock state, additional lock states
30534 ** are inserted in between.  The locking might fail on one of the later
30535 ** transitions leaving the lock state different from what it started but
30536 ** still short of its goal.  The following chart shows the allowed
30537 ** transitions and the inserted intermediate states:
30538 **
30539 **    UNLOCKED -> SHARED
30540 **    SHARED -> RESERVED
30541 **    SHARED -> (PENDING) -> EXCLUSIVE
30542 **    RESERVED -> (PENDING) -> EXCLUSIVE
30543 **    PENDING -> EXCLUSIVE
30544 **
30545 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30546 ** routine to lower a locking level.
30547 */
30548 static int proxyLock(sqlite3_file *id, int eFileLock) {
30549   unixFile *pFile = (unixFile*)id;
30550   int rc = proxyTakeConch(pFile);
30551   if( rc==SQLITE_OK ){
30552     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30553     if( pCtx->conchHeld>0 ){
30554       unixFile *proxy = pCtx->lockProxy;
30555       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30556       pFile->eFileLock = proxy->eFileLock;
30557     }else{
30558       /* conchHeld < 0 is lockless */
30559     }
30560   }
30561   return rc;
30562 }
30563 
30564 
30565 /*
30566 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30567 ** must be either NO_LOCK or SHARED_LOCK.
30568 **
30569 ** If the locking level of the file descriptor is already at or below
30570 ** the requested locking level, this routine is a no-op.
30571 */
30572 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30573   unixFile *pFile = (unixFile*)id;
30574   int rc = proxyTakeConch(pFile);
30575   if( rc==SQLITE_OK ){
30576     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30577     if( pCtx->conchHeld>0 ){
30578       unixFile *proxy = pCtx->lockProxy;
30579       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30580       pFile->eFileLock = proxy->eFileLock;
30581     }else{
30582       /* conchHeld < 0 is lockless */
30583     }
30584   }
30585   return rc;
30586 }
30587 
30588 /*
30589 ** Close a file that uses proxy locks.
30590 */
30591 static int proxyClose(sqlite3_file *id) {
30592   if( id ){
30593     unixFile *pFile = (unixFile*)id;
30594     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30595     unixFile *lockProxy = pCtx->lockProxy;
30596     unixFile *conchFile = pCtx->conchFile;
30597     int rc = SQLITE_OK;
30598     
30599     if( lockProxy ){
30600       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30601       if( rc ) return rc;
30602       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30603       if( rc ) return rc;
30604       sqlite3_free(lockProxy);
30605       pCtx->lockProxy = 0;
30606     }
30607     if( conchFile ){
30608       if( pCtx->conchHeld ){
30609         rc = proxyReleaseConch(pFile);
30610         if( rc ) return rc;
30611       }
30612       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30613       if( rc ) return rc;
30614       sqlite3_free(conchFile);
30615     }
30616     sqlite3DbFree(0, pCtx->lockProxyPath);
30617     sqlite3_free(pCtx->conchFilePath);
30618     sqlite3DbFree(0, pCtx->dbPath);
30619     /* restore the original locking context and pMethod then close it */
30620     pFile->lockingContext = pCtx->oldLockingContext;
30621     pFile->pMethod = pCtx->pOldMethod;
30622     sqlite3_free(pCtx);
30623     return pFile->pMethod->xClose(id);
30624   }
30625   return SQLITE_OK;
30626 }
30627 
30628 
30629 
30630 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30631 /*
30632 ** The proxy locking style is intended for use with AFP filesystems.
30633 ** And since AFP is only supported on MacOSX, the proxy locking is also
30634 ** restricted to MacOSX.
30635 ** 
30636 **
30637 ******************* End of the proxy lock implementation **********************
30638 ******************************************************************************/
30639 
30640 /*
30641 ** Initialize the operating system interface.
30642 **
30643 ** This routine registers all VFS implementations for unix-like operating
30644 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
30645 ** should be the only routines in this file that are visible from other
30646 ** files.
30647 **
30648 ** This routine is called once during SQLite initialization and by a
30649 ** single thread.  The memory allocation and mutex subsystems have not
30650 ** necessarily been initialized when this routine is called, and so they
30651 ** should not be used.
30652 */
30653 SQLITE_API int sqlite3_os_init(void){ 
30654   /* 
30655   ** The following macro defines an initializer for an sqlite3_vfs object.
30656   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30657   ** to the "finder" function.  (pAppData is a pointer to a pointer because
30658   ** silly C90 rules prohibit a void* from being cast to a function pointer
30659   ** and so we have to go through the intermediate pointer to avoid problems
30660   ** when compiling with -pedantic-errors on GCC.)
30661   **
30662   ** The FINDER parameter to this macro is the name of the pointer to the
30663   ** finder-function.  The finder-function returns a pointer to the
30664   ** sqlite_io_methods object that implements the desired locking
30665   ** behaviors.  See the division above that contains the IOMETHODS
30666   ** macro for addition information on finder-functions.
30667   **
30668   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30669   ** object.  But the "autolockIoFinder" available on MacOSX does a little
30670   ** more than that; it looks at the filesystem type that hosts the 
30671   ** database file and tries to choose an locking method appropriate for
30672   ** that filesystem time.
30673   */
30674   #define UNIXVFS(VFSNAME, FINDER) {                        \
30675     3,                    /* iVersion */                    \
30676     sizeof(unixFile),     /* szOsFile */                    \
30677     MAX_PATHNAME,         /* mxPathname */                  \
30678     0,                    /* pNext */                       \
30679     VFSNAME,              /* zName */                       \
30680     (void*)&FINDER,       /* pAppData */                    \
30681     unixOpen,             /* xOpen */                       \
30682     unixDelete,           /* xDelete */                     \
30683     unixAccess,           /* xAccess */                     \
30684     unixFullPathname,     /* xFullPathname */               \
30685     unixDlOpen,           /* xDlOpen */                     \
30686     unixDlError,          /* xDlError */                    \
30687     unixDlSym,            /* xDlSym */                      \
30688     unixDlClose,          /* xDlClose */                    \
30689     unixRandomness,       /* xRandomness */                 \
30690     unixSleep,            /* xSleep */                      \
30691     unixCurrentTime,      /* xCurrentTime */                \
30692     unixGetLastError,     /* xGetLastError */               \
30693     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30694     unixSetSystemCall,    /* xSetSystemCall */              \
30695     unixGetSystemCall,    /* xGetSystemCall */              \
30696     unixNextSystemCall,   /* xNextSystemCall */             \
30697   }
30698 
30699   /*
30700   ** All default VFSes for unix are contained in the following array.
30701   **
30702   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30703   ** by the SQLite core when the VFS is registered.  So the following
30704   ** array cannot be const.
30705   */
30706   static sqlite3_vfs aVfs[] = {
30707 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30708     UNIXVFS("unix",          autolockIoFinder ),
30709 #else
30710     UNIXVFS("unix",          posixIoFinder ),
30711 #endif
30712     UNIXVFS("unix-none",     nolockIoFinder ),
30713     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30714     UNIXVFS("unix-excl",     posixIoFinder ),
30715 #if OS_VXWORKS
30716     UNIXVFS("unix-namedsem", semIoFinder ),
30717 #endif
30718 #if SQLITE_ENABLE_LOCKING_STYLE
30719     UNIXVFS("unix-posix",    posixIoFinder ),
30720 #if !OS_VXWORKS
30721     UNIXVFS("unix-flock",    flockIoFinder ),
30722 #endif
30723 #endif
30724 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30725     UNIXVFS("unix-afp",      afpIoFinder ),
30726     UNIXVFS("unix-nfs",      nfsIoFinder ),
30727     UNIXVFS("unix-proxy",    proxyIoFinder ),
30728 #endif
30729   };
30730   unsigned int i;          /* Loop counter */
30731 
30732   /* Double-check that the aSyscall[] array has been constructed
30733   ** correctly.  See ticket [bb3a86e890c8e96ab] */
30734   assert( ArraySize(aSyscall)==24 );
30735 
30736   /* Register all VFSes defined in the aVfs[] array */
30737   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30738     sqlite3_vfs_register(&aVfs[i], i==0);
30739   }
30740   return SQLITE_OK; 
30741 }
30742 
30743 /*
30744 ** Shutdown the operating system interface.
30745 **
30746 ** Some operating systems might need to do some cleanup in this routine,
30747 ** to release dynamically allocated objects.  But not on unix.
30748 ** This routine is a no-op for unix.
30749 */
30750 SQLITE_API int sqlite3_os_end(void){ 
30751   return SQLITE_OK; 
30752 }
30753  
30754 #endif /* SQLITE_OS_UNIX */
30755 
30756 /************** End of os_unix.c *********************************************/
30757 /************** Begin file os_win.c ******************************************/
30758 /*
30759 ** 2004 May 22
30760 **
30761 ** The author disclaims copyright to this source code.  In place of
30762 ** a legal notice, here is a blessing:
30763 **
30764 **    May you do good and not evil.
30765 **    May you find forgiveness for yourself and forgive others.
30766 **    May you share freely, never taking more than you give.
30767 **
30768 ******************************************************************************
30769 **
30770 ** This file contains code that is specific to Windows.
30771 */
30772 #if SQLITE_OS_WIN               /* This file is used for Windows only */
30773 
30774 #ifdef __CYGWIN__
30775 # include <sys/cygwin.h>
30776 # include <errno.h> /* amalgamator: keep */
30777 #endif
30778 
30779 /*
30780 ** Include code that is common to all os_*.c files
30781 */
30782 /************** Include os_common.h in the middle of os_win.c ****************/
30783 /************** Begin file os_common.h ***************************************/
30784 /*
30785 ** 2004 May 22
30786 **
30787 ** The author disclaims copyright to this source code.  In place of
30788 ** a legal notice, here is a blessing:
30789 **
30790 **    May you do good and not evil.
30791 **    May you find forgiveness for yourself and forgive others.
30792 **    May you share freely, never taking more than you give.
30793 **
30794 ******************************************************************************
30795 **
30796 ** This file contains macros and a little bit of code that is common to
30797 ** all of the platform-specific files (os_*.c) and is #included into those
30798 ** files.
30799 **
30800 ** This file should be #included by the os_*.c files only.  It is not a
30801 ** general purpose header file.
30802 */
30803 #ifndef _OS_COMMON_H_
30804 #define _OS_COMMON_H_
30805 
30806 /*
30807 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30808 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30809 ** switch.  The following code should catch this problem at compile-time.
30810 */
30811 #ifdef MEMORY_DEBUG
30812 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30813 #endif
30814 
30815 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30816 # ifndef SQLITE_DEBUG_OS_TRACE
30817 #   define SQLITE_DEBUG_OS_TRACE 0
30818 # endif
30819   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30820 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30821 #else
30822 # define OSTRACE(X)
30823 #endif
30824 
30825 /*
30826 ** Macros for performance tracing.  Normally turned off.  Only works
30827 ** on i486 hardware.
30828 */
30829 #ifdef SQLITE_PERFORMANCE_TRACE
30830 
30831 /* 
30832 ** hwtime.h contains inline assembler code for implementing 
30833 ** high-performance timing routines.
30834 */
30835 /************** Include hwtime.h in the middle of os_common.h ****************/
30836 /************** Begin file hwtime.h ******************************************/
30837 /*
30838 ** 2008 May 27
30839 **
30840 ** The author disclaims copyright to this source code.  In place of
30841 ** a legal notice, here is a blessing:
30842 **
30843 **    May you do good and not evil.
30844 **    May you find forgiveness for yourself and forgive others.
30845 **    May you share freely, never taking more than you give.
30846 **
30847 ******************************************************************************
30848 **
30849 ** This file contains inline asm code for retrieving "high-performance"
30850 ** counters for x86 class CPUs.
30851 */
30852 #ifndef _HWTIME_H_
30853 #define _HWTIME_H_
30854 
30855 /*
30856 ** The following routine only works on pentium-class (or newer) processors.
30857 ** It uses the RDTSC opcode to read the cycle count value out of the
30858 ** processor and returns that value.  This can be used for high-res
30859 ** profiling.
30860 */
30861 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30862       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30863 
30864   #if defined(__GNUC__)
30865 
30866   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30867      unsigned int lo, hi;
30868      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30869      return (sqlite_uint64)hi << 32 | lo;
30870   }
30871 
30872   #elif defined(_MSC_VER)
30873 
30874   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30875      __asm {
30876         rdtsc
30877         ret       ; return value at EDX:EAX
30878      }
30879   }
30880 
30881   #endif
30882 
30883 #elif (defined(__GNUC__) && defined(__x86_64__))
30884 
30885   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30886       unsigned long val;
30887       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30888       return val;
30889   }
30890  
30891 #elif (defined(__GNUC__) && defined(__ppc__))
30892 
30893   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30894       unsigned long long retval;
30895       unsigned long junk;
30896       __asm__ __volatile__ ("\n\
30897           1:      mftbu   %1\n\
30898                   mftb    %L0\n\
30899                   mftbu   %0\n\
30900                   cmpw    %0,%1\n\
30901                   bne     1b"
30902                   : "=r" (retval), "=r" (junk));
30903       return retval;
30904   }
30905 
30906 #else
30907 
30908   #error Need implementation of sqlite3Hwtime() for your platform.
30909 
30910   /*
30911   ** To compile without implementing sqlite3Hwtime() for your platform,
30912   ** you can remove the above #error and use the following
30913   ** stub function.  You will lose timing support for many
30914   ** of the debugging and testing utilities, but it should at
30915   ** least compile and run.
30916   */
30917 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30918 
30919 #endif
30920 
30921 #endif /* !defined(_HWTIME_H_) */
30922 
30923 /************** End of hwtime.h **********************************************/
30924 /************** Continuing where we left off in os_common.h ******************/
30925 
30926 static sqlite_uint64 g_start;
30927 static sqlite_uint64 g_elapsed;
30928 #define TIMER_START       g_start=sqlite3Hwtime()
30929 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30930 #define TIMER_ELAPSED     g_elapsed
30931 #else
30932 #define TIMER_START
30933 #define TIMER_END
30934 #define TIMER_ELAPSED     ((sqlite_uint64)0)
30935 #endif
30936 
30937 /*
30938 ** If we compile with the SQLITE_TEST macro set, then the following block
30939 ** of code will give us the ability to simulate a disk I/O error.  This
30940 ** is used for testing the I/O recovery logic.
30941 */
30942 #ifdef SQLITE_TEST
30943 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30944 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30945 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30946 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30947 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30948 SQLITE_API int sqlite3_diskfull_pending = 0;
30949 SQLITE_API int sqlite3_diskfull = 0;
30950 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30951 #define SimulateIOError(CODE)  \
30952   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30953        || sqlite3_io_error_pending-- == 1 )  \
30954               { local_ioerr(); CODE; }
30955 static void local_ioerr(){
30956   IOTRACE(("IOERR\n"));
30957   sqlite3_io_error_hit++;
30958   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30959 }
30960 #define SimulateDiskfullError(CODE) \
30961    if( sqlite3_diskfull_pending ){ \
30962      if( sqlite3_diskfull_pending == 1 ){ \
30963        local_ioerr(); \
30964        sqlite3_diskfull = 1; \
30965        sqlite3_io_error_hit = 1; \
30966        CODE; \
30967      }else{ \
30968        sqlite3_diskfull_pending--; \
30969      } \
30970    }
30971 #else
30972 #define SimulateIOErrorBenign(X)
30973 #define SimulateIOError(A)
30974 #define SimulateDiskfullError(A)
30975 #endif
30976 
30977 /*
30978 ** When testing, keep a count of the number of open files.
30979 */
30980 #ifdef SQLITE_TEST
30981 SQLITE_API int sqlite3_open_file_count = 0;
30982 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
30983 #else
30984 #define OpenCounter(X)
30985 #endif
30986 
30987 #endif /* !defined(_OS_COMMON_H_) */
30988 
30989 /************** End of os_common.h *******************************************/
30990 /************** Continuing where we left off in os_win.c *********************/
30991 
30992 /*
30993 ** Compiling and using WAL mode requires several APIs that are only
30994 ** available in Windows platforms based on the NT kernel.
30995 */
30996 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30997 #  error "WAL mode requires support from the Windows NT kernel, compile\
30998  with SQLITE_OMIT_WAL."
30999 #endif
31000 
31001 /*
31002 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
31003 ** based on the sub-platform)?
31004 */
31005 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
31006 #  define SQLITE_WIN32_HAS_ANSI
31007 #endif
31008 
31009 /*
31010 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
31011 ** based on the sub-platform)?
31012 */
31013 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
31014     !defined(SQLITE_WIN32_NO_WIDE)
31015 #  define SQLITE_WIN32_HAS_WIDE
31016 #endif
31017 
31018 /*
31019 ** Make sure at least one set of Win32 APIs is available.
31020 */
31021 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
31022 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
31023  must be defined."
31024 #endif
31025 
31026 /*
31027 ** Define the required Windows SDK version constants if they are not
31028 ** already available.
31029 */
31030 #ifndef NTDDI_WIN8
31031 #  define NTDDI_WIN8                        0x06020000
31032 #endif
31033 
31034 #ifndef NTDDI_WINBLUE
31035 #  define NTDDI_WINBLUE                     0x06030000
31036 #endif
31037 
31038 /*
31039 ** Check if the GetVersionEx[AW] functions should be considered deprecated
31040 ** and avoid using them in that case.  It should be noted here that if the
31041 ** value of the SQLITE_WIN32_GETVERSIONEX pre-processor macro is zero
31042 ** (whether via this block or via being manually specified), that implies
31043 ** the underlying operating system will always be based on the Windows NT
31044 ** Kernel.
31045 */
31046 #ifndef SQLITE_WIN32_GETVERSIONEX
31047 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
31048 #    define SQLITE_WIN32_GETVERSIONEX   0
31049 #  else
31050 #    define SQLITE_WIN32_GETVERSIONEX   1
31051 #  endif
31052 #endif
31053 
31054 /*
31055 ** This constant should already be defined (in the "WinDef.h" SDK file).
31056 */
31057 #ifndef MAX_PATH
31058 #  define MAX_PATH                      (260)
31059 #endif
31060 
31061 /*
31062 ** Maximum pathname length (in chars) for Win32.  This should normally be
31063 ** MAX_PATH.
31064 */
31065 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
31066 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
31067 #endif
31068 
31069 /*
31070 ** This constant should already be defined (in the "WinNT.h" SDK file).
31071 */
31072 #ifndef UNICODE_STRING_MAX_CHARS
31073 #  define UNICODE_STRING_MAX_CHARS      (32767)
31074 #endif
31075 
31076 /*
31077 ** Maximum pathname length (in chars) for WinNT.  This should normally be
31078 ** UNICODE_STRING_MAX_CHARS.
31079 */
31080 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
31081 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
31082 #endif
31083 
31084 /*
31085 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
31086 ** characters, so we allocate 4 bytes per character assuming worst-case of
31087 ** 4-bytes-per-character for UTF8.
31088 */
31089 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
31090 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
31091 #endif
31092 
31093 /*
31094 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
31095 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
31096 */
31097 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
31098 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
31099                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
31100 #endif
31101 
31102 /*
31103 ** Maximum error message length (in chars) for WinRT.
31104 */
31105 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
31106 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
31107 #endif
31108 
31109 /*
31110 ** Returns non-zero if the character should be treated as a directory
31111 ** separator.
31112 */
31113 #ifndef winIsDirSep
31114 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
31115 #endif
31116 
31117 /*
31118 ** This macro is used when a local variable is set to a value that is
31119 ** [sometimes] not used by the code (e.g. via conditional compilation).
31120 */
31121 #ifndef UNUSED_VARIABLE_VALUE
31122 #  define UNUSED_VARIABLE_VALUE(x) (void)(x)
31123 #endif
31124 
31125 /*
31126 ** Returns the character that should be used as the directory separator.
31127 */
31128 #ifndef winGetDirSep
31129 #  define winGetDirSep()                '\\'
31130 #endif
31131 
31132 /*
31133 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
31134 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
31135 ** are not present in the header file)?
31136 */
31137 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
31138 /*
31139 ** Two of the file mapping APIs are different under WinRT.  Figure out which
31140 ** set we need.
31141 */
31142 #if SQLITE_OS_WINRT
31143 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
31144         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
31145 
31146 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
31147 #else
31148 #if defined(SQLITE_WIN32_HAS_ANSI)
31149 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
31150         DWORD, DWORD, DWORD, LPCSTR);
31151 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
31152 
31153 #if defined(SQLITE_WIN32_HAS_WIDE)
31154 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
31155         DWORD, DWORD, DWORD, LPCWSTR);
31156 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
31157 
31158 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
31159 #endif /* SQLITE_OS_WINRT */
31160 
31161 /*
31162 ** This file mapping API is common to both Win32 and WinRT.
31163 */
31164 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
31165 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
31166 
31167 /*
31168 ** Some Microsoft compilers lack this definition.
31169 */
31170 #ifndef INVALID_FILE_ATTRIBUTES
31171 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
31172 #endif
31173 
31174 #ifndef FILE_FLAG_MASK
31175 # define FILE_FLAG_MASK          (0xFF3C0000)
31176 #endif
31177 
31178 #ifndef FILE_ATTRIBUTE_MASK
31179 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
31180 #endif
31181 
31182 #ifndef SQLITE_OMIT_WAL
31183 /* Forward references to structures used for WAL */
31184 typedef struct winShm winShm;           /* A connection to shared-memory */
31185 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31186 #endif
31187 
31188 /*
31189 ** WinCE lacks native support for file locking so we have to fake it
31190 ** with some code of our own.
31191 */
31192 #if SQLITE_OS_WINCE
31193 typedef struct winceLock {
31194   int nReaders;       /* Number of reader locks obtained */
31195   BOOL bPending;      /* Indicates a pending lock has been obtained */
31196   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31197   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31198 } winceLock;
31199 #endif
31200 
31201 /*
31202 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31203 ** portability layer.
31204 */
31205 typedef struct winFile winFile;
31206 struct winFile {
31207   const sqlite3_io_methods *pMethod; /*** Must be first ***/
31208   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31209   HANDLE h;               /* Handle for accessing the file */
31210   u8 locktype;            /* Type of lock currently held on this file */
31211   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31212   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
31213   DWORD lastErrno;        /* The Windows errno from the last I/O error */
31214 #ifndef SQLITE_OMIT_WAL
31215   winShm *pShm;           /* Instance of shared memory on this file */
31216 #endif
31217   const char *zPath;      /* Full pathname of this file */
31218   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31219 #if SQLITE_OS_WINCE
31220   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
31221   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
31222   HANDLE hShared;         /* Shared memory segment used for locking */
31223   winceLock local;        /* Locks obtained by this instance of winFile */
31224   winceLock *shared;      /* Global shared lock memory for the file  */
31225 #endif
31226 #if SQLITE_MAX_MMAP_SIZE>0
31227   int nFetchOut;                /* Number of outstanding xFetch references */
31228   HANDLE hMap;                  /* Handle for accessing memory mapping */
31229   void *pMapRegion;             /* Area memory mapped */
31230   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
31231   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
31232   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
31233 #endif
31234 };
31235 
31236 /*
31237 ** Allowed values for winFile.ctrlFlags
31238 */
31239 #define WINFILE_RDONLY          0x02   /* Connection is read only */
31240 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
31241 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
31242 
31243 /*
31244  * The size of the buffer used by sqlite3_win32_write_debug().
31245  */
31246 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
31247 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
31248 #endif
31249 
31250 /*
31251  * The value used with sqlite3_win32_set_directory() to specify that
31252  * the data directory should be changed.
31253  */
31254 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
31255 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
31256 #endif
31257 
31258 /*
31259  * The value used with sqlite3_win32_set_directory() to specify that
31260  * the temporary directory should be changed.
31261  */
31262 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31263 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
31264 #endif
31265 
31266 /*
31267  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
31268  * various Win32 API heap functions instead of our own.
31269  */
31270 #ifdef SQLITE_WIN32_MALLOC
31271 
31272 /*
31273  * If this is non-zero, an isolated heap will be created by the native Win32
31274  * allocator subsystem; otherwise, the default process heap will be used.  This
31275  * setting has no effect when compiling for WinRT.  By default, this is enabled
31276  * and an isolated heap will be created to store all allocated data.
31277  *
31278  ******************************************************************************
31279  * WARNING: It is important to note that when this setting is non-zero and the
31280  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
31281  *          function), all data that was allocated using the isolated heap will
31282  *          be freed immediately and any attempt to access any of that freed
31283  *          data will almost certainly result in an immediate access violation.
31284  ******************************************************************************
31285  */
31286 #ifndef SQLITE_WIN32_HEAP_CREATE
31287 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
31288 #endif
31289 
31290 /*
31291  * The initial size of the Win32-specific heap.  This value may be zero.
31292  */
31293 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
31294 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
31295                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
31296 #endif
31297 
31298 /*
31299  * The maximum size of the Win32-specific heap.  This value may be zero.
31300  */
31301 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
31302 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
31303 #endif
31304 
31305 /*
31306  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
31307  * zero for the default behavior.
31308  */
31309 #ifndef SQLITE_WIN32_HEAP_FLAGS
31310 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
31311 #endif
31312 
31313 
31314 /*
31315 ** The winMemData structure stores information required by the Win32-specific
31316 ** sqlite3_mem_methods implementation.
31317 */
31318 typedef struct winMemData winMemData;
31319 struct winMemData {
31320 #ifndef NDEBUG
31321   u32 magic1;   /* Magic number to detect structure corruption. */
31322 #endif
31323   HANDLE hHeap; /* The handle to our heap. */
31324   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
31325 #ifndef NDEBUG
31326   u32 magic2;   /* Magic number to detect structure corruption. */
31327 #endif
31328 };
31329 
31330 #ifndef NDEBUG
31331 #define WINMEM_MAGIC1     0x42b2830b
31332 #define WINMEM_MAGIC2     0xbd4d7cf4
31333 #endif
31334 
31335 static struct winMemData win_mem_data = {
31336 #ifndef NDEBUG
31337   WINMEM_MAGIC1,
31338 #endif
31339   NULL, FALSE
31340 #ifndef NDEBUG
31341   ,WINMEM_MAGIC2
31342 #endif
31343 };
31344 
31345 #ifndef NDEBUG
31346 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
31347 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
31348 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
31349 #else
31350 #define winMemAssertMagic()
31351 #endif
31352 
31353 #define winMemGetDataPtr()  &win_mem_data
31354 #define winMemGetHeap()     win_mem_data.hHeap
31355 #define winMemGetOwned()    win_mem_data.bOwned
31356 
31357 static void *winMemMalloc(int nBytes);
31358 static void winMemFree(void *pPrior);
31359 static void *winMemRealloc(void *pPrior, int nBytes);
31360 static int winMemSize(void *p);
31361 static int winMemRoundup(int n);
31362 static int winMemInit(void *pAppData);
31363 static void winMemShutdown(void *pAppData);
31364 
31365 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
31366 #endif /* SQLITE_WIN32_MALLOC */
31367 
31368 /*
31369 ** The following variable is (normally) set once and never changes
31370 ** thereafter.  It records whether the operating system is Win9x
31371 ** or WinNT.
31372 **
31373 ** 0:   Operating system unknown.
31374 ** 1:   Operating system is Win9x.
31375 ** 2:   Operating system is WinNT.
31376 **
31377 ** In order to facilitate testing on a WinNT system, the test fixture
31378 ** can manually set this value to 1 to emulate Win98 behavior.
31379 */
31380 #ifdef SQLITE_TEST
31381 SQLITE_API int sqlite3_os_type = 0;
31382 #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
31383       defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
31384 static int sqlite3_os_type = 0;
31385 #endif
31386 
31387 #ifndef SYSCALL
31388 #  define SYSCALL sqlite3_syscall_ptr
31389 #endif
31390 
31391 /*
31392 ** This function is not available on Windows CE or WinRT.
31393  */
31394 
31395 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31396 #  define osAreFileApisANSI()       1
31397 #endif
31398 
31399 /*
31400 ** Many system calls are accessed through pointer-to-functions so that
31401 ** they may be overridden at runtime to facilitate fault injection during
31402 ** testing and sandboxing.  The following array holds the names and pointers
31403 ** to all overrideable system calls.
31404 */
31405 static struct win_syscall {
31406   const char *zName;            /* Name of the system call */
31407   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
31408   sqlite3_syscall_ptr pDefault; /* Default value */
31409 } aSyscall[] = {
31410 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31411   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
31412 #else
31413   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
31414 #endif
31415 
31416 #ifndef osAreFileApisANSI
31417 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
31418 #endif
31419 
31420 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31421   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
31422 #else
31423   { "CharLowerW",              (SYSCALL)0,                       0 },
31424 #endif
31425 
31426 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
31427 
31428 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31429   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
31430 #else
31431   { "CharUpperW",              (SYSCALL)0,                       0 },
31432 #endif
31433 
31434 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
31435 
31436   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
31437 
31438 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
31439 
31440 #if defined(SQLITE_WIN32_HAS_ANSI)
31441   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
31442 #else
31443   { "CreateFileA",             (SYSCALL)0,                       0 },
31444 #endif
31445 
31446 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
31447         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
31448 
31449 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31450   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
31451 #else
31452   { "CreateFileW",             (SYSCALL)0,                       0 },
31453 #endif
31454 
31455 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
31456         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
31457 
31458 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
31459         !defined(SQLITE_OMIT_WAL))
31460   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
31461 #else
31462   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
31463 #endif
31464 
31465 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31466         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
31467 
31468 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31469         !defined(SQLITE_OMIT_WAL))
31470   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
31471 #else
31472   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
31473 #endif
31474 
31475 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31476         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
31477 
31478 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31479   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
31480 #else
31481   { "CreateMutexW",            (SYSCALL)0,                       0 },
31482 #endif
31483 
31484 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
31485         LPCWSTR))aSyscall[8].pCurrent)
31486 
31487 #if defined(SQLITE_WIN32_HAS_ANSI)
31488   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
31489 #else
31490   { "DeleteFileA",             (SYSCALL)0,                       0 },
31491 #endif
31492 
31493 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
31494 
31495 #if defined(SQLITE_WIN32_HAS_WIDE)
31496   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
31497 #else
31498   { "DeleteFileW",             (SYSCALL)0,                       0 },
31499 #endif
31500 
31501 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
31502 
31503 #if SQLITE_OS_WINCE
31504   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
31505 #else
31506   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
31507 #endif
31508 
31509 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31510         LPFILETIME))aSyscall[11].pCurrent)
31511 
31512 #if SQLITE_OS_WINCE
31513   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
31514 #else
31515   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
31516 #endif
31517 
31518 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31519         LPSYSTEMTIME))aSyscall[12].pCurrent)
31520 
31521   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
31522 
31523 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
31524 
31525 #if defined(SQLITE_WIN32_HAS_ANSI)
31526   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
31527 #else
31528   { "FormatMessageA",          (SYSCALL)0,                       0 },
31529 #endif
31530 
31531 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
31532         DWORD,va_list*))aSyscall[14].pCurrent)
31533 
31534 #if defined(SQLITE_WIN32_HAS_WIDE)
31535   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
31536 #else
31537   { "FormatMessageW",          (SYSCALL)0,                       0 },
31538 #endif
31539 
31540 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
31541         DWORD,va_list*))aSyscall[15].pCurrent)
31542 
31543 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31544   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
31545 #else
31546   { "FreeLibrary",             (SYSCALL)0,                       0 },
31547 #endif
31548 
31549 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
31550 
31551   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
31552 
31553 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
31554 
31555 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31556   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
31557 #else
31558   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
31559 #endif
31560 
31561 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
31562         LPDWORD))aSyscall[18].pCurrent)
31563 
31564 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31565   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
31566 #else
31567   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
31568 #endif
31569 
31570 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
31571         LPDWORD))aSyscall[19].pCurrent)
31572 
31573 #if defined(SQLITE_WIN32_HAS_ANSI)
31574   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
31575 #else
31576   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
31577 #endif
31578 
31579 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
31580 
31581 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31582   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
31583 #else
31584   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
31585 #endif
31586 
31587 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
31588 
31589 #if defined(SQLITE_WIN32_HAS_WIDE)
31590   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
31591 #else
31592   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
31593 #endif
31594 
31595 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
31596         LPVOID))aSyscall[22].pCurrent)
31597 
31598 #if !SQLITE_OS_WINRT
31599   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
31600 #else
31601   { "GetFileSize",             (SYSCALL)0,                       0 },
31602 #endif
31603 
31604 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
31605 
31606 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31607   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
31608 #else
31609   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
31610 #endif
31611 
31612 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
31613         LPSTR*))aSyscall[24].pCurrent)
31614 
31615 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31616   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
31617 #else
31618   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
31619 #endif
31620 
31621 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
31622         LPWSTR*))aSyscall[25].pCurrent)
31623 
31624   { "GetLastError",            (SYSCALL)GetLastError,            0 },
31625 
31626 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
31627 
31628 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31629 #if SQLITE_OS_WINCE
31630   /* The GetProcAddressA() routine is only available on Windows CE. */
31631   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
31632 #else
31633   /* All other Windows platforms expect GetProcAddress() to take
31634   ** an ANSI string regardless of the _UNICODE setting */
31635   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
31636 #endif
31637 #else
31638   { "GetProcAddressA",         (SYSCALL)0,                       0 },
31639 #endif
31640 
31641 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
31642         LPCSTR))aSyscall[27].pCurrent)
31643 
31644 #if !SQLITE_OS_WINRT
31645   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
31646 #else
31647   { "GetSystemInfo",           (SYSCALL)0,                       0 },
31648 #endif
31649 
31650 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
31651 
31652   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
31653 
31654 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
31655 
31656 #if !SQLITE_OS_WINCE
31657   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
31658 #else
31659   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
31660 #endif
31661 
31662 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
31663         LPFILETIME))aSyscall[30].pCurrent)
31664 
31665 #if defined(SQLITE_WIN32_HAS_ANSI)
31666   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
31667 #else
31668   { "GetTempPathA",            (SYSCALL)0,                       0 },
31669 #endif
31670 
31671 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
31672 
31673 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31674   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
31675 #else
31676   { "GetTempPathW",            (SYSCALL)0,                       0 },
31677 #endif
31678 
31679 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
31680 
31681 #if !SQLITE_OS_WINRT
31682   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
31683 #else
31684   { "GetTickCount",            (SYSCALL)0,                       0 },
31685 #endif
31686 
31687 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
31688 
31689 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
31690         SQLITE_WIN32_GETVERSIONEX
31691   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
31692 #else
31693   { "GetVersionExA",           (SYSCALL)0,                       0 },
31694 #endif
31695 
31696 #define osGetVersionExA ((BOOL(WINAPI*)( \
31697         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
31698 
31699 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31700         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
31701   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
31702 #else
31703   { "GetVersionExW",           (SYSCALL)0,                       0 },
31704 #endif
31705 
31706 #define osGetVersionExW ((BOOL(WINAPI*)( \
31707         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
31708 
31709   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
31710 
31711 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
31712         SIZE_T))aSyscall[36].pCurrent)
31713 
31714 #if !SQLITE_OS_WINRT
31715   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
31716 #else
31717   { "HeapCreate",              (SYSCALL)0,                       0 },
31718 #endif
31719 
31720 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
31721         SIZE_T))aSyscall[37].pCurrent)
31722 
31723 #if !SQLITE_OS_WINRT
31724   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
31725 #else
31726   { "HeapDestroy",             (SYSCALL)0,                       0 },
31727 #endif
31728 
31729 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
31730 
31731   { "HeapFree",                (SYSCALL)HeapFree,                0 },
31732 
31733 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
31734 
31735   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
31736 
31737 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
31738         SIZE_T))aSyscall[40].pCurrent)
31739 
31740   { "HeapSize",                (SYSCALL)HeapSize,                0 },
31741 
31742 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
31743         LPCVOID))aSyscall[41].pCurrent)
31744 
31745 #if !SQLITE_OS_WINRT
31746   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
31747 #else
31748   { "HeapValidate",            (SYSCALL)0,                       0 },
31749 #endif
31750 
31751 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
31752         LPCVOID))aSyscall[42].pCurrent)
31753 
31754 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31755   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
31756 #else
31757   { "HeapCompact",             (SYSCALL)0,                       0 },
31758 #endif
31759 
31760 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
31761 
31762 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31763   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
31764 #else
31765   { "LoadLibraryA",            (SYSCALL)0,                       0 },
31766 #endif
31767 
31768 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
31769 
31770 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31771         !defined(SQLITE_OMIT_LOAD_EXTENSION)
31772   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
31773 #else
31774   { "LoadLibraryW",            (SYSCALL)0,                       0 },
31775 #endif
31776 
31777 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
31778 
31779 #if !SQLITE_OS_WINRT
31780   { "LocalFree",               (SYSCALL)LocalFree,               0 },
31781 #else
31782   { "LocalFree",               (SYSCALL)0,                       0 },
31783 #endif
31784 
31785 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
31786 
31787 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31788   { "LockFile",                (SYSCALL)LockFile,                0 },
31789 #else
31790   { "LockFile",                (SYSCALL)0,                       0 },
31791 #endif
31792 
31793 #ifndef osLockFile
31794 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31795         DWORD))aSyscall[47].pCurrent)
31796 #endif
31797 
31798 #if !SQLITE_OS_WINCE
31799   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
31800 #else
31801   { "LockFileEx",              (SYSCALL)0,                       0 },
31802 #endif
31803 
31804 #ifndef osLockFileEx
31805 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
31806         LPOVERLAPPED))aSyscall[48].pCurrent)
31807 #endif
31808 
31809 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
31810   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
31811 #else
31812   { "MapViewOfFile",           (SYSCALL)0,                       0 },
31813 #endif
31814 
31815 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31816         SIZE_T))aSyscall[49].pCurrent)
31817 
31818   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
31819 
31820 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
31821         int))aSyscall[50].pCurrent)
31822 
31823   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
31824 
31825 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
31826         LARGE_INTEGER*))aSyscall[51].pCurrent)
31827 
31828   { "ReadFile",                (SYSCALL)ReadFile,                0 },
31829 
31830 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
31831         LPOVERLAPPED))aSyscall[52].pCurrent)
31832 
31833   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
31834 
31835 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
31836 
31837 #if !SQLITE_OS_WINRT
31838   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
31839 #else
31840   { "SetFilePointer",          (SYSCALL)0,                       0 },
31841 #endif
31842 
31843 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
31844         DWORD))aSyscall[54].pCurrent)
31845 
31846 #if !SQLITE_OS_WINRT
31847   { "Sleep",                   (SYSCALL)Sleep,                   0 },
31848 #else
31849   { "Sleep",                   (SYSCALL)0,                       0 },
31850 #endif
31851 
31852 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
31853 
31854   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
31855 
31856 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
31857         LPFILETIME))aSyscall[56].pCurrent)
31858 
31859 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31860   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
31861 #else
31862   { "UnlockFile",              (SYSCALL)0,                       0 },
31863 #endif
31864 
31865 #ifndef osUnlockFile
31866 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31867         DWORD))aSyscall[57].pCurrent)
31868 #endif
31869 
31870 #if !SQLITE_OS_WINCE
31871   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
31872 #else
31873   { "UnlockFileEx",            (SYSCALL)0,                       0 },
31874 #endif
31875 
31876 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31877         LPOVERLAPPED))aSyscall[58].pCurrent)
31878 
31879 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
31880   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
31881 #else
31882   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
31883 #endif
31884 
31885 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
31886 
31887   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
31888 
31889 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
31890         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
31891 
31892   { "WriteFile",               (SYSCALL)WriteFile,               0 },
31893 
31894 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
31895         LPOVERLAPPED))aSyscall[61].pCurrent)
31896 
31897 #if SQLITE_OS_WINRT
31898   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
31899 #else
31900   { "CreateEventExW",          (SYSCALL)0,                       0 },
31901 #endif
31902 
31903 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
31904         DWORD,DWORD))aSyscall[62].pCurrent)
31905 
31906 #if !SQLITE_OS_WINRT
31907   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
31908 #else
31909   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
31910 #endif
31911 
31912 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
31913         DWORD))aSyscall[63].pCurrent)
31914 
31915 #if SQLITE_OS_WINRT
31916   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
31917 #else
31918   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
31919 #endif
31920 
31921 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
31922         BOOL))aSyscall[64].pCurrent)
31923 
31924 #if SQLITE_OS_WINRT
31925   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
31926 #else
31927   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
31928 #endif
31929 
31930 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
31931         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
31932 
31933 #if SQLITE_OS_WINRT
31934   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
31935 #else
31936   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
31937 #endif
31938 
31939 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
31940         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
31941 
31942 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31943   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
31944 #else
31945   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
31946 #endif
31947 
31948 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
31949         SIZE_T))aSyscall[67].pCurrent)
31950 
31951 #if SQLITE_OS_WINRT
31952   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
31953 #else
31954   { "CreateFile2",             (SYSCALL)0,                       0 },
31955 #endif
31956 
31957 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
31958         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
31959 
31960 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31961   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
31962 #else
31963   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
31964 #endif
31965 
31966 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31967         DWORD))aSyscall[69].pCurrent)
31968 
31969 #if SQLITE_OS_WINRT
31970   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
31971 #else
31972   { "GetTickCount64",          (SYSCALL)0,                       0 },
31973 #endif
31974 
31975 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
31976 
31977 #if SQLITE_OS_WINRT
31978   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
31979 #else
31980   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
31981 #endif
31982 
31983 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31984         LPSYSTEM_INFO))aSyscall[71].pCurrent)
31985 
31986 #if defined(SQLITE_WIN32_HAS_ANSI)
31987   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
31988 #else
31989   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
31990 #endif
31991 
31992 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
31993 
31994 #if defined(SQLITE_WIN32_HAS_WIDE)
31995   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
31996 #else
31997   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
31998 #endif
31999 
32000 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
32001 
32002   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
32003 
32004 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
32005 
32006 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
32007   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
32008 #else
32009   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
32010 #endif
32011 
32012 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
32013         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
32014 
32015 }; /* End of the overrideable system calls */
32016 
32017 /*
32018 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
32019 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
32020 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
32021 ** system call named zName.
32022 */
32023 static int winSetSystemCall(
32024   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
32025   const char *zName,            /* Name of system call to override */
32026   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
32027 ){
32028   unsigned int i;
32029   int rc = SQLITE_NOTFOUND;
32030 
32031   UNUSED_PARAMETER(pNotUsed);
32032   if( zName==0 ){
32033     /* If no zName is given, restore all system calls to their default
32034     ** settings and return NULL
32035     */
32036     rc = SQLITE_OK;
32037     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32038       if( aSyscall[i].pDefault ){
32039         aSyscall[i].pCurrent = aSyscall[i].pDefault;
32040       }
32041     }
32042   }else{
32043     /* If zName is specified, operate on only the one system call
32044     ** specified.
32045     */
32046     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32047       if( strcmp(zName, aSyscall[i].zName)==0 ){
32048         if( aSyscall[i].pDefault==0 ){
32049           aSyscall[i].pDefault = aSyscall[i].pCurrent;
32050         }
32051         rc = SQLITE_OK;
32052         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
32053         aSyscall[i].pCurrent = pNewFunc;
32054         break;
32055       }
32056     }
32057   }
32058   return rc;
32059 }
32060 
32061 /*
32062 ** Return the value of a system call.  Return NULL if zName is not a
32063 ** recognized system call name.  NULL is also returned if the system call
32064 ** is currently undefined.
32065 */
32066 static sqlite3_syscall_ptr winGetSystemCall(
32067   sqlite3_vfs *pNotUsed,
32068   const char *zName
32069 ){
32070   unsigned int i;
32071 
32072   UNUSED_PARAMETER(pNotUsed);
32073   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32074     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
32075   }
32076   return 0;
32077 }
32078 
32079 /*
32080 ** Return the name of the first system call after zName.  If zName==NULL
32081 ** then return the name of the first system call.  Return NULL if zName
32082 ** is the last system call or if zName is not the name of a valid
32083 ** system call.
32084 */
32085 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
32086   int i = -1;
32087 
32088   UNUSED_PARAMETER(p);
32089   if( zName ){
32090     for(i=0; i<ArraySize(aSyscall)-1; i++){
32091       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
32092     }
32093   }
32094   for(i++; i<ArraySize(aSyscall); i++){
32095     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
32096   }
32097   return 0;
32098 }
32099 
32100 #ifdef SQLITE_WIN32_MALLOC
32101 /*
32102 ** If a Win32 native heap has been configured, this function will attempt to
32103 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
32104 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
32105 ** "pnLargest" argument, if non-zero, will be used to return the size of the
32106 ** largest committed free block in the heap, in bytes.
32107 */
32108 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
32109   int rc = SQLITE_OK;
32110   UINT nLargest = 0;
32111   HANDLE hHeap;
32112 
32113   winMemAssertMagic();
32114   hHeap = winMemGetHeap();
32115   assert( hHeap!=0 );
32116   assert( hHeap!=INVALID_HANDLE_VALUE );
32117 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32118   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32119 #endif
32120 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32121   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
32122     DWORD lastErrno = osGetLastError();
32123     if( lastErrno==NO_ERROR ){
32124       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
32125                   (void*)hHeap);
32126       rc = SQLITE_NOMEM;
32127     }else{
32128       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
32129                   osGetLastError(), (void*)hHeap);
32130       rc = SQLITE_ERROR;
32131     }
32132   }
32133 #else
32134   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
32135               (void*)hHeap);
32136   rc = SQLITE_NOTFOUND;
32137 #endif
32138   if( pnLargest ) *pnLargest = nLargest;
32139   return rc;
32140 }
32141 
32142 /*
32143 ** If a Win32 native heap has been configured, this function will attempt to
32144 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
32145 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
32146 ** be returned and no changes will be made to the Win32 native heap.
32147 */
32148 SQLITE_API int sqlite3_win32_reset_heap(){
32149   int rc;
32150   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
32151   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
32152   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
32153   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
32154   sqlite3_mutex_enter(pMaster);
32155   sqlite3_mutex_enter(pMem);
32156   winMemAssertMagic();
32157   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
32158     /*
32159     ** At this point, there should be no outstanding memory allocations on
32160     ** the heap.  Also, since both the master and memsys locks are currently
32161     ** being held by us, no other function (i.e. from another thread) should
32162     ** be able to even access the heap.  Attempt to destroy and recreate our
32163     ** isolated Win32 native heap now.
32164     */
32165     assert( winMemGetHeap()!=NULL );
32166     assert( winMemGetOwned() );
32167     assert( sqlite3_memory_used()==0 );
32168     winMemShutdown(winMemGetDataPtr());
32169     assert( winMemGetHeap()==NULL );
32170     assert( !winMemGetOwned() );
32171     assert( sqlite3_memory_used()==0 );
32172     rc = winMemInit(winMemGetDataPtr());
32173     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
32174     assert( rc!=SQLITE_OK || winMemGetOwned() );
32175     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
32176   }else{
32177     /*
32178     ** The Win32 native heap cannot be modified because it may be in use.
32179     */
32180     rc = SQLITE_BUSY;
32181   }
32182   sqlite3_mutex_leave(pMem);
32183   sqlite3_mutex_leave(pMaster);
32184   return rc;
32185 }
32186 #endif /* SQLITE_WIN32_MALLOC */
32187 
32188 /*
32189 ** This function outputs the specified (ANSI) string to the Win32 debugger
32190 ** (if available).
32191 */
32192 
32193 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
32194   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
32195   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
32196   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
32197   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
32198 #if defined(SQLITE_WIN32_HAS_ANSI)
32199   if( nMin>0 ){
32200     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32201     memcpy(zDbgBuf, zBuf, nMin);
32202     osOutputDebugStringA(zDbgBuf);
32203   }else{
32204     osOutputDebugStringA(zBuf);
32205   }
32206 #elif defined(SQLITE_WIN32_HAS_WIDE)
32207   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32208   if ( osMultiByteToWideChar(
32209           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
32210           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
32211     return;
32212   }
32213   osOutputDebugStringW((LPCWSTR)zDbgBuf);
32214 #else
32215   if( nMin>0 ){
32216     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32217     memcpy(zDbgBuf, zBuf, nMin);
32218     fprintf(stderr, "%s", zDbgBuf);
32219   }else{
32220     fprintf(stderr, "%s", zBuf);
32221   }
32222 #endif
32223 }
32224 
32225 /*
32226 ** The following routine suspends the current thread for at least ms
32227 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
32228 */
32229 #if SQLITE_OS_WINRT
32230 static HANDLE sleepObj = NULL;
32231 #endif
32232 
32233 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
32234 #if SQLITE_OS_WINRT
32235   if ( sleepObj==NULL ){
32236     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
32237                                 SYNCHRONIZE);
32238   }
32239   assert( sleepObj!=NULL );
32240   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
32241 #else
32242   osSleep(milliseconds);
32243 #endif
32244 }
32245 
32246 /*
32247 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
32248 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
32249 **
32250 ** Here is an interesting observation:  Win95, Win98, and WinME lack
32251 ** the LockFileEx() API.  But we can still statically link against that
32252 ** API as long as we don't call it when running Win95/98/ME.  A call to
32253 ** this routine is used to determine if the host is Win95/98/ME or
32254 ** WinNT/2K/XP so that we will know whether or not we can safely call
32255 ** the LockFileEx() API.
32256 */
32257 
32258 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
32259 # define osIsNT()  (1)
32260 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
32261 # define osIsNT()  (1)
32262 #elif !defined(SQLITE_WIN32_HAS_WIDE)
32263 # define osIsNT()  (0)
32264 #else
32265   static int osIsNT(void){
32266     if( sqlite3_os_type==0 ){
32267 #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
32268       OSVERSIONINFOW sInfo;
32269       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32270       osGetVersionExW(&sInfo);
32271 #else
32272       OSVERSIONINFOA sInfo;
32273       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32274       osGetVersionExA(&sInfo);
32275 #endif
32276       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
32277     }
32278     return sqlite3_os_type==2;
32279   }
32280 #endif
32281 
32282 #ifdef SQLITE_WIN32_MALLOC
32283 /*
32284 ** Allocate nBytes of memory.
32285 */
32286 static void *winMemMalloc(int nBytes){
32287   HANDLE hHeap;
32288   void *p;
32289 
32290   winMemAssertMagic();
32291   hHeap = winMemGetHeap();
32292   assert( hHeap!=0 );
32293   assert( hHeap!=INVALID_HANDLE_VALUE );
32294 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32295   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32296 #endif
32297   assert( nBytes>=0 );
32298   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32299   if( !p ){
32300     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
32301                 nBytes, osGetLastError(), (void*)hHeap);
32302   }
32303   return p;
32304 }
32305 
32306 /*
32307 ** Free memory.
32308 */
32309 static void winMemFree(void *pPrior){
32310   HANDLE hHeap;
32311 
32312   winMemAssertMagic();
32313   hHeap = winMemGetHeap();
32314   assert( hHeap!=0 );
32315   assert( hHeap!=INVALID_HANDLE_VALUE );
32316 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32317   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32318 #endif
32319   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
32320   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
32321     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
32322                 pPrior, osGetLastError(), (void*)hHeap);
32323   }
32324 }
32325 
32326 /*
32327 ** Change the size of an existing memory allocation
32328 */
32329 static void *winMemRealloc(void *pPrior, int nBytes){
32330   HANDLE hHeap;
32331   void *p;
32332 
32333   winMemAssertMagic();
32334   hHeap = winMemGetHeap();
32335   assert( hHeap!=0 );
32336   assert( hHeap!=INVALID_HANDLE_VALUE );
32337 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32338   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32339 #endif
32340   assert( nBytes>=0 );
32341   if( !pPrior ){
32342     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32343   }else{
32344     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
32345   }
32346   if( !p ){
32347     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
32348                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
32349                 (void*)hHeap);
32350   }
32351   return p;
32352 }
32353 
32354 /*
32355 ** Return the size of an outstanding allocation, in bytes.
32356 */
32357 static int winMemSize(void *p){
32358   HANDLE hHeap;
32359   SIZE_T n;
32360 
32361   winMemAssertMagic();
32362   hHeap = winMemGetHeap();
32363   assert( hHeap!=0 );
32364   assert( hHeap!=INVALID_HANDLE_VALUE );
32365 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32366   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
32367 #endif
32368   if( !p ) return 0;
32369   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
32370   if( n==(SIZE_T)-1 ){
32371     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
32372                 p, osGetLastError(), (void*)hHeap);
32373     return 0;
32374   }
32375   return (int)n;
32376 }
32377 
32378 /*
32379 ** Round up a request size to the next valid allocation size.
32380 */
32381 static int winMemRoundup(int n){
32382   return n;
32383 }
32384 
32385 /*
32386 ** Initialize this module.
32387 */
32388 static int winMemInit(void *pAppData){
32389   winMemData *pWinMemData = (winMemData *)pAppData;
32390 
32391   if( !pWinMemData ) return SQLITE_ERROR;
32392   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
32393   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
32394 
32395 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
32396   if( !pWinMemData->hHeap ){
32397     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
32398     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
32399     if( dwMaximumSize==0 ){
32400       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
32401     }else if( dwInitialSize>dwMaximumSize ){
32402       dwInitialSize = dwMaximumSize;
32403     }
32404     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
32405                                       dwInitialSize, dwMaximumSize);
32406     if( !pWinMemData->hHeap ){
32407       sqlite3_log(SQLITE_NOMEM,
32408           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
32409           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
32410           dwMaximumSize);
32411       return SQLITE_NOMEM;
32412     }
32413     pWinMemData->bOwned = TRUE;
32414     assert( pWinMemData->bOwned );
32415   }
32416 #else
32417   pWinMemData->hHeap = osGetProcessHeap();
32418   if( !pWinMemData->hHeap ){
32419     sqlite3_log(SQLITE_NOMEM,
32420         "failed to GetProcessHeap (%lu)", osGetLastError());
32421     return SQLITE_NOMEM;
32422   }
32423   pWinMemData->bOwned = FALSE;
32424   assert( !pWinMemData->bOwned );
32425 #endif
32426   assert( pWinMemData->hHeap!=0 );
32427   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32428 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32429   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32430 #endif
32431   return SQLITE_OK;
32432 }
32433 
32434 /*
32435 ** Deinitialize this module.
32436 */
32437 static void winMemShutdown(void *pAppData){
32438   winMemData *pWinMemData = (winMemData *)pAppData;
32439 
32440   if( !pWinMemData ) return;
32441   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
32442   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
32443 
32444   if( pWinMemData->hHeap ){
32445     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32446 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32447     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32448 #endif
32449     if( pWinMemData->bOwned ){
32450       if( !osHeapDestroy(pWinMemData->hHeap) ){
32451         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
32452                     osGetLastError(), (void*)pWinMemData->hHeap);
32453       }
32454       pWinMemData->bOwned = FALSE;
32455     }
32456     pWinMemData->hHeap = NULL;
32457   }
32458 }
32459 
32460 /*
32461 ** Populate the low-level memory allocation function pointers in
32462 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
32463 ** arguments specify the block of memory to manage.
32464 **
32465 ** This routine is only called by sqlite3_config(), and therefore
32466 ** is not required to be threadsafe (it is not).
32467 */
32468 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
32469   static const sqlite3_mem_methods winMemMethods = {
32470     winMemMalloc,
32471     winMemFree,
32472     winMemRealloc,
32473     winMemSize,
32474     winMemRoundup,
32475     winMemInit,
32476     winMemShutdown,
32477     &win_mem_data
32478   };
32479   return &winMemMethods;
32480 }
32481 
32482 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
32483   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
32484 }
32485 #endif /* SQLITE_WIN32_MALLOC */
32486 
32487 /*
32488 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
32489 **
32490 ** Space to hold the returned string is obtained from malloc.
32491 */
32492 static LPWSTR winUtf8ToUnicode(const char *zFilename){
32493   int nChar;
32494   LPWSTR zWideFilename;
32495 
32496   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
32497   if( nChar==0 ){
32498     return 0;
32499   }
32500   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
32501   if( zWideFilename==0 ){
32502     return 0;
32503   }
32504   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
32505                                 nChar);
32506   if( nChar==0 ){
32507     sqlite3_free(zWideFilename);
32508     zWideFilename = 0;
32509   }
32510   return zWideFilename;
32511 }
32512 
32513 /*
32514 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
32515 ** obtained from sqlite3_malloc().
32516 */
32517 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
32518   int nByte;
32519   char *zFilename;
32520 
32521   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32522   if( nByte == 0 ){
32523     return 0;
32524   }
32525   zFilename = sqlite3MallocZero( nByte );
32526   if( zFilename==0 ){
32527     return 0;
32528   }
32529   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32530                                 0, 0);
32531   if( nByte == 0 ){
32532     sqlite3_free(zFilename);
32533     zFilename = 0;
32534   }
32535   return zFilename;
32536 }
32537 
32538 /*
32539 ** Convert an ANSI string to Microsoft Unicode, based on the
32540 ** current codepage settings for file apis.
32541 ** 
32542 ** Space to hold the returned string is obtained
32543 ** from sqlite3_malloc.
32544 */
32545 static LPWSTR winMbcsToUnicode(const char *zFilename){
32546   int nByte;
32547   LPWSTR zMbcsFilename;
32548   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32549 
32550   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
32551                                 0)*sizeof(WCHAR);
32552   if( nByte==0 ){
32553     return 0;
32554   }
32555   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
32556   if( zMbcsFilename==0 ){
32557     return 0;
32558   }
32559   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
32560                                 nByte);
32561   if( nByte==0 ){
32562     sqlite3_free(zMbcsFilename);
32563     zMbcsFilename = 0;
32564   }
32565   return zMbcsFilename;
32566 }
32567 
32568 /*
32569 ** Convert Microsoft Unicode to multi-byte character string, based on the
32570 ** user's ANSI codepage.
32571 **
32572 ** Space to hold the returned string is obtained from
32573 ** sqlite3_malloc().
32574 */
32575 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
32576   int nByte;
32577   char *zFilename;
32578   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32579 
32580   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32581   if( nByte == 0 ){
32582     return 0;
32583   }
32584   zFilename = sqlite3MallocZero( nByte );
32585   if( zFilename==0 ){
32586     return 0;
32587   }
32588   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
32589                                 nByte, 0, 0);
32590   if( nByte == 0 ){
32591     sqlite3_free(zFilename);
32592     zFilename = 0;
32593   }
32594   return zFilename;
32595 }
32596 
32597 /*
32598 ** Convert multibyte character string to UTF-8.  Space to hold the
32599 ** returned string is obtained from sqlite3_malloc().
32600 */
32601 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32602   char *zFilenameUtf8;
32603   LPWSTR zTmpWide;
32604 
32605   zTmpWide = winMbcsToUnicode(zFilename);
32606   if( zTmpWide==0 ){
32607     return 0;
32608   }
32609   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
32610   sqlite3_free(zTmpWide);
32611   return zFilenameUtf8;
32612 }
32613 
32614 /*
32615 ** Convert UTF-8 to multibyte character string.  Space to hold the 
32616 ** returned string is obtained from sqlite3_malloc().
32617 */
32618 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32619   char *zFilenameMbcs;
32620   LPWSTR zTmpWide;
32621 
32622   zTmpWide = winUtf8ToUnicode(zFilename);
32623   if( zTmpWide==0 ){
32624     return 0;
32625   }
32626   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
32627   sqlite3_free(zTmpWide);
32628   return zFilenameMbcs;
32629 }
32630 
32631 /*
32632 ** This function sets the data directory or the temporary directory based on
32633 ** the provided arguments.  The type argument must be 1 in order to set the
32634 ** data directory or 2 in order to set the temporary directory.  The zValue
32635 ** argument is the name of the directory to use.  The return value will be
32636 ** SQLITE_OK if successful.
32637 */
32638 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
32639   char **ppDirectory = 0;
32640 #ifndef SQLITE_OMIT_AUTOINIT
32641   int rc = sqlite3_initialize();
32642   if( rc ) return rc;
32643 #endif
32644   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
32645     ppDirectory = &sqlite3_data_directory;
32646   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
32647     ppDirectory = &sqlite3_temp_directory;
32648   }
32649   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
32650           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32651   );
32652   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
32653   if( ppDirectory ){
32654     char *zValueUtf8 = 0;
32655     if( zValue && zValue[0] ){
32656       zValueUtf8 = winUnicodeToUtf8(zValue);
32657       if ( zValueUtf8==0 ){
32658         return SQLITE_NOMEM;
32659       }
32660     }
32661     sqlite3_free(*ppDirectory);
32662     *ppDirectory = zValueUtf8;
32663     return SQLITE_OK;
32664   }
32665   return SQLITE_ERROR;
32666 }
32667 
32668 /*
32669 ** The return value of winGetLastErrorMsg
32670 ** is zero if the error message fits in the buffer, or non-zero
32671 ** otherwise (if the message was truncated).
32672 */
32673 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
32674   /* FormatMessage returns 0 on failure.  Otherwise it
32675   ** returns the number of TCHARs written to the output
32676   ** buffer, excluding the terminating null char.
32677   */
32678   DWORD dwLen = 0;
32679   char *zOut = 0;
32680 
32681   if( osIsNT() ){
32682 #if SQLITE_OS_WINRT
32683     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
32684     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
32685                              FORMAT_MESSAGE_IGNORE_INSERTS,
32686                              NULL,
32687                              lastErrno,
32688                              0,
32689                              zTempWide,
32690                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
32691                              0);
32692 #else
32693     LPWSTR zTempWide = NULL;
32694     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32695                              FORMAT_MESSAGE_FROM_SYSTEM |
32696                              FORMAT_MESSAGE_IGNORE_INSERTS,
32697                              NULL,
32698                              lastErrno,
32699                              0,
32700                              (LPWSTR) &zTempWide,
32701                              0,
32702                              0);
32703 #endif
32704     if( dwLen > 0 ){
32705       /* allocate a buffer and convert to UTF8 */
32706       sqlite3BeginBenignMalloc();
32707       zOut = winUnicodeToUtf8(zTempWide);
32708       sqlite3EndBenignMalloc();
32709 #if !SQLITE_OS_WINRT
32710       /* free the system buffer allocated by FormatMessage */
32711       osLocalFree(zTempWide);
32712 #endif
32713     }
32714   }
32715 #ifdef SQLITE_WIN32_HAS_ANSI
32716   else{
32717     char *zTemp = NULL;
32718     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32719                              FORMAT_MESSAGE_FROM_SYSTEM |
32720                              FORMAT_MESSAGE_IGNORE_INSERTS,
32721                              NULL,
32722                              lastErrno,
32723                              0,
32724                              (LPSTR) &zTemp,
32725                              0,
32726                              0);
32727     if( dwLen > 0 ){
32728       /* allocate a buffer and convert to UTF8 */
32729       sqlite3BeginBenignMalloc();
32730       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32731       sqlite3EndBenignMalloc();
32732       /* free the system buffer allocated by FormatMessage */
32733       osLocalFree(zTemp);
32734     }
32735   }
32736 #endif
32737   if( 0 == dwLen ){
32738     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
32739   }else{
32740     /* copy a maximum of nBuf chars to output buffer */
32741     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32742     /* free the UTF8 buffer */
32743     sqlite3_free(zOut);
32744   }
32745   return 0;
32746 }
32747 
32748 /*
32749 **
32750 ** This function - winLogErrorAtLine() - is only ever called via the macro
32751 ** winLogError().
32752 **
32753 ** This routine is invoked after an error occurs in an OS function.
32754 ** It logs a message using sqlite3_log() containing the current value of
32755 ** error code and, if possible, the human-readable equivalent from 
32756 ** FormatMessage.
32757 **
32758 ** The first argument passed to the macro should be the error code that
32759 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
32760 ** The two subsequent arguments should be the name of the OS function that
32761 ** failed and the associated file-system path, if any.
32762 */
32763 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
32764 static int winLogErrorAtLine(
32765   int errcode,                    /* SQLite error code */
32766   DWORD lastErrno,                /* Win32 last error */
32767   const char *zFunc,              /* Name of OS function that failed */
32768   const char *zPath,              /* File path associated with error */
32769   int iLine                       /* Source line number where error occurred */
32770 ){
32771   char zMsg[500];                 /* Human readable error text */
32772   int i;                          /* Loop counter */
32773 
32774   zMsg[0] = 0;
32775   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
32776   assert( errcode!=SQLITE_OK );
32777   if( zPath==0 ) zPath = "";
32778   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32779   zMsg[i] = 0;
32780   sqlite3_log(errcode,
32781       "os_win.c:%d: (%lu) %s(%s) - %s",
32782       iLine, lastErrno, zFunc, zPath, zMsg
32783   );
32784 
32785   return errcode;
32786 }
32787 
32788 /*
32789 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32790 ** will be retried following a locking error - probably caused by 
32791 ** antivirus software.  Also the initial delay before the first retry.
32792 ** The delay increases linearly with each retry.
32793 */
32794 #ifndef SQLITE_WIN32_IOERR_RETRY
32795 # define SQLITE_WIN32_IOERR_RETRY 10
32796 #endif
32797 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32798 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32799 #endif
32800 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32801 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32802 
32803 /*
32804 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
32805 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
32806 ** to give up with an error.
32807 */
32808 static int winRetryIoerr(int *pnRetry, DWORD *pError){
32809   DWORD e = osGetLastError();
32810   if( *pnRetry>=winIoerrRetry ){
32811     if( pError ){
32812       *pError = e;
32813     }
32814     return 0;
32815   }
32816   if( e==ERROR_ACCESS_DENIED ||
32817       e==ERROR_LOCK_VIOLATION ||
32818       e==ERROR_SHARING_VIOLATION ){
32819     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
32820     ++*pnRetry;
32821     return 1;
32822   }
32823   if( pError ){
32824     *pError = e;
32825   }
32826   return 0;
32827 }
32828 
32829 /*
32830 ** Log a I/O error retry episode.
32831 */
32832 static void winLogIoerr(int nRetry){
32833   if( nRetry ){
32834     sqlite3_log(SQLITE_IOERR, 
32835       "delayed %dms for lock/sharing conflict",
32836       winIoerrRetryDelay*nRetry*(nRetry+1)/2
32837     );
32838   }
32839 }
32840 
32841 #if SQLITE_OS_WINCE
32842 /*************************************************************************
32843 ** This section contains code for WinCE only.
32844 */
32845 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
32846 /*
32847 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
32848 ** create a substitute.
32849 */
32850 /* #include <time.h> */
32851 struct tm *__cdecl localtime(const time_t *t)
32852 {
32853   static struct tm y;
32854   FILETIME uTm, lTm;
32855   SYSTEMTIME pTm;
32856   sqlite3_int64 t64;
32857   t64 = *t;
32858   t64 = (t64 + 11644473600)*10000000;
32859   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32860   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32861   osFileTimeToLocalFileTime(&uTm,&lTm);
32862   osFileTimeToSystemTime(&lTm,&pTm);
32863   y.tm_year = pTm.wYear - 1900;
32864   y.tm_mon = pTm.wMonth - 1;
32865   y.tm_wday = pTm.wDayOfWeek;
32866   y.tm_mday = pTm.wDay;
32867   y.tm_hour = pTm.wHour;
32868   y.tm_min = pTm.wMinute;
32869   y.tm_sec = pTm.wSecond;
32870   return &y;
32871 }
32872 #endif
32873 
32874 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32875 
32876 /*
32877 ** Acquire a lock on the handle h
32878 */
32879 static void winceMutexAcquire(HANDLE h){
32880    DWORD dwErr;
32881    do {
32882      dwErr = osWaitForSingleObject(h, INFINITE);
32883    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32884 }
32885 /*
32886 ** Release a lock acquired by winceMutexAcquire()
32887 */
32888 #define winceMutexRelease(h) ReleaseMutex(h)
32889 
32890 /*
32891 ** Create the mutex and shared memory used for locking in the file
32892 ** descriptor pFile
32893 */
32894 static int winceCreateLock(const char *zFilename, winFile *pFile){
32895   LPWSTR zTok;
32896   LPWSTR zName;
32897   DWORD lastErrno;
32898   BOOL bLogged = FALSE;
32899   BOOL bInit = TRUE;
32900 
32901   zName = winUtf8ToUnicode(zFilename);
32902   if( zName==0 ){
32903     /* out of memory */
32904     return SQLITE_IOERR_NOMEM;
32905   }
32906 
32907   /* Initialize the local lockdata */
32908   memset(&pFile->local, 0, sizeof(pFile->local));
32909 
32910   /* Replace the backslashes from the filename and lowercase it
32911   ** to derive a mutex name. */
32912   zTok = osCharLowerW(zName);
32913   for (;*zTok;zTok++){
32914     if (*zTok == '\\') *zTok = '_';
32915   }
32916 
32917   /* Create/open the named mutex */
32918   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
32919   if (!pFile->hMutex){
32920     pFile->lastErrno = osGetLastError();
32921     sqlite3_free(zName);
32922     return winLogError(SQLITE_IOERR, pFile->lastErrno,
32923                        "winceCreateLock1", zFilename);
32924   }
32925 
32926   /* Acquire the mutex before continuing */
32927   winceMutexAcquire(pFile->hMutex);
32928   
32929   /* Since the names of named mutexes, semaphores, file mappings etc are 
32930   ** case-sensitive, take advantage of that by uppercasing the mutex name
32931   ** and using that as the shared filemapping name.
32932   */
32933   osCharUpperW(zName);
32934   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32935                                         PAGE_READWRITE, 0, sizeof(winceLock),
32936                                         zName);  
32937 
32938   /* Set a flag that indicates we're the first to create the memory so it 
32939   ** must be zero-initialized */
32940   lastErrno = osGetLastError();
32941   if (lastErrno == ERROR_ALREADY_EXISTS){
32942     bInit = FALSE;
32943   }
32944 
32945   sqlite3_free(zName);
32946 
32947   /* If we succeeded in making the shared memory handle, map it. */
32948   if( pFile->hShared ){
32949     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
32950              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32951     /* If mapping failed, close the shared memory handle and erase it */
32952     if( !pFile->shared ){
32953       pFile->lastErrno = osGetLastError();
32954       winLogError(SQLITE_IOERR, pFile->lastErrno,
32955                   "winceCreateLock2", zFilename);
32956       bLogged = TRUE;
32957       osCloseHandle(pFile->hShared);
32958       pFile->hShared = NULL;
32959     }
32960   }
32961 
32962   /* If shared memory could not be created, then close the mutex and fail */
32963   if( pFile->hShared==NULL ){
32964     if( !bLogged ){
32965       pFile->lastErrno = lastErrno;
32966       winLogError(SQLITE_IOERR, pFile->lastErrno,
32967                   "winceCreateLock3", zFilename);
32968       bLogged = TRUE;
32969     }
32970     winceMutexRelease(pFile->hMutex);
32971     osCloseHandle(pFile->hMutex);
32972     pFile->hMutex = NULL;
32973     return SQLITE_IOERR;
32974   }
32975   
32976   /* Initialize the shared memory if we're supposed to */
32977   if( bInit ){
32978     memset(pFile->shared, 0, sizeof(winceLock));
32979   }
32980 
32981   winceMutexRelease(pFile->hMutex);
32982   return SQLITE_OK;
32983 }
32984 
32985 /*
32986 ** Destroy the part of winFile that deals with wince locks
32987 */
32988 static void winceDestroyLock(winFile *pFile){
32989   if (pFile->hMutex){
32990     /* Acquire the mutex */
32991     winceMutexAcquire(pFile->hMutex);
32992 
32993     /* The following blocks should probably assert in debug mode, but they
32994        are to cleanup in case any locks remained open */
32995     if (pFile->local.nReaders){
32996       pFile->shared->nReaders --;
32997     }
32998     if (pFile->local.bReserved){
32999       pFile->shared->bReserved = FALSE;
33000     }
33001     if (pFile->local.bPending){
33002       pFile->shared->bPending = FALSE;
33003     }
33004     if (pFile->local.bExclusive){
33005       pFile->shared->bExclusive = FALSE;
33006     }
33007 
33008     /* De-reference and close our copy of the shared memory handle */
33009     osUnmapViewOfFile(pFile->shared);
33010     osCloseHandle(pFile->hShared);
33011 
33012     /* Done with the mutex */
33013     winceMutexRelease(pFile->hMutex);    
33014     osCloseHandle(pFile->hMutex);
33015     pFile->hMutex = NULL;
33016   }
33017 }
33018 
33019 /* 
33020 ** An implementation of the LockFile() API of Windows for CE
33021 */
33022 static BOOL winceLockFile(
33023   LPHANDLE phFile,
33024   DWORD dwFileOffsetLow,
33025   DWORD dwFileOffsetHigh,
33026   DWORD nNumberOfBytesToLockLow,
33027   DWORD nNumberOfBytesToLockHigh
33028 ){
33029   winFile *pFile = HANDLE_TO_WINFILE(phFile);
33030   BOOL bReturn = FALSE;
33031 
33032   UNUSED_PARAMETER(dwFileOffsetHigh);
33033   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33034 
33035   if (!pFile->hMutex) return TRUE;
33036   winceMutexAcquire(pFile->hMutex);
33037 
33038   /* Wanting an exclusive lock? */
33039   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33040        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33041     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33042        pFile->shared->bExclusive = TRUE;
33043        pFile->local.bExclusive = TRUE;
33044        bReturn = TRUE;
33045     }
33046   }
33047 
33048   /* Want a read-only lock? */
33049   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33050            nNumberOfBytesToLockLow == 1){
33051     if (pFile->shared->bExclusive == 0){
33052       pFile->local.nReaders ++;
33053       if (pFile->local.nReaders == 1){
33054         pFile->shared->nReaders ++;
33055       }
33056       bReturn = TRUE;
33057     }
33058   }
33059 
33060   /* Want a pending lock? */
33061   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33062            && nNumberOfBytesToLockLow == 1){
33063     /* If no pending lock has been acquired, then acquire it */
33064     if (pFile->shared->bPending == 0) {
33065       pFile->shared->bPending = TRUE;
33066       pFile->local.bPending = TRUE;
33067       bReturn = TRUE;
33068     }
33069   }
33070 
33071   /* Want a reserved lock? */
33072   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33073            && nNumberOfBytesToLockLow == 1){
33074     if (pFile->shared->bReserved == 0) {
33075       pFile->shared->bReserved = TRUE;
33076       pFile->local.bReserved = TRUE;
33077       bReturn = TRUE;
33078     }
33079   }
33080 
33081   winceMutexRelease(pFile->hMutex);
33082   return bReturn;
33083 }
33084 
33085 /*
33086 ** An implementation of the UnlockFile API of Windows for CE
33087 */
33088 static BOOL winceUnlockFile(
33089   LPHANDLE phFile,
33090   DWORD dwFileOffsetLow,
33091   DWORD dwFileOffsetHigh,
33092   DWORD nNumberOfBytesToUnlockLow,
33093   DWORD nNumberOfBytesToUnlockHigh
33094 ){
33095   winFile *pFile = HANDLE_TO_WINFILE(phFile);
33096   BOOL bReturn = FALSE;
33097 
33098   UNUSED_PARAMETER(dwFileOffsetHigh);
33099   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33100 
33101   if (!pFile->hMutex) return TRUE;
33102   winceMutexAcquire(pFile->hMutex);
33103 
33104   /* Releasing a reader lock or an exclusive lock */
33105   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33106     /* Did we have an exclusive lock? */
33107     if (pFile->local.bExclusive){
33108       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33109       pFile->local.bExclusive = FALSE;
33110       pFile->shared->bExclusive = FALSE;
33111       bReturn = TRUE;
33112     }
33113 
33114     /* Did we just have a reader lock? */
33115     else if (pFile->local.nReaders){
33116       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
33117              || nNumberOfBytesToUnlockLow == 1);
33118       pFile->local.nReaders --;
33119       if (pFile->local.nReaders == 0)
33120       {
33121         pFile->shared->nReaders --;
33122       }
33123       bReturn = TRUE;
33124     }
33125   }
33126 
33127   /* Releasing a pending lock */
33128   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33129            && nNumberOfBytesToUnlockLow == 1){
33130     if (pFile->local.bPending){
33131       pFile->local.bPending = FALSE;
33132       pFile->shared->bPending = FALSE;
33133       bReturn = TRUE;
33134     }
33135   }
33136   /* Releasing a reserved lock */
33137   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33138            && nNumberOfBytesToUnlockLow == 1){
33139     if (pFile->local.bReserved) {
33140       pFile->local.bReserved = FALSE;
33141       pFile->shared->bReserved = FALSE;
33142       bReturn = TRUE;
33143     }
33144   }
33145 
33146   winceMutexRelease(pFile->hMutex);
33147   return bReturn;
33148 }
33149 /*
33150 ** End of the special code for wince
33151 *****************************************************************************/
33152 #endif /* SQLITE_OS_WINCE */
33153 
33154 /*
33155 ** Lock a file region.
33156 */
33157 static BOOL winLockFile(
33158   LPHANDLE phFile,
33159   DWORD flags,
33160   DWORD offsetLow,
33161   DWORD offsetHigh,
33162   DWORD numBytesLow,
33163   DWORD numBytesHigh
33164 ){
33165 #if SQLITE_OS_WINCE
33166   /*
33167   ** NOTE: Windows CE is handled differently here due its lack of the Win32
33168   **       API LockFile.
33169   */
33170   return winceLockFile(phFile, offsetLow, offsetHigh,
33171                        numBytesLow, numBytesHigh);
33172 #else
33173   if( osIsNT() ){
33174     OVERLAPPED ovlp;
33175     memset(&ovlp, 0, sizeof(OVERLAPPED));
33176     ovlp.Offset = offsetLow;
33177     ovlp.OffsetHigh = offsetHigh;
33178     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
33179   }else{
33180     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33181                       numBytesHigh);
33182   }
33183 #endif
33184 }
33185 
33186 /*
33187 ** Unlock a file region.
33188  */
33189 static BOOL winUnlockFile(
33190   LPHANDLE phFile,
33191   DWORD offsetLow,
33192   DWORD offsetHigh,
33193   DWORD numBytesLow,
33194   DWORD numBytesHigh
33195 ){
33196 #if SQLITE_OS_WINCE
33197   /*
33198   ** NOTE: Windows CE is handled differently here due its lack of the Win32
33199   **       API UnlockFile.
33200   */
33201   return winceUnlockFile(phFile, offsetLow, offsetHigh,
33202                          numBytesLow, numBytesHigh);
33203 #else
33204   if( osIsNT() ){
33205     OVERLAPPED ovlp;
33206     memset(&ovlp, 0, sizeof(OVERLAPPED));
33207     ovlp.Offset = offsetLow;
33208     ovlp.OffsetHigh = offsetHigh;
33209     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
33210   }else{
33211     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33212                         numBytesHigh);
33213   }
33214 #endif
33215 }
33216 
33217 /*****************************************************************************
33218 ** The next group of routines implement the I/O methods specified
33219 ** by the sqlite3_io_methods object.
33220 ******************************************************************************/
33221 
33222 /*
33223 ** Some Microsoft compilers lack this definition.
33224 */
33225 #ifndef INVALID_SET_FILE_POINTER
33226 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
33227 #endif
33228 
33229 /*
33230 ** Move the current position of the file handle passed as the first 
33231 ** argument to offset iOffset within the file. If successful, return 0. 
33232 ** Otherwise, set pFile->lastErrno and return non-zero.
33233 */
33234 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
33235 #if !SQLITE_OS_WINRT
33236   LONG upperBits;                 /* Most sig. 32 bits of new offset */
33237   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
33238   DWORD dwRet;                    /* Value returned by SetFilePointer() */
33239   DWORD lastErrno;                /* Value returned by GetLastError() */
33240 
33241   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
33242 
33243   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
33244   lowerBits = (LONG)(iOffset & 0xffffffff);
33245 
33246   /* API oddity: If successful, SetFilePointer() returns a dword 
33247   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
33248   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
33249   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
33250   ** whether an error has actually occurred, it is also necessary to call 
33251   ** GetLastError().
33252   */
33253   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
33254 
33255   if( (dwRet==INVALID_SET_FILE_POINTER
33256       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
33257     pFile->lastErrno = lastErrno;
33258     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33259                 "winSeekFile", pFile->zPath);
33260     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33261     return 1;
33262   }
33263 
33264   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33265   return 0;
33266 #else
33267   /*
33268   ** Same as above, except that this implementation works for WinRT.
33269   */
33270 
33271   LARGE_INTEGER x;                /* The new offset */
33272   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
33273 
33274   x.QuadPart = iOffset;
33275   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
33276 
33277   if(!bRet){
33278     pFile->lastErrno = osGetLastError();
33279     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33280                 "winSeekFile", pFile->zPath);
33281     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33282     return 1;
33283   }
33284 
33285   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33286   return 0;
33287 #endif
33288 }
33289 
33290 #if SQLITE_MAX_MMAP_SIZE>0
33291 /* Forward references to VFS helper methods used for memory mapped files */
33292 static int winMapfile(winFile*, sqlite3_int64);
33293 static int winUnmapfile(winFile*);
33294 #endif
33295 
33296 /*
33297 ** Close a file.
33298 **
33299 ** It is reported that an attempt to close a handle might sometimes
33300 ** fail.  This is a very unreasonable result, but Windows is notorious
33301 ** for being unreasonable so I do not doubt that it might happen.  If
33302 ** the close fails, we pause for 100 milliseconds and try again.  As
33303 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
33304 ** giving up and returning an error.
33305 */
33306 #define MX_CLOSE_ATTEMPT 3
33307 static int winClose(sqlite3_file *id){
33308   int rc, cnt = 0;
33309   winFile *pFile = (winFile*)id;
33310 
33311   assert( id!=0 );
33312 #ifndef SQLITE_OMIT_WAL
33313   assert( pFile->pShm==0 );
33314 #endif
33315   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
33316   OSTRACE(("CLOSE file=%p\n", pFile->h));
33317 
33318 #if SQLITE_MAX_MMAP_SIZE>0
33319   winUnmapfile(pFile);
33320 #endif
33321 
33322   do{
33323     rc = osCloseHandle(pFile->h);
33324     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
33325   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
33326 #if SQLITE_OS_WINCE
33327 #define WINCE_DELETION_ATTEMPTS 3
33328   winceDestroyLock(pFile);
33329   if( pFile->zDeleteOnClose ){
33330     int cnt = 0;
33331     while(
33332            osDeleteFileW(pFile->zDeleteOnClose)==0
33333         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
33334         && cnt++ < WINCE_DELETION_ATTEMPTS
33335     ){
33336        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
33337     }
33338     sqlite3_free(pFile->zDeleteOnClose);
33339   }
33340 #endif
33341   if( rc ){
33342     pFile->h = NULL;
33343   }
33344   OpenCounter(-1);
33345   OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
33346   return rc ? SQLITE_OK
33347             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
33348                           "winClose", pFile->zPath);
33349 }
33350 
33351 /*
33352 ** Read data from a file into a buffer.  Return SQLITE_OK if all
33353 ** bytes were read successfully and SQLITE_IOERR if anything goes
33354 ** wrong.
33355 */
33356 static int winRead(
33357   sqlite3_file *id,          /* File to read from */
33358   void *pBuf,                /* Write content into this buffer */
33359   int amt,                   /* Number of bytes to read */
33360   sqlite3_int64 offset       /* Begin reading at this offset */
33361 ){
33362 #if !SQLITE_OS_WINCE
33363   OVERLAPPED overlapped;          /* The offset for ReadFile. */
33364 #endif
33365   winFile *pFile = (winFile*)id;  /* file handle */
33366   DWORD nRead;                    /* Number of bytes actually read from file */
33367   int nRetry = 0;                 /* Number of retrys */
33368 
33369   assert( id!=0 );
33370   assert( amt>0 );
33371   assert( offset>=0 );
33372   SimulateIOError(return SQLITE_IOERR_READ);
33373   OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
33374            pFile->h, pBuf, amt, offset, pFile->locktype));
33375 
33376 #if SQLITE_MAX_MMAP_SIZE>0
33377   /* Deal with as much of this read request as possible by transfering
33378   ** data from the memory mapping using memcpy().  */
33379   if( offset<pFile->mmapSize ){
33380     if( offset+amt <= pFile->mmapSize ){
33381       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
33382       OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
33383       return SQLITE_OK;
33384     }else{
33385       int nCopy = (int)(pFile->mmapSize - offset);
33386       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
33387       pBuf = &((u8 *)pBuf)[nCopy];
33388       amt -= nCopy;
33389       offset += nCopy;
33390     }
33391   }
33392 #endif
33393 
33394 #if SQLITE_OS_WINCE
33395   if( winSeekFile(pFile, offset) ){
33396     OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
33397     return SQLITE_FULL;
33398   }
33399   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
33400 #else
33401   memset(&overlapped, 0, sizeof(OVERLAPPED));
33402   overlapped.Offset = (LONG)(offset & 0xffffffff);
33403   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33404   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
33405          osGetLastError()!=ERROR_HANDLE_EOF ){
33406 #endif
33407     DWORD lastErrno;
33408     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
33409     pFile->lastErrno = lastErrno;
33410     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
33411     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
33412                        "winRead", pFile->zPath);
33413   }
33414   winLogIoerr(nRetry);
33415   if( nRead<(DWORD)amt ){
33416     /* Unread parts of the buffer must be zero-filled */
33417     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
33418     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
33419     return SQLITE_IOERR_SHORT_READ;
33420   }
33421 
33422   OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
33423   return SQLITE_OK;
33424 }
33425 
33426 /*
33427 ** Write data from a buffer into a file.  Return SQLITE_OK on success
33428 ** or some other error code on failure.
33429 */
33430 static int winWrite(
33431   sqlite3_file *id,               /* File to write into */
33432   const void *pBuf,               /* The bytes to be written */
33433   int amt,                        /* Number of bytes to write */
33434   sqlite3_int64 offset            /* Offset into the file to begin writing at */
33435 ){
33436   int rc = 0;                     /* True if error has occurred, else false */
33437   winFile *pFile = (winFile*)id;  /* File handle */
33438   int nRetry = 0;                 /* Number of retries */
33439 
33440   assert( amt>0 );
33441   assert( pFile );
33442   SimulateIOError(return SQLITE_IOERR_WRITE);
33443   SimulateDiskfullError(return SQLITE_FULL);
33444 
33445   OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
33446            pFile->h, pBuf, amt, offset, pFile->locktype));
33447 
33448 #if SQLITE_MAX_MMAP_SIZE>0
33449   /* Deal with as much of this write request as possible by transfering
33450   ** data from the memory mapping using memcpy().  */
33451   if( offset<pFile->mmapSize ){
33452     if( offset+amt <= pFile->mmapSize ){
33453       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
33454       OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
33455       return SQLITE_OK;
33456     }else{
33457       int nCopy = (int)(pFile->mmapSize - offset);
33458       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
33459       pBuf = &((u8 *)pBuf)[nCopy];
33460       amt -= nCopy;
33461       offset += nCopy;
33462     }
33463   }
33464 #endif
33465 
33466 #if SQLITE_OS_WINCE
33467   rc = winSeekFile(pFile, offset);
33468   if( rc==0 ){
33469 #else
33470   {
33471 #endif
33472 #if !SQLITE_OS_WINCE
33473     OVERLAPPED overlapped;        /* The offset for WriteFile. */
33474 #endif
33475     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
33476     int nRem = amt;               /* Number of bytes yet to be written */
33477     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
33478     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
33479 
33480 #if !SQLITE_OS_WINCE
33481     memset(&overlapped, 0, sizeof(OVERLAPPED));
33482     overlapped.Offset = (LONG)(offset & 0xffffffff);
33483     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33484 #endif
33485 
33486     while( nRem>0 ){
33487 #if SQLITE_OS_WINCE
33488       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
33489 #else
33490       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
33491 #endif
33492         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
33493         break;
33494       }
33495       assert( nWrite==0 || nWrite<=(DWORD)nRem );
33496       if( nWrite==0 || nWrite>(DWORD)nRem ){
33497         lastErrno = osGetLastError();
33498         break;
33499       }
33500 #if !SQLITE_OS_WINCE
33501       offset += nWrite;
33502       overlapped.Offset = (LONG)(offset & 0xffffffff);
33503       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33504 #endif
33505       aRem += nWrite;
33506       nRem -= nWrite;
33507     }
33508     if( nRem>0 ){
33509       pFile->lastErrno = lastErrno;
33510       rc = 1;
33511     }
33512   }
33513 
33514   if( rc ){
33515     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33516        || ( pFile->lastErrno==ERROR_DISK_FULL )){
33517       OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
33518       return winLogError(SQLITE_FULL, pFile->lastErrno,
33519                          "winWrite1", pFile->zPath);
33520     }
33521     OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
33522     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33523                        "winWrite2", pFile->zPath);
33524   }else{
33525     winLogIoerr(nRetry);
33526   }
33527   OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
33528   return SQLITE_OK;
33529 }
33530 
33531 /*
33532 ** Truncate an open file to a specified size
33533 */
33534 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33535   winFile *pFile = (winFile*)id;  /* File handle object */
33536   int rc = SQLITE_OK;             /* Return code for this function */
33537   DWORD lastErrno;
33538 
33539   assert( pFile );
33540   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33541   OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
33542            pFile->h, nByte, pFile->locktype));
33543 
33544   /* If the user has configured a chunk-size for this file, truncate the
33545   ** file so that it consists of an integer number of chunks (i.e. the
33546   ** actual file size after the operation may be larger than the requested
33547   ** size).
33548   */
33549   if( pFile->szChunk>0 ){
33550     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33551   }
33552 
33553   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33554   if( winSeekFile(pFile, nByte) ){
33555     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33556                      "winTruncate1", pFile->zPath);
33557   }else if( 0==osSetEndOfFile(pFile->h) &&
33558             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
33559     pFile->lastErrno = lastErrno;
33560     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33561                      "winTruncate2", pFile->zPath);
33562   }
33563 
33564 #if SQLITE_MAX_MMAP_SIZE>0
33565   /* If the file was truncated to a size smaller than the currently
33566   ** mapped region, reduce the effective mapping size as well. SQLite will
33567   ** use read() and write() to access data beyond this point from now on.
33568   */
33569   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
33570     pFile->mmapSize = nByte;
33571   }
33572 #endif
33573 
33574   OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33575   return rc;
33576 }
33577 
33578 #ifdef SQLITE_TEST
33579 /*
33580 ** Count the number of fullsyncs and normal syncs.  This is used to test
33581 ** that syncs and fullsyncs are occuring at the right times.
33582 */
33583 SQLITE_API int sqlite3_sync_count = 0;
33584 SQLITE_API int sqlite3_fullsync_count = 0;
33585 #endif
33586 
33587 /*
33588 ** Make sure all writes to a particular file are committed to disk.
33589 */
33590 static int winSync(sqlite3_file *id, int flags){
33591 #ifndef SQLITE_NO_SYNC
33592   /*
33593   ** Used only when SQLITE_NO_SYNC is not defined.
33594    */
33595   BOOL rc;
33596 #endif
33597 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33598     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33599   /*
33600   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33601   ** OSTRACE() macros.
33602    */
33603   winFile *pFile = (winFile*)id;
33604 #else
33605   UNUSED_PARAMETER(id);
33606 #endif
33607 
33608   assert( pFile );
33609   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33610   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33611       || (flags&0x0F)==SQLITE_SYNC_FULL
33612   );
33613 
33614   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33615   ** line is to test that doing so does not cause any problems.
33616   */
33617   SimulateDiskfullError( return SQLITE_FULL );
33618 
33619   OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
33620            pFile->h, flags, pFile->locktype));
33621 
33622 #ifndef SQLITE_TEST
33623   UNUSED_PARAMETER(flags);
33624 #else
33625   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33626     sqlite3_fullsync_count++;
33627   }
33628   sqlite3_sync_count++;
33629 #endif
33630 
33631   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33632   ** no-op
33633   */
33634 #ifdef SQLITE_NO_SYNC
33635   OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
33636   return SQLITE_OK;
33637 #else
33638   rc = osFlushFileBuffers(pFile->h);
33639   SimulateIOError( rc=FALSE );
33640   if( rc ){
33641     OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
33642     return SQLITE_OK;
33643   }else{
33644     pFile->lastErrno = osGetLastError();
33645     OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
33646     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33647                        "winSync", pFile->zPath);
33648   }
33649 #endif
33650 }
33651 
33652 /*
33653 ** Determine the current size of a file in bytes
33654 */
33655 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33656   winFile *pFile = (winFile*)id;
33657   int rc = SQLITE_OK;
33658 
33659   assert( id!=0 );
33660   assert( pSize!=0 );
33661   SimulateIOError(return SQLITE_IOERR_FSTAT);
33662   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
33663 
33664 #if SQLITE_OS_WINRT
33665   {
33666     FILE_STANDARD_INFO info;
33667     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
33668                                      &info, sizeof(info)) ){
33669       *pSize = info.EndOfFile.QuadPart;
33670     }else{
33671       pFile->lastErrno = osGetLastError();
33672       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33673                        "winFileSize", pFile->zPath);
33674     }
33675   }
33676 #else
33677   {
33678     DWORD upperBits;
33679     DWORD lowerBits;
33680     DWORD lastErrno;
33681 
33682     lowerBits = osGetFileSize(pFile->h, &upperBits);
33683     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33684     if(   (lowerBits == INVALID_FILE_SIZE)
33685        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
33686       pFile->lastErrno = lastErrno;
33687       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33688                        "winFileSize", pFile->zPath);
33689     }
33690   }
33691 #endif
33692   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
33693            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
33694   return rc;
33695 }
33696 
33697 /*
33698 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33699 */
33700 #ifndef LOCKFILE_FAIL_IMMEDIATELY
33701 # define LOCKFILE_FAIL_IMMEDIATELY 1
33702 #endif
33703 
33704 #ifndef LOCKFILE_EXCLUSIVE_LOCK
33705 # define LOCKFILE_EXCLUSIVE_LOCK 2
33706 #endif
33707 
33708 /*
33709 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
33710 ** When the LockFile function was used, it was always expected to fail
33711 ** immediately if the lock could not be obtained.  Also, it always expected to
33712 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
33713 ** and reflect those expectations; therefore, they should not be changed.
33714 */
33715 #ifndef SQLITE_LOCKFILE_FLAGS
33716 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
33717                                   LOCKFILE_EXCLUSIVE_LOCK)
33718 #endif
33719 
33720 /*
33721 ** Currently, SQLite never calls the LockFileEx function without wanting the
33722 ** call to fail immediately if the lock cannot be obtained.
33723 */
33724 #ifndef SQLITE_LOCKFILEEX_FLAGS
33725 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
33726 #endif
33727 
33728 /*
33729 ** Acquire a reader lock.
33730 ** Different API routines are called depending on whether or not this
33731 ** is Win9x or WinNT.
33732 */
33733 static int winGetReadLock(winFile *pFile){
33734   int res;
33735   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33736   if( osIsNT() ){
33737 #if SQLITE_OS_WINCE
33738     /*
33739     ** NOTE: Windows CE is handled differently here due its lack of the Win32
33740     **       API LockFileEx.
33741     */
33742     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
33743 #else
33744     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
33745                       SHARED_SIZE, 0);
33746 #endif
33747   }
33748 #ifdef SQLITE_WIN32_HAS_ANSI
33749   else{
33750     int lk;
33751     sqlite3_randomness(sizeof(lk), &lk);
33752     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
33753     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33754                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33755   }
33756 #endif
33757   if( res == 0 ){
33758     pFile->lastErrno = osGetLastError();
33759     /* No need to log a failure to lock */
33760   }
33761   OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33762   return res;
33763 }
33764 
33765 /*
33766 ** Undo a readlock
33767 */
33768 static int winUnlockReadLock(winFile *pFile){
33769   int res;
33770   DWORD lastErrno;
33771   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33772   if( osIsNT() ){
33773     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33774   }
33775 #ifdef SQLITE_WIN32_HAS_ANSI
33776   else{
33777     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33778   }
33779 #endif
33780   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
33781     pFile->lastErrno = lastErrno;
33782     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
33783                 "winUnlockReadLock", pFile->zPath);
33784   }
33785   OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33786   return res;
33787 }
33788 
33789 /*
33790 ** Lock the file with the lock specified by parameter locktype - one
33791 ** of the following:
33792 **
33793 **     (1) SHARED_LOCK
33794 **     (2) RESERVED_LOCK
33795 **     (3) PENDING_LOCK
33796 **     (4) EXCLUSIVE_LOCK
33797 **
33798 ** Sometimes when requesting one lock state, additional lock states
33799 ** are inserted in between.  The locking might fail on one of the later
33800 ** transitions leaving the lock state different from what it started but
33801 ** still short of its goal.  The following chart shows the allowed
33802 ** transitions and the inserted intermediate states:
33803 **
33804 **    UNLOCKED -> SHARED
33805 **    SHARED -> RESERVED
33806 **    SHARED -> (PENDING) -> EXCLUSIVE
33807 **    RESERVED -> (PENDING) -> EXCLUSIVE
33808 **    PENDING -> EXCLUSIVE
33809 **
33810 ** This routine will only increase a lock.  The winUnlock() routine
33811 ** erases all locks at once and returns us immediately to locking level 0.
33812 ** It is not possible to lower the locking level one step at a time.  You
33813 ** must go straight to locking level 0.
33814 */
33815 static int winLock(sqlite3_file *id, int locktype){
33816   int rc = SQLITE_OK;    /* Return code from subroutines */
33817   int res = 1;           /* Result of a Windows lock call */
33818   int newLocktype;       /* Set pFile->locktype to this value before exiting */
33819   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
33820   winFile *pFile = (winFile*)id;
33821   DWORD lastErrno = NO_ERROR;
33822 
33823   assert( id!=0 );
33824   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33825            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33826 
33827   /* If there is already a lock of this type or more restrictive on the
33828   ** OsFile, do nothing. Don't use the end_lock: exit path, as
33829   ** sqlite3OsEnterMutex() hasn't been called yet.
33830   */
33831   if( pFile->locktype>=locktype ){
33832     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
33833     return SQLITE_OK;
33834   }
33835 
33836   /* Make sure the locking sequence is correct
33837   */
33838   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
33839   assert( locktype!=PENDING_LOCK );
33840   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
33841 
33842   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
33843   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
33844   ** the PENDING_LOCK byte is temporary.
33845   */
33846   newLocktype = pFile->locktype;
33847   if(   (pFile->locktype==NO_LOCK)
33848      || (   (locktype==EXCLUSIVE_LOCK)
33849          && (pFile->locktype==RESERVED_LOCK))
33850   ){
33851     int cnt = 3;
33852     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33853                                          PENDING_BYTE, 0, 1, 0))==0 ){
33854       /* Try 3 times to get the pending lock.  This is needed to work
33855       ** around problems caused by indexing and/or anti-virus software on
33856       ** Windows systems.
33857       ** If you are using this code as a model for alternative VFSes, do not
33858       ** copy this retry logic.  It is a hack intended for Windows only.
33859       */
33860       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
33861                pFile->h, cnt, sqlite3ErrName(res)));
33862       if( cnt ) sqlite3_win32_sleep(1);
33863     }
33864     gotPendingLock = res;
33865     if( !res ){
33866       lastErrno = osGetLastError();
33867     }
33868   }
33869 
33870   /* Acquire a shared lock
33871   */
33872   if( locktype==SHARED_LOCK && res ){
33873     assert( pFile->locktype==NO_LOCK );
33874     res = winGetReadLock(pFile);
33875     if( res ){
33876       newLocktype = SHARED_LOCK;
33877     }else{
33878       lastErrno = osGetLastError();
33879     }
33880   }
33881 
33882   /* Acquire a RESERVED lock
33883   */
33884   if( locktype==RESERVED_LOCK && res ){
33885     assert( pFile->locktype==SHARED_LOCK );
33886     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
33887     if( res ){
33888       newLocktype = RESERVED_LOCK;
33889     }else{
33890       lastErrno = osGetLastError();
33891     }
33892   }
33893 
33894   /* Acquire a PENDING lock
33895   */
33896   if( locktype==EXCLUSIVE_LOCK && res ){
33897     newLocktype = PENDING_LOCK;
33898     gotPendingLock = 0;
33899   }
33900 
33901   /* Acquire an EXCLUSIVE lock
33902   */
33903   if( locktype==EXCLUSIVE_LOCK && res ){
33904     assert( pFile->locktype>=SHARED_LOCK );
33905     res = winUnlockReadLock(pFile);
33906     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
33907                       SHARED_SIZE, 0);
33908     if( res ){
33909       newLocktype = EXCLUSIVE_LOCK;
33910     }else{
33911       lastErrno = osGetLastError();
33912       winGetReadLock(pFile);
33913     }
33914   }
33915 
33916   /* If we are holding a PENDING lock that ought to be released, then
33917   ** release it now.
33918   */
33919   if( gotPendingLock && locktype==SHARED_LOCK ){
33920     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33921   }
33922 
33923   /* Update the state of the lock has held in the file descriptor then
33924   ** return the appropriate result code.
33925   */
33926   if( res ){
33927     rc = SQLITE_OK;
33928   }else{
33929     pFile->lastErrno = lastErrno;
33930     rc = SQLITE_BUSY;
33931     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
33932              pFile->h, locktype, newLocktype));
33933   }
33934   pFile->locktype = (u8)newLocktype;
33935   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
33936            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33937   return rc;
33938 }
33939 
33940 /*
33941 ** This routine checks if there is a RESERVED lock held on the specified
33942 ** file by this or any other process. If such a lock is held, return
33943 ** non-zero, otherwise zero.
33944 */
33945 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33946   int rc;
33947   winFile *pFile = (winFile*)id;
33948 
33949   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33950   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
33951 
33952   assert( id!=0 );
33953   if( pFile->locktype>=RESERVED_LOCK ){
33954     rc = 1;
33955     OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
33956   }else{
33957     rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
33958     if( rc ){
33959       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33960     }
33961     rc = !rc;
33962     OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
33963   }
33964   *pResOut = rc;
33965   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
33966            pFile->h, pResOut, *pResOut));
33967   return SQLITE_OK;
33968 }
33969 
33970 /*
33971 ** Lower the locking level on file descriptor id to locktype.  locktype
33972 ** must be either NO_LOCK or SHARED_LOCK.
33973 **
33974 ** If the locking level of the file descriptor is already at or below
33975 ** the requested locking level, this routine is a no-op.
33976 **
33977 ** It is not possible for this routine to fail if the second argument
33978 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
33979 ** might return SQLITE_IOERR;
33980 */
33981 static int winUnlock(sqlite3_file *id, int locktype){
33982   int type;
33983   winFile *pFile = (winFile*)id;
33984   int rc = SQLITE_OK;
33985   assert( pFile!=0 );
33986   assert( locktype<=SHARED_LOCK );
33987   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33988            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33989   type = pFile->locktype;
33990   if( type>=EXCLUSIVE_LOCK ){
33991     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33992     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
33993       /* This should never happen.  We should always be able to
33994       ** reacquire the read lock */
33995       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
33996                        "winUnlock", pFile->zPath);
33997     }
33998   }
33999   if( type>=RESERVED_LOCK ){
34000     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34001   }
34002   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34003     winUnlockReadLock(pFile);
34004   }
34005   if( type>=PENDING_LOCK ){
34006     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34007   }
34008   pFile->locktype = (u8)locktype;
34009   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
34010            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
34011   return rc;
34012 }
34013 
34014 /*
34015 ** If *pArg is inititially negative then this is a query.  Set *pArg to
34016 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34017 **
34018 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34019 */
34020 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34021   if( *pArg<0 ){
34022     *pArg = (pFile->ctrlFlags & mask)!=0;
34023   }else if( (*pArg)==0 ){
34024     pFile->ctrlFlags &= ~mask;
34025   }else{
34026     pFile->ctrlFlags |= mask;
34027   }
34028 }
34029 
34030 /* Forward references to VFS helper methods used for temporary files */
34031 static int winGetTempname(sqlite3_vfs *, char **);
34032 static int winIsDir(const void *);
34033 static BOOL winIsDriveLetterAndColon(const char *);
34034 
34035 /*
34036 ** Control and query of the open file handle.
34037 */
34038 static int winFileControl(sqlite3_file *id, int op, void *pArg){
34039   winFile *pFile = (winFile*)id;
34040   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
34041   switch( op ){
34042     case SQLITE_FCNTL_LOCKSTATE: {
34043       *(int*)pArg = pFile->locktype;
34044       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34045       return SQLITE_OK;
34046     }
34047     case SQLITE_LAST_ERRNO: {
34048       *(int*)pArg = (int)pFile->lastErrno;
34049       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34050       return SQLITE_OK;
34051     }
34052     case SQLITE_FCNTL_CHUNK_SIZE: {
34053       pFile->szChunk = *(int *)pArg;
34054       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34055       return SQLITE_OK;
34056     }
34057     case SQLITE_FCNTL_SIZE_HINT: {
34058       if( pFile->szChunk>0 ){
34059         sqlite3_int64 oldSz;
34060         int rc = winFileSize(id, &oldSz);
34061         if( rc==SQLITE_OK ){
34062           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34063           if( newSz>oldSz ){
34064             SimulateIOErrorBenign(1);
34065             rc = winTruncate(id, newSz);
34066             SimulateIOErrorBenign(0);
34067           }
34068         }
34069         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34070         return rc;
34071       }
34072       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34073       return SQLITE_OK;
34074     }
34075     case SQLITE_FCNTL_PERSIST_WAL: {
34076       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34077       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34078       return SQLITE_OK;
34079     }
34080     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34081       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34082       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34083       return SQLITE_OK;
34084     }
34085     case SQLITE_FCNTL_VFSNAME: {
34086       *(char**)pArg = sqlite3_mprintf("win32");
34087       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34088       return SQLITE_OK;
34089     }
34090     case SQLITE_FCNTL_WIN32_AV_RETRY: {
34091       int *a = (int*)pArg;
34092       if( a[0]>0 ){
34093         winIoerrRetry = a[0];
34094       }else{
34095         a[0] = winIoerrRetry;
34096       }
34097       if( a[1]>0 ){
34098         winIoerrRetryDelay = a[1];
34099       }else{
34100         a[1] = winIoerrRetryDelay;
34101       }
34102       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34103       return SQLITE_OK;
34104     }
34105     case SQLITE_FCNTL_TEMPFILENAME: {
34106       char *zTFile = 0;
34107       int rc = winGetTempname(pFile->pVfs, &zTFile);
34108       if( rc==SQLITE_OK ){
34109         *(char**)pArg = zTFile;
34110       }
34111       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34112       return rc;
34113     }
34114 #if SQLITE_MAX_MMAP_SIZE>0
34115     case SQLITE_FCNTL_MMAP_SIZE: {
34116       i64 newLimit = *(i64*)pArg;
34117       int rc = SQLITE_OK;
34118       if( newLimit>sqlite3GlobalConfig.mxMmap ){
34119         newLimit = sqlite3GlobalConfig.mxMmap;
34120       }
34121       *(i64*)pArg = pFile->mmapSizeMax;
34122       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
34123         pFile->mmapSizeMax = newLimit;
34124         if( pFile->mmapSize>0 ){
34125           winUnmapfile(pFile);
34126           rc = winMapfile(pFile, -1);
34127         }
34128       }
34129       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34130       return rc;
34131     }
34132 #endif
34133   }
34134   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
34135   return SQLITE_NOTFOUND;
34136 }
34137 
34138 /*
34139 ** Return the sector size in bytes of the underlying block device for
34140 ** the specified file. This is almost always 512 bytes, but may be
34141 ** larger for some devices.
34142 **
34143 ** SQLite code assumes this function cannot fail. It also assumes that
34144 ** if two files are created in the same file-system directory (i.e.
34145 ** a database and its journal file) that the sector size will be the
34146 ** same for both.
34147 */
34148 static int winSectorSize(sqlite3_file *id){
34149   (void)id;
34150   return SQLITE_DEFAULT_SECTOR_SIZE;
34151 }
34152 
34153 /*
34154 ** Return a vector of device characteristics.
34155 */
34156 static int winDeviceCharacteristics(sqlite3_file *id){
34157   winFile *p = (winFile*)id;
34158   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34159          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34160 }
34161 
34162 /* 
34163 ** Windows will only let you create file view mappings
34164 ** on allocation size granularity boundaries.
34165 ** During sqlite3_os_init() we do a GetSystemInfo()
34166 ** to get the granularity size.
34167 */
34168 SYSTEM_INFO winSysInfo;
34169 
34170 #ifndef SQLITE_OMIT_WAL
34171 
34172 /*
34173 ** Helper functions to obtain and relinquish the global mutex. The
34174 ** global mutex is used to protect the winLockInfo objects used by 
34175 ** this file, all of which may be shared by multiple threads.
34176 **
34177 ** Function winShmMutexHeld() is used to assert() that the global mutex 
34178 ** is held when required. This function is only used as part of assert() 
34179 ** statements. e.g.
34180 **
34181 **   winShmEnterMutex()
34182 **     assert( winShmMutexHeld() );
34183 **   winShmLeaveMutex()
34184 */
34185 static void winShmEnterMutex(void){
34186   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34187 }
34188 static void winShmLeaveMutex(void){
34189   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34190 }
34191 #ifdef SQLITE_DEBUG
34192 static int winShmMutexHeld(void) {
34193   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34194 }
34195 #endif
34196 
34197 /*
34198 ** Object used to represent a single file opened and mmapped to provide
34199 ** shared memory.  When multiple threads all reference the same
34200 ** log-summary, each thread has its own winFile object, but they all
34201 ** point to a single instance of this object.  In other words, each
34202 ** log-summary is opened only once per process.
34203 **
34204 ** winShmMutexHeld() must be true when creating or destroying
34205 ** this object or while reading or writing the following fields:
34206 **
34207 **      nRef
34208 **      pNext 
34209 **
34210 ** The following fields are read-only after the object is created:
34211 ** 
34212 **      fid
34213 **      zFilename
34214 **
34215 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34216 ** winShmMutexHeld() is true when reading or writing any other field
34217 ** in this structure.
34218 **
34219 */
34220 struct winShmNode {
34221   sqlite3_mutex *mutex;      /* Mutex to access this object */
34222   char *zFilename;           /* Name of the file */
34223   winFile hFile;             /* File handle from winOpen */
34224 
34225   int szRegion;              /* Size of shared-memory regions */
34226   int nRegion;               /* Size of array apRegion */
34227   struct ShmRegion {
34228     HANDLE hMap;             /* File handle from CreateFileMapping */
34229     void *pMap;
34230   } *aRegion;
34231   DWORD lastErrno;           /* The Windows errno from the last I/O error */
34232 
34233   int nRef;                  /* Number of winShm objects pointing to this */
34234   winShm *pFirst;            /* All winShm objects pointing to this */
34235   winShmNode *pNext;         /* Next in list of all winShmNode objects */
34236 #ifdef SQLITE_DEBUG
34237   u8 nextShmId;              /* Next available winShm.id value */
34238 #endif
34239 };
34240 
34241 /*
34242 ** A global array of all winShmNode objects.
34243 **
34244 ** The winShmMutexHeld() must be true while reading or writing this list.
34245 */
34246 static winShmNode *winShmNodeList = 0;
34247 
34248 /*
34249 ** Structure used internally by this VFS to record the state of an
34250 ** open shared memory connection.
34251 **
34252 ** The following fields are initialized when this object is created and
34253 ** are read-only thereafter:
34254 **
34255 **    winShm.pShmNode
34256 **    winShm.id
34257 **
34258 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
34259 ** while accessing any read/write fields.
34260 */
34261 struct winShm {
34262   winShmNode *pShmNode;      /* The underlying winShmNode object */
34263   winShm *pNext;             /* Next winShm with the same winShmNode */
34264   u8 hasMutex;               /* True if holding the winShmNode mutex */
34265   u16 sharedMask;            /* Mask of shared locks held */
34266   u16 exclMask;              /* Mask of exclusive locks held */
34267 #ifdef SQLITE_DEBUG
34268   u8 id;                     /* Id of this connection with its winShmNode */
34269 #endif
34270 };
34271 
34272 /*
34273 ** Constants used for locking
34274 */
34275 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
34276 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34277 
34278 /*
34279 ** Apply advisory locks for all n bytes beginning at ofst.
34280 */
34281 #define _SHM_UNLCK  1
34282 #define _SHM_RDLCK  2
34283 #define _SHM_WRLCK  3
34284 static int winShmSystemLock(
34285   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
34286   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34287   int ofst,             /* Offset to first byte to be locked/unlocked */
34288   int nByte             /* Number of bytes to lock or unlock */
34289 ){
34290   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
34291 
34292   /* Access to the winShmNode object is serialized by the caller */
34293   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
34294 
34295   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
34296            pFile->hFile.h, lockType, ofst, nByte));
34297 
34298   /* Release/Acquire the system-level lock */
34299   if( lockType==_SHM_UNLCK ){
34300     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
34301   }else{
34302     /* Initialize the locking parameters */
34303     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
34304     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
34305     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
34306   }
34307   
34308   if( rc!= 0 ){
34309     rc = SQLITE_OK;
34310   }else{
34311     pFile->lastErrno =  osGetLastError();
34312     rc = SQLITE_BUSY;
34313   }
34314 
34315   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
34316            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
34317            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
34318 
34319   return rc;
34320 }
34321 
34322 /* Forward references to VFS methods */
34323 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
34324 static int winDelete(sqlite3_vfs *,const char*,int);
34325 
34326 /*
34327 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
34328 **
34329 ** This is not a VFS shared-memory method; it is a utility function called
34330 ** by VFS shared-memory methods.
34331 */
34332 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
34333   winShmNode **pp;
34334   winShmNode *p;
34335   assert( winShmMutexHeld() );
34336   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
34337            osGetCurrentProcessId(), deleteFlag));
34338   pp = &winShmNodeList;
34339   while( (p = *pp)!=0 ){
34340     if( p->nRef==0 ){
34341       int i;
34342       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
34343       for(i=0; i<p->nRegion; i++){
34344         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
34345         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
34346                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
34347         UNUSED_VARIABLE_VALUE(bRc);
34348         bRc = osCloseHandle(p->aRegion[i].hMap);
34349         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
34350                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
34351         UNUSED_VARIABLE_VALUE(bRc);
34352       }
34353       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
34354         SimulateIOErrorBenign(1);
34355         winClose((sqlite3_file *)&p->hFile);
34356         SimulateIOErrorBenign(0);
34357       }
34358       if( deleteFlag ){
34359         SimulateIOErrorBenign(1);
34360         sqlite3BeginBenignMalloc();
34361         winDelete(pVfs, p->zFilename, 0);
34362         sqlite3EndBenignMalloc();
34363         SimulateIOErrorBenign(0);
34364       }
34365       *pp = p->pNext;
34366       sqlite3_free(p->aRegion);
34367       sqlite3_free(p);
34368     }else{
34369       pp = &p->pNext;
34370     }
34371   }
34372 }
34373 
34374 /*
34375 ** Open the shared-memory area associated with database file pDbFd.
34376 **
34377 ** When opening a new shared-memory file, if no other instances of that
34378 ** file are currently open, in this process or in other processes, then
34379 ** the file must be truncated to zero length or have its header cleared.
34380 */
34381 static int winOpenSharedMemory(winFile *pDbFd){
34382   struct winShm *p;                  /* The connection to be opened */
34383   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
34384   int rc;                            /* Result code */
34385   struct winShmNode *pNew;           /* Newly allocated winShmNode */
34386   int nName;                         /* Size of zName in bytes */
34387 
34388   assert( pDbFd->pShm==0 );    /* Not previously opened */
34389 
34390   /* Allocate space for the new sqlite3_shm object.  Also speculatively
34391   ** allocate space for a new winShmNode and filename.
34392   */
34393   p = sqlite3MallocZero( sizeof(*p) );
34394   if( p==0 ) return SQLITE_IOERR_NOMEM;
34395   nName = sqlite3Strlen30(pDbFd->zPath);
34396   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
34397   if( pNew==0 ){
34398     sqlite3_free(p);
34399     return SQLITE_IOERR_NOMEM;
34400   }
34401   pNew->zFilename = (char*)&pNew[1];
34402   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
34403   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
34404 
34405   /* Look to see if there is an existing winShmNode that can be used.
34406   ** If no matching winShmNode currently exists, create a new one.
34407   */
34408   winShmEnterMutex();
34409   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
34410     /* TBD need to come up with better match here.  Perhaps
34411     ** use FILE_ID_BOTH_DIR_INFO Structure.
34412     */
34413     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
34414   }
34415   if( pShmNode ){
34416     sqlite3_free(pNew);
34417   }else{
34418     pShmNode = pNew;
34419     pNew = 0;
34420     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
34421     pShmNode->pNext = winShmNodeList;
34422     winShmNodeList = pShmNode;
34423 
34424     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34425     if( pShmNode->mutex==0 ){
34426       rc = SQLITE_IOERR_NOMEM;
34427       goto shm_open_err;
34428     }
34429 
34430     rc = winOpen(pDbFd->pVfs,
34431                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
34432                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
34433                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
34434                  0);
34435     if( SQLITE_OK!=rc ){
34436       goto shm_open_err;
34437     }
34438 
34439     /* Check to see if another process is holding the dead-man switch.
34440     ** If not, truncate the file to zero length. 
34441     */
34442     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
34443       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
34444       if( rc!=SQLITE_OK ){
34445         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
34446                          "winOpenShm", pDbFd->zPath);
34447       }
34448     }
34449     if( rc==SQLITE_OK ){
34450       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34451       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
34452     }
34453     if( rc ) goto shm_open_err;
34454   }
34455 
34456   /* Make the new connection a child of the winShmNode */
34457   p->pShmNode = pShmNode;
34458 #ifdef SQLITE_DEBUG
34459   p->id = pShmNode->nextShmId++;
34460 #endif
34461   pShmNode->nRef++;
34462   pDbFd->pShm = p;
34463   winShmLeaveMutex();
34464 
34465   /* The reference count on pShmNode has already been incremented under
34466   ** the cover of the winShmEnterMutex() mutex and the pointer from the
34467   ** new (struct winShm) object to the pShmNode has been set. All that is
34468   ** left to do is to link the new object into the linked list starting
34469   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
34470   ** mutex.
34471   */
34472   sqlite3_mutex_enter(pShmNode->mutex);
34473   p->pNext = pShmNode->pFirst;
34474   pShmNode->pFirst = p;
34475   sqlite3_mutex_leave(pShmNode->mutex);
34476   return SQLITE_OK;
34477 
34478   /* Jump here on any error */
34479 shm_open_err:
34480   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34481   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
34482   sqlite3_free(p);
34483   sqlite3_free(pNew);
34484   winShmLeaveMutex();
34485   return rc;
34486 }
34487 
34488 /*
34489 ** Close a connection to shared-memory.  Delete the underlying 
34490 ** storage if deleteFlag is true.
34491 */
34492 static int winShmUnmap(
34493   sqlite3_file *fd,          /* Database holding shared memory */
34494   int deleteFlag             /* Delete after closing if true */
34495 ){
34496   winFile *pDbFd;       /* Database holding shared-memory */
34497   winShm *p;            /* The connection to be closed */
34498   winShmNode *pShmNode; /* The underlying shared-memory file */
34499   winShm **pp;          /* For looping over sibling connections */
34500 
34501   pDbFd = (winFile*)fd;
34502   p = pDbFd->pShm;
34503   if( p==0 ) return SQLITE_OK;
34504   pShmNode = p->pShmNode;
34505 
34506   /* Remove connection p from the set of connections associated
34507   ** with pShmNode */
34508   sqlite3_mutex_enter(pShmNode->mutex);
34509   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34510   *pp = p->pNext;
34511 
34512   /* Free the connection p */
34513   sqlite3_free(p);
34514   pDbFd->pShm = 0;
34515   sqlite3_mutex_leave(pShmNode->mutex);
34516 
34517   /* If pShmNode->nRef has reached 0, then close the underlying
34518   ** shared-memory file, too */
34519   winShmEnterMutex();
34520   assert( pShmNode->nRef>0 );
34521   pShmNode->nRef--;
34522   if( pShmNode->nRef==0 ){
34523     winShmPurge(pDbFd->pVfs, deleteFlag);
34524   }
34525   winShmLeaveMutex();
34526 
34527   return SQLITE_OK;
34528 }
34529 
34530 /*
34531 ** Change the lock state for a shared-memory segment.
34532 */
34533 static int winShmLock(
34534   sqlite3_file *fd,          /* Database file holding the shared memory */
34535   int ofst,                  /* First lock to acquire or release */
34536   int n,                     /* Number of locks to acquire or release */
34537   int flags                  /* What to do with the lock */
34538 ){
34539   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
34540   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
34541   winShm *pX;                           /* For looping over all siblings */
34542   winShmNode *pShmNode = p->pShmNode;
34543   int rc = SQLITE_OK;                   /* Result code */
34544   u16 mask;                             /* Mask of locks to take or release */
34545 
34546   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34547   assert( n>=1 );
34548   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34549        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34550        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34551        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34552   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34553 
34554   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34555   assert( n>1 || mask==(1<<ofst) );
34556   sqlite3_mutex_enter(pShmNode->mutex);
34557   if( flags & SQLITE_SHM_UNLOCK ){
34558     u16 allMask = 0; /* Mask of locks held by siblings */
34559 
34560     /* See if any siblings hold this same lock */
34561     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34562       if( pX==p ) continue;
34563       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34564       allMask |= pX->sharedMask;
34565     }
34566 
34567     /* Unlock the system-level locks */
34568     if( (mask & allMask)==0 ){
34569       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34570     }else{
34571       rc = SQLITE_OK;
34572     }
34573 
34574     /* Undo the local locks */
34575     if( rc==SQLITE_OK ){
34576       p->exclMask &= ~mask;
34577       p->sharedMask &= ~mask;
34578     } 
34579   }else if( flags & SQLITE_SHM_SHARED ){
34580     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34581 
34582     /* Find out which shared locks are already held by sibling connections.
34583     ** If any sibling already holds an exclusive lock, go ahead and return
34584     ** SQLITE_BUSY.
34585     */
34586     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34587       if( (pX->exclMask & mask)!=0 ){
34588         rc = SQLITE_BUSY;
34589         break;
34590       }
34591       allShared |= pX->sharedMask;
34592     }
34593 
34594     /* Get shared locks at the system level, if necessary */
34595     if( rc==SQLITE_OK ){
34596       if( (allShared & mask)==0 ){
34597         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34598       }else{
34599         rc = SQLITE_OK;
34600       }
34601     }
34602 
34603     /* Get the local shared locks */
34604     if( rc==SQLITE_OK ){
34605       p->sharedMask |= mask;
34606     }
34607   }else{
34608     /* Make sure no sibling connections hold locks that will block this
34609     ** lock.  If any do, return SQLITE_BUSY right away.
34610     */
34611     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34612       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34613         rc = SQLITE_BUSY;
34614         break;
34615       }
34616     }
34617   
34618     /* Get the exclusive locks at the system level.  Then if successful
34619     ** also mark the local connection as being locked.
34620     */
34621     if( rc==SQLITE_OK ){
34622       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34623       if( rc==SQLITE_OK ){
34624         assert( (p->sharedMask & mask)==0 );
34625         p->exclMask |= mask;
34626       }
34627     }
34628   }
34629   sqlite3_mutex_leave(pShmNode->mutex);
34630   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
34631            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
34632            sqlite3ErrName(rc)));
34633   return rc;
34634 }
34635 
34636 /*
34637 ** Implement a memory barrier or memory fence on shared memory.  
34638 **
34639 ** All loads and stores begun before the barrier must complete before
34640 ** any load or store begun after the barrier.
34641 */
34642 static void winShmBarrier(
34643   sqlite3_file *fd          /* Database holding the shared memory */
34644 ){
34645   UNUSED_PARAMETER(fd);
34646   /* MemoryBarrier(); // does not work -- do not know why not */
34647   winShmEnterMutex();
34648   winShmLeaveMutex();
34649 }
34650 
34651 /*
34652 ** This function is called to obtain a pointer to region iRegion of the 
34653 ** shared-memory associated with the database file fd. Shared-memory regions 
34654 ** are numbered starting from zero. Each shared-memory region is szRegion 
34655 ** bytes in size.
34656 **
34657 ** If an error occurs, an error code is returned and *pp is set to NULL.
34658 **
34659 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34660 ** region has not been allocated (by any client, including one running in a
34661 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
34662 ** isWrite is non-zero and the requested shared-memory region has not yet 
34663 ** been allocated, it is allocated by this function.
34664 **
34665 ** If the shared-memory region has already been allocated or is allocated by
34666 ** this call as described above, then it is mapped into this processes 
34667 ** address space (if it is not already), *pp is set to point to the mapped 
34668 ** memory and SQLITE_OK returned.
34669 */
34670 static int winShmMap(
34671   sqlite3_file *fd,               /* Handle open on database file */
34672   int iRegion,                    /* Region to retrieve */
34673   int szRegion,                   /* Size of regions */
34674   int isWrite,                    /* True to extend file if necessary */
34675   void volatile **pp              /* OUT: Mapped memory */
34676 ){
34677   winFile *pDbFd = (winFile*)fd;
34678   winShm *p = pDbFd->pShm;
34679   winShmNode *pShmNode;
34680   int rc = SQLITE_OK;
34681 
34682   if( !p ){
34683     rc = winOpenSharedMemory(pDbFd);
34684     if( rc!=SQLITE_OK ) return rc;
34685     p = pDbFd->pShm;
34686   }
34687   pShmNode = p->pShmNode;
34688 
34689   sqlite3_mutex_enter(pShmNode->mutex);
34690   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34691 
34692   if( pShmNode->nRegion<=iRegion ){
34693     struct ShmRegion *apNew;           /* New aRegion[] array */
34694     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
34695     sqlite3_int64 sz;                  /* Current size of wal-index file */
34696 
34697     pShmNode->szRegion = szRegion;
34698 
34699     /* The requested region is not mapped into this processes address space.
34700     ** Check to see if it has been allocated (i.e. if the wal-index file is
34701     ** large enough to contain the requested region).
34702     */
34703     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34704     if( rc!=SQLITE_OK ){
34705       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34706                        "winShmMap1", pDbFd->zPath);
34707       goto shmpage_out;
34708     }
34709 
34710     if( sz<nByte ){
34711       /* The requested memory region does not exist. If isWrite is set to
34712       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34713       **
34714       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34715       ** the requested memory region.
34716       */
34717       if( !isWrite ) goto shmpage_out;
34718       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34719       if( rc!=SQLITE_OK ){
34720         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34721                          "winShmMap2", pDbFd->zPath);
34722         goto shmpage_out;
34723       }
34724     }
34725 
34726     /* Map the requested memory region into this processes address space. */
34727     apNew = (struct ShmRegion *)sqlite3_realloc(
34728         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34729     );
34730     if( !apNew ){
34731       rc = SQLITE_IOERR_NOMEM;
34732       goto shmpage_out;
34733     }
34734     pShmNode->aRegion = apNew;
34735 
34736     while( pShmNode->nRegion<=iRegion ){
34737       HANDLE hMap = NULL;         /* file-mapping handle */
34738       void *pMap = 0;             /* Mapped memory region */
34739      
34740 #if SQLITE_OS_WINRT
34741       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
34742           NULL, PAGE_READWRITE, nByte, NULL
34743       );
34744 #elif defined(SQLITE_WIN32_HAS_WIDE)
34745       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
34746           NULL, PAGE_READWRITE, 0, nByte, NULL
34747       );
34748 #elif defined(SQLITE_WIN32_HAS_ANSI)
34749       hMap = osCreateFileMappingA(pShmNode->hFile.h, 
34750           NULL, PAGE_READWRITE, 0, nByte, NULL
34751       );
34752 #endif
34753       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
34754                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34755                hMap ? "ok" : "failed"));
34756       if( hMap ){
34757         int iOffset = pShmNode->nRegion*szRegion;
34758         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34759 #if SQLITE_OS_WINRT
34760         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34761             iOffset - iOffsetShift, szRegion + iOffsetShift
34762         );
34763 #else
34764         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34765             0, iOffset - iOffsetShift, szRegion + iOffsetShift
34766         );
34767 #endif
34768         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
34769                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34770                  szRegion, pMap ? "ok" : "failed"));
34771       }
34772       if( !pMap ){
34773         pShmNode->lastErrno = osGetLastError();
34774         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34775                          "winShmMap3", pDbFd->zPath);
34776         if( hMap ) osCloseHandle(hMap);
34777         goto shmpage_out;
34778       }
34779 
34780       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34781       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34782       pShmNode->nRegion++;
34783     }
34784   }
34785 
34786 shmpage_out:
34787   if( pShmNode->nRegion>iRegion ){
34788     int iOffset = iRegion*szRegion;
34789     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34790     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34791     *pp = (void *)&p[iOffsetShift];
34792   }else{
34793     *pp = 0;
34794   }
34795   sqlite3_mutex_leave(pShmNode->mutex);
34796   return rc;
34797 }
34798 
34799 #else
34800 # define winShmMap     0
34801 # define winShmLock    0
34802 # define winShmBarrier 0
34803 # define winShmUnmap   0
34804 #endif /* #ifndef SQLITE_OMIT_WAL */
34805 
34806 /*
34807 ** Cleans up the mapped region of the specified file, if any.
34808 */
34809 #if SQLITE_MAX_MMAP_SIZE>0
34810 static int winUnmapfile(winFile *pFile){
34811   assert( pFile!=0 );
34812   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
34813            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
34814            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
34815            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
34816   if( pFile->pMapRegion ){
34817     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
34818       pFile->lastErrno = osGetLastError();
34819       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
34820                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
34821                pFile->pMapRegion));
34822       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34823                          "winUnmapfile1", pFile->zPath);
34824     }
34825     pFile->pMapRegion = 0;
34826     pFile->mmapSize = 0;
34827     pFile->mmapSizeActual = 0;
34828   }
34829   if( pFile->hMap!=NULL ){
34830     if( !osCloseHandle(pFile->hMap) ){
34831       pFile->lastErrno = osGetLastError();
34832       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
34833                osGetCurrentProcessId(), pFile, pFile->hMap));
34834       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34835                          "winUnmapfile2", pFile->zPath);
34836     }
34837     pFile->hMap = NULL;
34838   }
34839   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34840            osGetCurrentProcessId(), pFile));
34841   return SQLITE_OK;
34842 }
34843 
34844 /*
34845 ** Memory map or remap the file opened by file-descriptor pFd (if the file
34846 ** is already mapped, the existing mapping is replaced by the new). Or, if 
34847 ** there already exists a mapping for this file, and there are still 
34848 ** outstanding xFetch() references to it, this function is a no-op.
34849 **
34850 ** If parameter nByte is non-negative, then it is the requested size of 
34851 ** the mapping to create. Otherwise, if nByte is less than zero, then the 
34852 ** requested size is the size of the file on disk. The actual size of the
34853 ** created mapping is either the requested size or the value configured 
34854 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
34855 **
34856 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34857 ** recreated as a result of outstanding references) or an SQLite error
34858 ** code otherwise.
34859 */
34860 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
34861   sqlite3_int64 nMap = nByte;
34862   int rc;
34863 
34864   assert( nMap>=0 || pFd->nFetchOut==0 );
34865   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
34866            osGetCurrentProcessId(), pFd, nByte));
34867 
34868   if( pFd->nFetchOut>0 ) return SQLITE_OK;
34869 
34870   if( nMap<0 ){
34871     rc = winFileSize((sqlite3_file*)pFd, &nMap);
34872     if( rc ){
34873       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
34874                osGetCurrentProcessId(), pFd));
34875       return SQLITE_IOERR_FSTAT;
34876     }
34877   }
34878   if( nMap>pFd->mmapSizeMax ){
34879     nMap = pFd->mmapSizeMax;
34880   }
34881   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
34882  
34883   if( nMap==0 && pFd->mmapSize>0 ){
34884     winUnmapfile(pFd);
34885   }
34886   if( nMap!=pFd->mmapSize ){
34887     void *pNew = 0;
34888     DWORD protect = PAGE_READONLY;
34889     DWORD flags = FILE_MAP_READ;
34890 
34891     winUnmapfile(pFd);
34892     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
34893       protect = PAGE_READWRITE;
34894       flags |= FILE_MAP_WRITE;
34895     }
34896 #if SQLITE_OS_WINRT
34897     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
34898 #elif defined(SQLITE_WIN32_HAS_WIDE)
34899     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
34900                                 (DWORD)((nMap>>32) & 0xffffffff),
34901                                 (DWORD)(nMap & 0xffffffff), NULL);
34902 #elif defined(SQLITE_WIN32_HAS_ANSI)
34903     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
34904                                 (DWORD)((nMap>>32) & 0xffffffff),
34905                                 (DWORD)(nMap & 0xffffffff), NULL);
34906 #endif
34907     if( pFd->hMap==NULL ){
34908       pFd->lastErrno = osGetLastError();
34909       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34910                        "winMapfile1", pFd->zPath);
34911       /* Log the error, but continue normal operation using xRead/xWrite */
34912       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
34913                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34914       return SQLITE_OK;
34915     }
34916     assert( (nMap % winSysInfo.dwPageSize)==0 );
34917     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
34918 #if SQLITE_OS_WINRT
34919     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
34920 #else
34921     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
34922 #endif
34923     if( pNew==NULL ){
34924       osCloseHandle(pFd->hMap);
34925       pFd->hMap = NULL;
34926       pFd->lastErrno = osGetLastError();
34927       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34928                        "winMapfile2", pFd->zPath);
34929       /* Log the error, but continue normal operation using xRead/xWrite */
34930       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
34931                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34932       return SQLITE_OK;
34933     }
34934     pFd->pMapRegion = pNew;
34935     pFd->mmapSize = nMap;
34936     pFd->mmapSizeActual = nMap;
34937   }
34938 
34939   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34940            osGetCurrentProcessId(), pFd));
34941   return SQLITE_OK;
34942 }
34943 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34944 
34945 /*
34946 ** If possible, return a pointer to a mapping of file fd starting at offset
34947 ** iOff. The mapping must be valid for at least nAmt bytes.
34948 **
34949 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34950 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34951 ** Finally, if an error does occur, return an SQLite error code. The final
34952 ** value of *pp is undefined in this case.
34953 **
34954 ** If this function does return a pointer, the caller must eventually 
34955 ** release the reference by calling winUnfetch().
34956 */
34957 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34958 #if SQLITE_MAX_MMAP_SIZE>0
34959   winFile *pFd = (winFile*)fd;   /* The underlying database file */
34960 #endif
34961   *pp = 0;
34962 
34963   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
34964            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
34965 
34966 #if SQLITE_MAX_MMAP_SIZE>0
34967   if( pFd->mmapSizeMax>0 ){
34968     if( pFd->pMapRegion==0 ){
34969       int rc = winMapfile(pFd, -1);
34970       if( rc!=SQLITE_OK ){
34971         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
34972                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34973         return rc;
34974       }
34975     }
34976     if( pFd->mmapSize >= iOff+nAmt ){
34977       *pp = &((u8 *)pFd->pMapRegion)[iOff];
34978       pFd->nFetchOut++;
34979     }
34980   }
34981 #endif
34982 
34983   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
34984            osGetCurrentProcessId(), fd, pp, *pp));
34985   return SQLITE_OK;
34986 }
34987 
34988 /*
34989 ** If the third argument is non-NULL, then this function releases a 
34990 ** reference obtained by an earlier call to winFetch(). The second
34991 ** argument passed to this function must be the same as the corresponding
34992 ** argument that was passed to the winFetch() invocation. 
34993 **
34994 ** Or, if the third argument is NULL, then this function is being called 
34995 ** to inform the VFS layer that, according to POSIX, any existing mapping 
34996 ** may now be invalid and should be unmapped.
34997 */
34998 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34999 #if SQLITE_MAX_MMAP_SIZE>0
35000   winFile *pFd = (winFile*)fd;   /* The underlying database file */
35001 
35002   /* If p==0 (unmap the entire file) then there must be no outstanding 
35003   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
35004   ** then there must be at least one outstanding.  */
35005   assert( (p==0)==(pFd->nFetchOut==0) );
35006 
35007   /* If p!=0, it must match the iOff value. */
35008   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
35009 
35010   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
35011            osGetCurrentProcessId(), pFd, iOff, p));
35012 
35013   if( p ){
35014     pFd->nFetchOut--;
35015   }else{
35016     /* FIXME:  If Windows truly always prevents truncating or deleting a
35017     ** file while a mapping is held, then the following winUnmapfile() call
35018     ** is unnecessary can can be omitted - potentially improving
35019     ** performance.  */
35020     winUnmapfile(pFd);
35021   }
35022 
35023   assert( pFd->nFetchOut>=0 );
35024 #endif
35025 
35026   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35027            osGetCurrentProcessId(), fd));
35028   return SQLITE_OK;
35029 }
35030 
35031 /*
35032 ** Here ends the implementation of all sqlite3_file methods.
35033 **
35034 ********************** End sqlite3_file Methods *******************************
35035 ******************************************************************************/
35036 
35037 /*
35038 ** This vector defines all the methods that can operate on an
35039 ** sqlite3_file for win32.
35040 */
35041 static const sqlite3_io_methods winIoMethod = {
35042   3,                              /* iVersion */
35043   winClose,                       /* xClose */
35044   winRead,                        /* xRead */
35045   winWrite,                       /* xWrite */
35046   winTruncate,                    /* xTruncate */
35047   winSync,                        /* xSync */
35048   winFileSize,                    /* xFileSize */
35049   winLock,                        /* xLock */
35050   winUnlock,                      /* xUnlock */
35051   winCheckReservedLock,           /* xCheckReservedLock */
35052   winFileControl,                 /* xFileControl */
35053   winSectorSize,                  /* xSectorSize */
35054   winDeviceCharacteristics,       /* xDeviceCharacteristics */
35055   winShmMap,                      /* xShmMap */
35056   winShmLock,                     /* xShmLock */
35057   winShmBarrier,                  /* xShmBarrier */
35058   winShmUnmap,                    /* xShmUnmap */
35059   winFetch,                       /* xFetch */
35060   winUnfetch                      /* xUnfetch */
35061 };
35062 
35063 /****************************************************************************
35064 **************************** sqlite3_vfs methods ****************************
35065 **
35066 ** This division contains the implementation of methods on the
35067 ** sqlite3_vfs object.
35068 */
35069 
35070 #if defined(__CYGWIN__)
35071 /*
35072 ** Convert a filename from whatever the underlying operating system
35073 ** supports for filenames into UTF-8.  Space to hold the result is
35074 ** obtained from malloc and must be freed by the calling function.
35075 */
35076 static char *winConvertToUtf8Filename(const void *zFilename){
35077   char *zConverted = 0;
35078   if( osIsNT() ){
35079     zConverted = winUnicodeToUtf8(zFilename);
35080   }
35081 #ifdef SQLITE_WIN32_HAS_ANSI
35082   else{
35083     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
35084   }
35085 #endif
35086   /* caller will handle out of memory */
35087   return zConverted;
35088 }
35089 #endif
35090 
35091 /*
35092 ** Convert a UTF-8 filename into whatever form the underlying
35093 ** operating system wants filenames in.  Space to hold the result
35094 ** is obtained from malloc and must be freed by the calling
35095 ** function.
35096 */
35097 static void *winConvertFromUtf8Filename(const char *zFilename){
35098   void *zConverted = 0;
35099   if( osIsNT() ){
35100     zConverted = winUtf8ToUnicode(zFilename);
35101   }
35102 #ifdef SQLITE_WIN32_HAS_ANSI
35103   else{
35104     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35105   }
35106 #endif
35107   /* caller will handle out of memory */
35108   return zConverted;
35109 }
35110 
35111 /*
35112 ** This function returns non-zero if the specified UTF-8 string buffer
35113 ** ends with a directory separator character or one was successfully
35114 ** added to it.
35115 */
35116 static int winMakeEndInDirSep(int nBuf, char *zBuf){
35117   if( zBuf ){
35118     int nLen = sqlite3Strlen30(zBuf);
35119     if( nLen>0 ){
35120       if( winIsDirSep(zBuf[nLen-1]) ){
35121         return 1;
35122       }else if( nLen+1<nBuf ){
35123         zBuf[nLen] = winGetDirSep();
35124         zBuf[nLen+1] = '\0';
35125         return 1;
35126       }
35127     }
35128   }
35129   return 0;
35130 }
35131 
35132 /*
35133 ** Create a temporary file name and store the resulting pointer into pzBuf.
35134 ** The pointer returned in pzBuf must be freed via sqlite3_free().
35135 */
35136 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
35137   static char zChars[] =
35138     "abcdefghijklmnopqrstuvwxyz"
35139     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35140     "0123456789";
35141   size_t i, j;
35142   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
35143   int nMax, nBuf, nDir, nLen;
35144   char *zBuf;
35145 
35146   /* It's odd to simulate an io-error here, but really this is just
35147   ** using the io-error infrastructure to test that SQLite handles this
35148   ** function failing. 
35149   */
35150   SimulateIOError( return SQLITE_IOERR );
35151 
35152   /* Allocate a temporary buffer to store the fully qualified file
35153   ** name for the temporary file.  If this fails, we cannot continue.
35154   */
35155   nMax = pVfs->mxPathname; nBuf = nMax + 2;
35156   zBuf = sqlite3MallocZero( nBuf );
35157   if( !zBuf ){
35158     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35159     return SQLITE_IOERR_NOMEM;
35160   }
35161 
35162   /* Figure out the effective temporary directory.  First, check if one
35163   ** has been explicitly set by the application; otherwise, use the one
35164   ** configured by the operating system.
35165   */
35166   nDir = nMax - (nPre + 15);
35167   assert( nDir>0 );
35168   if( sqlite3_temp_directory ){
35169     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
35170     if( nDirLen>0 ){
35171       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
35172         nDirLen++;
35173       }
35174       if( nDirLen>nDir ){
35175         sqlite3_free(zBuf);
35176         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35177         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
35178       }
35179       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
35180     }
35181   }
35182 #if defined(__CYGWIN__)
35183   else{
35184     static const char *azDirs[] = {
35185        0, /* getenv("SQLITE_TMPDIR") */
35186        0, /* getenv("TMPDIR") */
35187        0, /* getenv("TMP") */
35188        0, /* getenv("TEMP") */
35189        0, /* getenv("USERPROFILE") */
35190        "/var/tmp",
35191        "/usr/tmp",
35192        "/tmp",
35193        ".",
35194        0        /* List terminator */
35195     };
35196     unsigned int i;
35197     const char *zDir = 0;
35198 
35199     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35200     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35201     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
35202     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
35203     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
35204     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
35205       void *zConverted;
35206       if( zDir==0 ) continue;
35207       /* If the path starts with a drive letter followed by the colon
35208       ** character, assume it is already a native Win32 path; otherwise,
35209       ** it must be converted to a native Win32 path via the Cygwin API
35210       ** prior to using it.
35211       */
35212       if( winIsDriveLetterAndColon(zDir) ){
35213         zConverted = winConvertFromUtf8Filename(zDir);
35214         if( !zConverted ){
35215           sqlite3_free(zBuf);
35216           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35217           return SQLITE_IOERR_NOMEM;
35218         }
35219         if( winIsDir(zConverted) ){
35220           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
35221           sqlite3_free(zConverted);
35222           break;
35223         }
35224         sqlite3_free(zConverted);
35225       }else{
35226         zConverted = sqlite3MallocZero( nMax+1 );
35227         if( !zConverted ){
35228           sqlite3_free(zBuf);
35229           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35230           return SQLITE_IOERR_NOMEM;
35231         }
35232         if( cygwin_conv_path(
35233                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
35234                 zConverted, nMax+1)<0 ){
35235           sqlite3_free(zConverted);
35236           sqlite3_free(zBuf);
35237           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
35238           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
35239                              "winGetTempname2", zDir);
35240         }
35241         if( winIsDir(zConverted) ){
35242           /* At this point, we know the candidate directory exists and should
35243           ** be used.  However, we may need to convert the string containing
35244           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
35245           */
35246           char *zUtf8 = winConvertToUtf8Filename(zConverted);
35247           if( !zUtf8 ){
35248             sqlite3_free(zConverted);
35249             sqlite3_free(zBuf);
35250             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35251             return SQLITE_IOERR_NOMEM;
35252           }
35253           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
35254           sqlite3_free(zUtf8);
35255           sqlite3_free(zConverted);
35256           break;
35257         }
35258         sqlite3_free(zConverted);
35259       }
35260     }
35261   }
35262 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35263   else if( osIsNT() ){
35264     char *zMulti;
35265     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
35266     if( !zWidePath ){
35267       sqlite3_free(zBuf);
35268       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35269       return SQLITE_IOERR_NOMEM;
35270     }
35271     if( osGetTempPathW(nMax, zWidePath)==0 ){
35272       sqlite3_free(zWidePath);
35273       sqlite3_free(zBuf);
35274       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
35275       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
35276                          "winGetTempname2", 0);
35277     }
35278     zMulti = winUnicodeToUtf8(zWidePath);
35279     if( zMulti ){
35280       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
35281       sqlite3_free(zMulti);
35282       sqlite3_free(zWidePath);
35283     }else{
35284       sqlite3_free(zWidePath);
35285       sqlite3_free(zBuf);
35286       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35287       return SQLITE_IOERR_NOMEM;
35288     }
35289   }
35290 #ifdef SQLITE_WIN32_HAS_ANSI
35291   else{
35292     char *zUtf8;
35293     char *zMbcsPath = sqlite3MallocZero( nMax );
35294     if( !zMbcsPath ){
35295       sqlite3_free(zBuf);
35296       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35297       return SQLITE_IOERR_NOMEM;
35298     }
35299     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
35300       sqlite3_free(zBuf);
35301       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
35302       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
35303                          "winGetTempname3", 0);
35304     }
35305     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35306     if( zUtf8 ){
35307       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
35308       sqlite3_free(zUtf8);
35309     }else{
35310       sqlite3_free(zBuf);
35311       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35312       return SQLITE_IOERR_NOMEM;
35313     }
35314   }
35315 #endif /* SQLITE_WIN32_HAS_ANSI */
35316 #endif /* !SQLITE_OS_WINRT */
35317 
35318   /*
35319   ** Check to make sure the temporary directory ends with an appropriate
35320   ** separator.  If it does not and there is not enough space left to add
35321   ** one, fail.
35322   */
35323   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
35324     sqlite3_free(zBuf);
35325     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35326     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
35327   }
35328 
35329   /*
35330   ** Check that the output buffer is large enough for the temporary file 
35331   ** name in the following format:
35332   **
35333   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
35334   **
35335   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
35336   ** account for the space used by the 15 character random suffix and the
35337   ** two trailing NUL characters.  The final directory separator character
35338   ** has already added if it was not already present.
35339   */
35340   nLen = sqlite3Strlen30(zBuf);
35341   if( (nLen + nPre + 17) > nBuf ){
35342     sqlite3_free(zBuf);
35343     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35344     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
35345   }
35346 
35347   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
35348 
35349   j = sqlite3Strlen30(zBuf);
35350   sqlite3_randomness(15, &zBuf[j]);
35351   for(i=0; i<15; i++, j++){
35352     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35353   }
35354   zBuf[j] = 0;
35355   zBuf[j+1] = 0;
35356   *pzBuf = zBuf;
35357 
35358   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
35359   return SQLITE_OK;
35360 }
35361 
35362 /*
35363 ** Return TRUE if the named file is really a directory.  Return false if
35364 ** it is something other than a directory, or if there is any kind of memory
35365 ** allocation failure.
35366 */
35367 static int winIsDir(const void *zConverted){
35368   DWORD attr;
35369   int rc = 0;
35370   DWORD lastErrno;
35371 
35372   if( osIsNT() ){
35373     int cnt = 0;
35374     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35375     memset(&sAttrData, 0, sizeof(sAttrData));
35376     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35377                              GetFileExInfoStandard,
35378                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
35379     if( !rc ){
35380       return 0; /* Invalid name? */
35381     }
35382     attr = sAttrData.dwFileAttributes;
35383 #if SQLITE_OS_WINCE==0
35384   }else{
35385     attr = osGetFileAttributesA((char*)zConverted);
35386 #endif
35387   }
35388   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
35389 }
35390 
35391 /*
35392 ** Open a file.
35393 */
35394 static int winOpen(
35395   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
35396   const char *zName,        /* Name of the file (UTF-8) */
35397   sqlite3_file *id,         /* Write the SQLite file handle here */
35398   int flags,                /* Open mode flags */
35399   int *pOutFlags            /* Status return flags */
35400 ){
35401   HANDLE h;
35402   DWORD lastErrno = 0;
35403   DWORD dwDesiredAccess;
35404   DWORD dwShareMode;
35405   DWORD dwCreationDisposition;
35406   DWORD dwFlagsAndAttributes = 0;
35407 #if SQLITE_OS_WINCE
35408   int isTemp = 0;
35409 #endif
35410   winFile *pFile = (winFile*)id;
35411   void *zConverted;              /* Filename in OS encoding */
35412   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
35413   int cnt = 0;
35414 
35415   /* If argument zPath is a NULL pointer, this function is required to open
35416   ** a temporary file. Use this buffer to store the file name in.
35417   */
35418   char *zTmpname = 0; /* For temporary filename, if necessary. */
35419 
35420   int rc = SQLITE_OK;            /* Function Return Code */
35421 #if !defined(NDEBUG) || SQLITE_OS_WINCE
35422   int eType = flags&0xFFFFFF00;  /* Type of file to open */
35423 #endif
35424 
35425   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
35426   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
35427   int isCreate     = (flags & SQLITE_OPEN_CREATE);
35428   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
35429   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
35430 
35431 #ifndef NDEBUG
35432   int isOpenJournal = (isCreate && (
35433         eType==SQLITE_OPEN_MASTER_JOURNAL 
35434      || eType==SQLITE_OPEN_MAIN_JOURNAL 
35435      || eType==SQLITE_OPEN_WAL
35436   ));
35437 #endif
35438 
35439   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
35440            zUtf8Name, id, flags, pOutFlags));
35441 
35442   /* Check the following statements are true: 
35443   **
35444   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
35445   **   (b) if CREATE is set, then READWRITE must also be set, and
35446   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35447   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35448   */
35449   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35450   assert(isCreate==0 || isReadWrite);
35451   assert(isExclusive==0 || isCreate);
35452   assert(isDelete==0 || isCreate);
35453 
35454   /* The main DB, main journal, WAL file and master journal are never 
35455   ** automatically deleted. Nor are they ever temporary files.  */
35456   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35457   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35458   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35459   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35460 
35461   /* Assert that the upper layer has set one of the "file-type" flags. */
35462   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
35463        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
35464        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
35465        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35466   );
35467 
35468   assert( pFile!=0 );
35469   memset(pFile, 0, sizeof(winFile));
35470   pFile->h = INVALID_HANDLE_VALUE;
35471 
35472 #if SQLITE_OS_WINRT
35473   if( !zUtf8Name && !sqlite3_temp_directory ){
35474     sqlite3_log(SQLITE_ERROR,
35475         "sqlite3_temp_directory variable should be set for WinRT");
35476   }
35477 #endif
35478 
35479   /* If the second argument to this function is NULL, generate a 
35480   ** temporary file name to use 
35481   */
35482   if( !zUtf8Name ){
35483     assert( isDelete && !isOpenJournal );
35484     rc = winGetTempname(pVfs, &zTmpname);
35485     if( rc!=SQLITE_OK ){
35486       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
35487       return rc;
35488     }
35489     zUtf8Name = zTmpname;
35490   }
35491 
35492   /* Database filenames are double-zero terminated if they are not
35493   ** URIs with parameters.  Hence, they can always be passed into
35494   ** sqlite3_uri_parameter().
35495   */
35496   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
35497        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
35498 
35499   /* Convert the filename to the system encoding. */
35500   zConverted = winConvertFromUtf8Filename(zUtf8Name);
35501   if( zConverted==0 ){
35502     sqlite3_free(zTmpname);
35503     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
35504     return SQLITE_IOERR_NOMEM;
35505   }
35506 
35507   if( winIsDir(zConverted) ){
35508     sqlite3_free(zConverted);
35509     sqlite3_free(zTmpname);
35510     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
35511     return SQLITE_CANTOPEN_ISDIR;
35512   }
35513 
35514   if( isReadWrite ){
35515     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
35516   }else{
35517     dwDesiredAccess = GENERIC_READ;
35518   }
35519 
35520   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
35521   ** created. SQLite doesn't use it to indicate "exclusive access" 
35522   ** as it is usually understood.
35523   */
35524   if( isExclusive ){
35525     /* Creates a new file, only if it does not already exist. */
35526     /* If the file exists, it fails. */
35527     dwCreationDisposition = CREATE_NEW;
35528   }else if( isCreate ){
35529     /* Open existing file, or create if it doesn't exist */
35530     dwCreationDisposition = OPEN_ALWAYS;
35531   }else{
35532     /* Opens a file, only if it exists. */
35533     dwCreationDisposition = OPEN_EXISTING;
35534   }
35535 
35536   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
35537 
35538   if( isDelete ){
35539 #if SQLITE_OS_WINCE
35540     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
35541     isTemp = 1;
35542 #else
35543     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
35544                                | FILE_ATTRIBUTE_HIDDEN
35545                                | FILE_FLAG_DELETE_ON_CLOSE;
35546 #endif
35547   }else{
35548     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
35549   }
35550   /* Reports from the internet are that performance is always
35551   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
35552 #if SQLITE_OS_WINCE
35553   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
35554 #endif
35555 
35556   if( osIsNT() ){
35557 #if SQLITE_OS_WINRT
35558     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
35559     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
35560     extendedParameters.dwFileAttributes =
35561             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
35562     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
35563     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
35564     extendedParameters.lpSecurityAttributes = NULL;
35565     extendedParameters.hTemplateFile = NULL;
35566     while( (h = osCreateFile2((LPCWSTR)zConverted,
35567                               dwDesiredAccess,
35568                               dwShareMode,
35569                               dwCreationDisposition,
35570                               &extendedParameters))==INVALID_HANDLE_VALUE &&
35571                               winRetryIoerr(&cnt, &lastErrno) ){
35572                /* Noop */
35573     }
35574 #else
35575     while( (h = osCreateFileW((LPCWSTR)zConverted,
35576                               dwDesiredAccess,
35577                               dwShareMode, NULL,
35578                               dwCreationDisposition,
35579                               dwFlagsAndAttributes,
35580                               NULL))==INVALID_HANDLE_VALUE &&
35581                               winRetryIoerr(&cnt, &lastErrno) ){
35582                /* Noop */
35583     }
35584 #endif
35585   }
35586 #ifdef SQLITE_WIN32_HAS_ANSI
35587   else{
35588     while( (h = osCreateFileA((LPCSTR)zConverted,
35589                               dwDesiredAccess,
35590                               dwShareMode, NULL,
35591                               dwCreationDisposition,
35592                               dwFlagsAndAttributes,
35593                               NULL))==INVALID_HANDLE_VALUE &&
35594                               winRetryIoerr(&cnt, &lastErrno) ){
35595                /* Noop */
35596     }
35597   }
35598 #endif
35599   winLogIoerr(cnt);
35600 
35601   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
35602            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
35603 
35604   if( h==INVALID_HANDLE_VALUE ){
35605     pFile->lastErrno = lastErrno;
35606     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
35607     sqlite3_free(zConverted);
35608     sqlite3_free(zTmpname);
35609     if( isReadWrite && !isExclusive ){
35610       return winOpen(pVfs, zName, id, 
35611          ((flags|SQLITE_OPEN_READONLY) &
35612                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
35613          pOutFlags);
35614     }else{
35615       return SQLITE_CANTOPEN_BKPT;
35616     }
35617   }
35618 
35619   if( pOutFlags ){
35620     if( isReadWrite ){
35621       *pOutFlags = SQLITE_OPEN_READWRITE;
35622     }else{
35623       *pOutFlags = SQLITE_OPEN_READONLY;
35624     }
35625   }
35626 
35627   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
35628            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
35629            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
35630 
35631 #if SQLITE_OS_WINCE
35632   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
35633        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
35634   ){
35635     osCloseHandle(h);
35636     sqlite3_free(zConverted);
35637     sqlite3_free(zTmpname);
35638     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
35639     return rc;
35640   }
35641   if( isTemp ){
35642     pFile->zDeleteOnClose = zConverted;
35643   }else
35644 #endif
35645   {
35646     sqlite3_free(zConverted);
35647   }
35648 
35649   sqlite3_free(zTmpname);
35650   pFile->pMethod = &winIoMethod;
35651   pFile->pVfs = pVfs;
35652   pFile->h = h;
35653   if( isReadonly ){
35654     pFile->ctrlFlags |= WINFILE_RDONLY;
35655   }
35656   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35657     pFile->ctrlFlags |= WINFILE_PSOW;
35658   }
35659   pFile->lastErrno = NO_ERROR;
35660   pFile->zPath = zName;
35661 #if SQLITE_MAX_MMAP_SIZE>0
35662   pFile->hMap = NULL;
35663   pFile->pMapRegion = 0;
35664   pFile->mmapSize = 0;
35665   pFile->mmapSizeActual = 0;
35666   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
35667 #endif
35668 
35669   OpenCounter(+1);
35670   return rc;
35671 }
35672 
35673 /*
35674 ** Delete the named file.
35675 **
35676 ** Note that Windows does not allow a file to be deleted if some other
35677 ** process has it open.  Sometimes a virus scanner or indexing program
35678 ** will open a journal file shortly after it is created in order to do
35679 ** whatever it does.  While this other process is holding the
35680 ** file open, we will be unable to delete it.  To work around this
35681 ** problem, we delay 100 milliseconds and try to delete again.  Up
35682 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
35683 ** up and returning an error.
35684 */
35685 static int winDelete(
35686   sqlite3_vfs *pVfs,          /* Not used on win32 */
35687   const char *zFilename,      /* Name of file to delete */
35688   int syncDir                 /* Not used on win32 */
35689 ){
35690   int cnt = 0;
35691   int rc;
35692   DWORD attr;
35693   DWORD lastErrno = 0;
35694   void *zConverted;
35695   UNUSED_PARAMETER(pVfs);
35696   UNUSED_PARAMETER(syncDir);
35697 
35698   SimulateIOError(return SQLITE_IOERR_DELETE);
35699   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
35700 
35701   zConverted = winConvertFromUtf8Filename(zFilename);
35702   if( zConverted==0 ){
35703     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
35704     return SQLITE_IOERR_NOMEM;
35705   }
35706   if( osIsNT() ){
35707     do {
35708 #if SQLITE_OS_WINRT
35709       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35710       memset(&sAttrData, 0, sizeof(sAttrData));
35711       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
35712                                   &sAttrData) ){
35713         attr = sAttrData.dwFileAttributes;
35714       }else{
35715         lastErrno = osGetLastError();
35716         if( lastErrno==ERROR_FILE_NOT_FOUND
35717          || lastErrno==ERROR_PATH_NOT_FOUND ){
35718           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35719         }else{
35720           rc = SQLITE_ERROR;
35721         }
35722         break;
35723       }
35724 #else
35725       attr = osGetFileAttributesW(zConverted);
35726 #endif
35727       if ( attr==INVALID_FILE_ATTRIBUTES ){
35728         lastErrno = osGetLastError();
35729         if( lastErrno==ERROR_FILE_NOT_FOUND
35730          || lastErrno==ERROR_PATH_NOT_FOUND ){
35731           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35732         }else{
35733           rc = SQLITE_ERROR;
35734         }
35735         break;
35736       }
35737       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35738         rc = SQLITE_ERROR; /* Files only. */
35739         break;
35740       }
35741       if ( osDeleteFileW(zConverted) ){
35742         rc = SQLITE_OK; /* Deleted OK. */
35743         break;
35744       }
35745       if ( !winRetryIoerr(&cnt, &lastErrno) ){
35746         rc = SQLITE_ERROR; /* No more retries. */
35747         break;
35748       }
35749     } while(1);
35750   }
35751 #ifdef SQLITE_WIN32_HAS_ANSI
35752   else{
35753     do {
35754       attr = osGetFileAttributesA(zConverted);
35755       if ( attr==INVALID_FILE_ATTRIBUTES ){
35756         lastErrno = osGetLastError();
35757         if( lastErrno==ERROR_FILE_NOT_FOUND
35758          || lastErrno==ERROR_PATH_NOT_FOUND ){
35759           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35760         }else{
35761           rc = SQLITE_ERROR;
35762         }
35763         break;
35764       }
35765       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35766         rc = SQLITE_ERROR; /* Files only. */
35767         break;
35768       }
35769       if ( osDeleteFileA(zConverted) ){
35770         rc = SQLITE_OK; /* Deleted OK. */
35771         break;
35772       }
35773       if ( !winRetryIoerr(&cnt, &lastErrno) ){
35774         rc = SQLITE_ERROR; /* No more retries. */
35775         break;
35776       }
35777     } while(1);
35778   }
35779 #endif
35780   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
35781     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
35782   }else{
35783     winLogIoerr(cnt);
35784   }
35785   sqlite3_free(zConverted);
35786   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
35787   return rc;
35788 }
35789 
35790 /*
35791 ** Check the existence and status of a file.
35792 */
35793 static int winAccess(
35794   sqlite3_vfs *pVfs,         /* Not used on win32 */
35795   const char *zFilename,     /* Name of file to check */
35796   int flags,                 /* Type of test to make on this file */
35797   int *pResOut               /* OUT: Result */
35798 ){
35799   DWORD attr;
35800   int rc = 0;
35801   DWORD lastErrno = 0;
35802   void *zConverted;
35803   UNUSED_PARAMETER(pVfs);
35804 
35805   SimulateIOError( return SQLITE_IOERR_ACCESS; );
35806   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
35807            zFilename, flags, pResOut));
35808 
35809   zConverted = winConvertFromUtf8Filename(zFilename);
35810   if( zConverted==0 ){
35811     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
35812     return SQLITE_IOERR_NOMEM;
35813   }
35814   if( osIsNT() ){
35815     int cnt = 0;
35816     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35817     memset(&sAttrData, 0, sizeof(sAttrData));
35818     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35819                              GetFileExInfoStandard, 
35820                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
35821     if( rc ){
35822       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35823       ** as if it does not exist.
35824       */
35825       if(    flags==SQLITE_ACCESS_EXISTS
35826           && sAttrData.nFileSizeHigh==0 
35827           && sAttrData.nFileSizeLow==0 ){
35828         attr = INVALID_FILE_ATTRIBUTES;
35829       }else{
35830         attr = sAttrData.dwFileAttributes;
35831       }
35832     }else{
35833       winLogIoerr(cnt);
35834       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
35835         sqlite3_free(zConverted);
35836         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
35837                            zFilename);
35838       }else{
35839         attr = INVALID_FILE_ATTRIBUTES;
35840       }
35841     }
35842   }
35843 #ifdef SQLITE_WIN32_HAS_ANSI
35844   else{
35845     attr = osGetFileAttributesA((char*)zConverted);
35846   }
35847 #endif
35848   sqlite3_free(zConverted);
35849   switch( flags ){
35850     case SQLITE_ACCESS_READ:
35851     case SQLITE_ACCESS_EXISTS:
35852       rc = attr!=INVALID_FILE_ATTRIBUTES;
35853       break;
35854     case SQLITE_ACCESS_READWRITE:
35855       rc = attr!=INVALID_FILE_ATTRIBUTES &&
35856              (attr & FILE_ATTRIBUTE_READONLY)==0;
35857       break;
35858     default:
35859       assert(!"Invalid flags argument");
35860   }
35861   *pResOut = rc;
35862   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35863            zFilename, pResOut, *pResOut));
35864   return SQLITE_OK;
35865 }
35866 
35867 /*
35868 ** Returns non-zero if the specified path name starts with a drive letter
35869 ** followed by a colon character.
35870 */
35871 static BOOL winIsDriveLetterAndColon(
35872   const char *zPathname
35873 ){
35874   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
35875 }
35876 
35877 /*
35878 ** Returns non-zero if the specified path name should be used verbatim.  If
35879 ** non-zero is returned from this function, the calling function must simply
35880 ** use the provided path name verbatim -OR- resolve it into a full path name
35881 ** using the GetFullPathName Win32 API function (if available).
35882 */
35883 static BOOL winIsVerbatimPathname(
35884   const char *zPathname
35885 ){
35886   /*
35887   ** If the path name starts with a forward slash or a backslash, it is either
35888   ** a legal UNC name, a volume relative path, or an absolute path name in the
35889   ** "Unix" format on Windows.  There is no easy way to differentiate between
35890   ** the final two cases; therefore, we return the safer return value of TRUE
35891   ** so that callers of this function will simply use it verbatim.
35892   */
35893   if ( winIsDirSep(zPathname[0]) ){
35894     return TRUE;
35895   }
35896 
35897   /*
35898   ** If the path name starts with a letter and a colon it is either a volume
35899   ** relative path or an absolute path.  Callers of this function must not
35900   ** attempt to treat it as a relative path name (i.e. they should simply use
35901   ** it verbatim).
35902   */
35903   if ( winIsDriveLetterAndColon(zPathname) ){
35904     return TRUE;
35905   }
35906 
35907   /*
35908   ** If we get to this point, the path name should almost certainly be a purely
35909   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
35910   */
35911   return FALSE;
35912 }
35913 
35914 /*
35915 ** Turn a relative pathname into a full pathname.  Write the full
35916 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
35917 ** bytes in size.
35918 */
35919 static int winFullPathname(
35920   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35921   const char *zRelative,        /* Possibly relative input path */
35922   int nFull,                    /* Size of output buffer in bytes */
35923   char *zFull                   /* Output buffer */
35924 ){
35925   
35926 #if defined(__CYGWIN__)
35927   SimulateIOError( return SQLITE_ERROR );
35928   UNUSED_PARAMETER(nFull);
35929   assert( nFull>=pVfs->mxPathname );
35930   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35931     /*
35932     ** NOTE: We are dealing with a relative path name and the data
35933     **       directory has been set.  Therefore, use it as the basis
35934     **       for converting the relative path name to an absolute
35935     **       one by prepending the data directory and a slash.
35936     */
35937     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
35938     if( !zOut ){
35939       return SQLITE_IOERR_NOMEM;
35940     }
35941     if( cygwin_conv_path(
35942             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
35943             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
35944       sqlite3_free(zOut);
35945       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
35946                          "winFullPathname1", zRelative);
35947     }else{
35948       char *zUtf8 = winConvertToUtf8Filename(zOut);
35949       if( !zUtf8 ){
35950         sqlite3_free(zOut);
35951         return SQLITE_IOERR_NOMEM;
35952       }
35953       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
35954                        sqlite3_data_directory, winGetDirSep(), zUtf8);
35955       sqlite3_free(zUtf8);
35956       sqlite3_free(zOut);
35957     }
35958   }else{
35959     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
35960     if( !zOut ){
35961       return SQLITE_IOERR_NOMEM;
35962     }
35963     if( cygwin_conv_path(
35964             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
35965             zRelative, zOut, pVfs->mxPathname+1)<0 ){
35966       sqlite3_free(zOut);
35967       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
35968                          "winFullPathname2", zRelative);
35969     }else{
35970       char *zUtf8 = winConvertToUtf8Filename(zOut);
35971       if( !zUtf8 ){
35972         sqlite3_free(zOut);
35973         return SQLITE_IOERR_NOMEM;
35974       }
35975       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
35976       sqlite3_free(zUtf8);
35977       sqlite3_free(zOut);
35978     }
35979   }
35980   return SQLITE_OK;
35981 #endif
35982 
35983 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
35984   SimulateIOError( return SQLITE_ERROR );
35985   /* WinCE has no concept of a relative pathname, or so I am told. */
35986   /* WinRT has no way to convert a relative path to an absolute one. */
35987   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35988     /*
35989     ** NOTE: We are dealing with a relative path name and the data
35990     **       directory has been set.  Therefore, use it as the basis
35991     **       for converting the relative path name to an absolute
35992     **       one by prepending the data directory and a backslash.
35993     */
35994     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
35995                      sqlite3_data_directory, winGetDirSep(), zRelative);
35996   }else{
35997     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
35998   }
35999   return SQLITE_OK;
36000 #endif
36001 
36002 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36003   DWORD nByte;
36004   void *zConverted;
36005   char *zOut;
36006 
36007   /* If this path name begins with "/X:", where "X" is any alphabetic
36008   ** character, discard the initial "/" from the pathname.
36009   */
36010   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
36011     zRelative++;
36012   }
36013 
36014   /* It's odd to simulate an io-error here, but really this is just
36015   ** using the io-error infrastructure to test that SQLite handles this
36016   ** function failing. This function could fail if, for example, the
36017   ** current working directory has been unlinked.
36018   */
36019   SimulateIOError( return SQLITE_ERROR );
36020   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36021     /*
36022     ** NOTE: We are dealing with a relative path name and the data
36023     **       directory has been set.  Therefore, use it as the basis
36024     **       for converting the relative path name to an absolute
36025     **       one by prepending the data directory and a backslash.
36026     */
36027     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36028                      sqlite3_data_directory, winGetDirSep(), zRelative);
36029     return SQLITE_OK;
36030   }
36031   zConverted = winConvertFromUtf8Filename(zRelative);
36032   if( zConverted==0 ){
36033     return SQLITE_IOERR_NOMEM;
36034   }
36035   if( osIsNT() ){
36036     LPWSTR zTemp;
36037     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
36038     if( nByte==0 ){
36039       sqlite3_free(zConverted);
36040       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36041                          "winFullPathname1", zRelative);
36042     }
36043     nByte += 3;
36044     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36045     if( zTemp==0 ){
36046       sqlite3_free(zConverted);
36047       return SQLITE_IOERR_NOMEM;
36048     }
36049     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
36050     if( nByte==0 ){
36051       sqlite3_free(zConverted);
36052       sqlite3_free(zTemp);
36053       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36054                          "winFullPathname2", zRelative);
36055     }
36056     sqlite3_free(zConverted);
36057     zOut = winUnicodeToUtf8(zTemp);
36058     sqlite3_free(zTemp);
36059   }
36060 #ifdef SQLITE_WIN32_HAS_ANSI
36061   else{
36062     char *zTemp;
36063     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
36064     if( nByte==0 ){
36065       sqlite3_free(zConverted);
36066       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36067                          "winFullPathname3", zRelative);
36068     }
36069     nByte += 3;
36070     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36071     if( zTemp==0 ){
36072       sqlite3_free(zConverted);
36073       return SQLITE_IOERR_NOMEM;
36074     }
36075     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36076     if( nByte==0 ){
36077       sqlite3_free(zConverted);
36078       sqlite3_free(zTemp);
36079       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36080                          "winFullPathname4", zRelative);
36081     }
36082     sqlite3_free(zConverted);
36083     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36084     sqlite3_free(zTemp);
36085   }
36086 #endif
36087   if( zOut ){
36088     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
36089     sqlite3_free(zOut);
36090     return SQLITE_OK;
36091   }else{
36092     return SQLITE_IOERR_NOMEM;
36093   }
36094 #endif
36095 }
36096 
36097 #ifndef SQLITE_OMIT_LOAD_EXTENSION
36098 /*
36099 ** Interfaces for opening a shared library, finding entry points
36100 ** within the shared library, and closing the shared library.
36101 */
36102 /*
36103 ** Interfaces for opening a shared library, finding entry points
36104 ** within the shared library, and closing the shared library.
36105 */
36106 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
36107   HANDLE h;
36108   void *zConverted = winConvertFromUtf8Filename(zFilename);
36109   UNUSED_PARAMETER(pVfs);
36110   if( zConverted==0 ){
36111     return 0;
36112   }
36113   if( osIsNT() ){
36114 #if SQLITE_OS_WINRT
36115     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
36116 #else
36117     h = osLoadLibraryW((LPCWSTR)zConverted);
36118 #endif
36119   }
36120 #ifdef SQLITE_WIN32_HAS_ANSI
36121   else{
36122     h = osLoadLibraryA((char*)zConverted);
36123   }
36124 #endif
36125   sqlite3_free(zConverted);
36126   return (void*)h;
36127 }
36128 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
36129   UNUSED_PARAMETER(pVfs);
36130   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
36131 }
36132 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
36133   UNUSED_PARAMETER(pVfs);
36134   return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
36135 }
36136 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
36137   UNUSED_PARAMETER(pVfs);
36138   osFreeLibrary((HANDLE)pHandle);
36139 }
36140 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36141   #define winDlOpen  0
36142   #define winDlError 0
36143   #define winDlSym   0
36144   #define winDlClose 0
36145 #endif
36146 
36147 
36148 /*
36149 ** Write up to nBuf bytes of randomness into zBuf.
36150 */
36151 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36152   int n = 0;
36153   UNUSED_PARAMETER(pVfs);
36154 #if defined(SQLITE_TEST)
36155   n = nBuf;
36156   memset(zBuf, 0, nBuf);
36157 #else
36158   if( sizeof(SYSTEMTIME)<=nBuf-n ){
36159     SYSTEMTIME x;
36160     osGetSystemTime(&x);
36161     memcpy(&zBuf[n], &x, sizeof(x));
36162     n += sizeof(x);
36163   }
36164   if( sizeof(DWORD)<=nBuf-n ){
36165     DWORD pid = osGetCurrentProcessId();
36166     memcpy(&zBuf[n], &pid, sizeof(pid));
36167     n += sizeof(pid);
36168   }
36169 #if SQLITE_OS_WINRT
36170   if( sizeof(ULONGLONG)<=nBuf-n ){
36171     ULONGLONG cnt = osGetTickCount64();
36172     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36173     n += sizeof(cnt);
36174   }
36175 #else
36176   if( sizeof(DWORD)<=nBuf-n ){
36177     DWORD cnt = osGetTickCount();
36178     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36179     n += sizeof(cnt);
36180   }
36181 #endif
36182   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36183     LARGE_INTEGER i;
36184     osQueryPerformanceCounter(&i);
36185     memcpy(&zBuf[n], &i, sizeof(i));
36186     n += sizeof(i);
36187   }
36188 #endif
36189   return n;
36190 }
36191 
36192 
36193 /*
36194 ** Sleep for a little while.  Return the amount of time slept.
36195 */
36196 static int winSleep(sqlite3_vfs *pVfs, int microsec){
36197   sqlite3_win32_sleep((microsec+999)/1000);
36198   UNUSED_PARAMETER(pVfs);
36199   return ((microsec+999)/1000)*1000;
36200 }
36201 
36202 /*
36203 ** The following variable, if set to a non-zero value, is interpreted as
36204 ** the number of seconds since 1970 and is used to set the result of
36205 ** sqlite3OsCurrentTime() during testing.
36206 */
36207 #ifdef SQLITE_TEST
36208 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36209 #endif
36210 
36211 /*
36212 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
36213 ** the current time and date as a Julian Day number times 86_400_000.  In
36214 ** other words, write into *piNow the number of milliseconds since the Julian
36215 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36216 ** proleptic Gregorian calendar.
36217 **
36218 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
36219 ** cannot be found.
36220 */
36221 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
36222   /* FILETIME structure is a 64-bit value representing the number of 
36223      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
36224   */
36225   FILETIME ft;
36226   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
36227 #ifdef SQLITE_TEST
36228   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36229 #endif
36230   /* 2^32 - to avoid use of LL and warnings in gcc */
36231   static const sqlite3_int64 max32BitValue = 
36232       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
36233       (sqlite3_int64)294967296;
36234 
36235 #if SQLITE_OS_WINCE
36236   SYSTEMTIME time;
36237   osGetSystemTime(&time);
36238   /* if SystemTimeToFileTime() fails, it returns zero. */
36239   if (!osSystemTimeToFileTime(&time,&ft)){
36240     return SQLITE_ERROR;
36241   }
36242 #else
36243   osGetSystemTimeAsFileTime( &ft );
36244 #endif
36245 
36246   *piNow = winFiletimeEpoch +
36247             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
36248                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
36249 
36250 #ifdef SQLITE_TEST
36251   if( sqlite3_current_time ){
36252     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36253   }
36254 #endif
36255   UNUSED_PARAMETER(pVfs);
36256   return SQLITE_OK;
36257 }
36258 
36259 /*
36260 ** Find the current time (in Universal Coordinated Time).  Write the
36261 ** current time and date as a Julian Day number into *prNow and
36262 ** return 0.  Return 1 if the time and date cannot be found.
36263 */
36264 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
36265   int rc;
36266   sqlite3_int64 i;
36267   rc = winCurrentTimeInt64(pVfs, &i);
36268   if( !rc ){
36269     *prNow = i/86400000.0;
36270   }
36271   return rc;
36272 }
36273 
36274 /*
36275 ** The idea is that this function works like a combination of
36276 ** GetLastError() and FormatMessage() on Windows (or errno and
36277 ** strerror_r() on Unix). After an error is returned by an OS
36278 ** function, SQLite calls this function with zBuf pointing to
36279 ** a buffer of nBuf bytes. The OS layer should populate the
36280 ** buffer with a nul-terminated UTF-8 encoded error message
36281 ** describing the last IO error to have occurred within the calling
36282 ** thread.
36283 **
36284 ** If the error message is too large for the supplied buffer,
36285 ** it should be truncated. The return value of xGetLastError
36286 ** is zero if the error message fits in the buffer, or non-zero
36287 ** otherwise (if the message was truncated). If non-zero is returned,
36288 ** then it is not necessary to include the nul-terminator character
36289 ** in the output buffer.
36290 **
36291 ** Not supplying an error message will have no adverse effect
36292 ** on SQLite. It is fine to have an implementation that never
36293 ** returns an error message:
36294 **
36295 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36296 **     assert(zBuf[0]=='\0');
36297 **     return 0;
36298 **   }
36299 **
36300 ** However if an error message is supplied, it will be incorporated
36301 ** by sqlite into the error message available to the user using
36302 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
36303 */
36304 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36305   UNUSED_PARAMETER(pVfs);
36306   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
36307 }
36308 
36309 /*
36310 ** Initialize and deinitialize the operating system interface.
36311 */
36312 SQLITE_API int sqlite3_os_init(void){
36313   static sqlite3_vfs winVfs = {
36314     3,                   /* iVersion */
36315     sizeof(winFile),     /* szOsFile */
36316     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
36317     0,                   /* pNext */
36318     "win32",             /* zName */
36319     0,                   /* pAppData */
36320     winOpen,             /* xOpen */
36321     winDelete,           /* xDelete */
36322     winAccess,           /* xAccess */
36323     winFullPathname,     /* xFullPathname */
36324     winDlOpen,           /* xDlOpen */
36325     winDlError,          /* xDlError */
36326     winDlSym,            /* xDlSym */
36327     winDlClose,          /* xDlClose */
36328     winRandomness,       /* xRandomness */
36329     winSleep,            /* xSleep */
36330     winCurrentTime,      /* xCurrentTime */
36331     winGetLastError,     /* xGetLastError */
36332     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36333     winSetSystemCall,    /* xSetSystemCall */
36334     winGetSystemCall,    /* xGetSystemCall */
36335     winNextSystemCall,   /* xNextSystemCall */
36336   };
36337 #if defined(SQLITE_WIN32_HAS_WIDE)
36338   static sqlite3_vfs winLongPathVfs = {
36339     3,                   /* iVersion */
36340     sizeof(winFile),     /* szOsFile */
36341     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
36342     0,                   /* pNext */
36343     "win32-longpath",    /* zName */
36344     0,                   /* pAppData */
36345     winOpen,             /* xOpen */
36346     winDelete,           /* xDelete */
36347     winAccess,           /* xAccess */
36348     winFullPathname,     /* xFullPathname */
36349     winDlOpen,           /* xDlOpen */
36350     winDlError,          /* xDlError */
36351     winDlSym,            /* xDlSym */
36352     winDlClose,          /* xDlClose */
36353     winRandomness,       /* xRandomness */
36354     winSleep,            /* xSleep */
36355     winCurrentTime,      /* xCurrentTime */
36356     winGetLastError,     /* xGetLastError */
36357     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36358     winSetSystemCall,    /* xSetSystemCall */
36359     winGetSystemCall,    /* xGetSystemCall */
36360     winNextSystemCall,   /* xNextSystemCall */
36361   };
36362 #endif
36363 
36364   /* Double-check that the aSyscall[] array has been constructed
36365   ** correctly.  See ticket [bb3a86e890c8e96ab] */
36366   assert( ArraySize(aSyscall)==76 );
36367 
36368   /* get memory map allocation granularity */
36369   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36370 #if SQLITE_OS_WINRT
36371   osGetNativeSystemInfo(&winSysInfo);
36372 #else
36373   osGetSystemInfo(&winSysInfo);
36374 #endif
36375   assert( winSysInfo.dwAllocationGranularity>0 );
36376   assert( winSysInfo.dwPageSize>0 );
36377 
36378   sqlite3_vfs_register(&winVfs, 1);
36379 
36380 #if defined(SQLITE_WIN32_HAS_WIDE)
36381   sqlite3_vfs_register(&winLongPathVfs, 0);
36382 #endif
36383 
36384   return SQLITE_OK; 
36385 }
36386 
36387 SQLITE_API int sqlite3_os_end(void){ 
36388 #if SQLITE_OS_WINRT
36389   if( sleepObj!=NULL ){
36390     osCloseHandle(sleepObj);
36391     sleepObj = NULL;
36392   }
36393 #endif
36394   return SQLITE_OK;
36395 }
36396 
36397 #endif /* SQLITE_OS_WIN */
36398 
36399 /************** End of os_win.c **********************************************/
36400 /************** Begin file bitvec.c ******************************************/
36401 /*
36402 ** 2008 February 16
36403 **
36404 ** The author disclaims copyright to this source code.  In place of
36405 ** a legal notice, here is a blessing:
36406 **
36407 **    May you do good and not evil.
36408 **    May you find forgiveness for yourself and forgive others.
36409 **    May you share freely, never taking more than you give.
36410 **
36411 *************************************************************************
36412 ** This file implements an object that represents a fixed-length
36413 ** bitmap.  Bits are numbered starting with 1.
36414 **
36415 ** A bitmap is used to record which pages of a database file have been
36416 ** journalled during a transaction, or which pages have the "dont-write"
36417 ** property.  Usually only a few pages are meet either condition.
36418 ** So the bitmap is usually sparse and has low cardinality.
36419 ** But sometimes (for example when during a DROP of a large table) most
36420 ** or all of the pages in a database can get journalled.  In those cases, 
36421 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
36422 ** to handle both cases well.
36423 **
36424 ** The size of the bitmap is fixed when the object is created.
36425 **
36426 ** All bits are clear when the bitmap is created.  Individual bits
36427 ** may be set or cleared one at a time.
36428 **
36429 ** Test operations are about 100 times more common that set operations.
36430 ** Clear operations are exceedingly rare.  There are usually between
36431 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36432 ** sometimes grow into tens of thousands or larger.  The size of the
36433 ** Bitvec object is the number of pages in the database file at the
36434 ** start of a transaction, and is thus usually less than a few thousand,
36435 ** but can be as large as 2 billion for a really big database.
36436 */
36437 
36438 /* Size of the Bitvec structure in bytes. */
36439 #define BITVEC_SZ        512
36440 
36441 /* Round the union size down to the nearest pointer boundary, since that's how 
36442 ** it will be aligned within the Bitvec struct. */
36443 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36444 
36445 /* Type of the array "element" for the bitmap representation. 
36446 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
36447 ** Setting this to the "natural word" size of your CPU may improve
36448 ** performance. */
36449 #define BITVEC_TELEM     u8
36450 /* Size, in bits, of the bitmap element. */
36451 #define BITVEC_SZELEM    8
36452 /* Number of elements in a bitmap array. */
36453 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36454 /* Number of bits in the bitmap array. */
36455 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
36456 
36457 /* Number of u32 values in hash table. */
36458 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
36459 /* Maximum number of entries in hash table before 
36460 ** sub-dividing and re-hashing. */
36461 #define BITVEC_MXHASH    (BITVEC_NINT/2)
36462 /* Hashing function for the aHash representation.
36463 ** Empirical testing showed that the *37 multiplier 
36464 ** (an arbitrary prime)in the hash function provided 
36465 ** no fewer collisions than the no-op *1. */
36466 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
36467 
36468 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
36469 
36470 
36471 /*
36472 ** A bitmap is an instance of the following structure.
36473 **
36474 ** This bitmap records the existence of zero or more bits
36475 ** with values between 1 and iSize, inclusive.
36476 **
36477 ** There are three possible representations of the bitmap.
36478 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
36479 ** bitmap.  The least significant bit is bit 1.
36480 **
36481 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
36482 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
36483 **
36484 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
36485 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
36486 ** handles up to iDivisor separate values of i.  apSub[0] holds
36487 ** values between 1 and iDivisor.  apSub[1] holds values between
36488 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
36489 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
36490 ** to hold deal with values between 1 and iDivisor.
36491 */
36492 struct Bitvec {
36493   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
36494   u32 nSet;       /* Number of bits that are set - only valid for aHash
36495                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
36496                   ** this would be 125. */
36497   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
36498                   /* Should >=0 for apSub element. */
36499                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
36500                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
36501   union {
36502     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
36503     u32 aHash[BITVEC_NINT];      /* Hash table representation */
36504     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
36505   } u;
36506 };
36507 
36508 /*
36509 ** Create a new bitmap object able to handle bits between 0 and iSize,
36510 ** inclusive.  Return a pointer to the new object.  Return NULL if 
36511 ** malloc fails.
36512 */
36513 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
36514   Bitvec *p;
36515   assert( sizeof(*p)==BITVEC_SZ );
36516   p = sqlite3MallocZero( sizeof(*p) );
36517   if( p ){
36518     p->iSize = iSize;
36519   }
36520   return p;
36521 }
36522 
36523 /*
36524 ** Check to see if the i-th bit is set.  Return true or false.
36525 ** If p is NULL (if the bitmap has not been created) or if
36526 ** i is out of range, then return false.
36527 */
36528 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
36529   if( p==0 ) return 0;
36530   if( i>p->iSize || i==0 ) return 0;
36531   i--;
36532   while( p->iDivisor ){
36533     u32 bin = i/p->iDivisor;
36534     i = i%p->iDivisor;
36535     p = p->u.apSub[bin];
36536     if (!p) {
36537       return 0;
36538     }
36539   }
36540   if( p->iSize<=BITVEC_NBIT ){
36541     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
36542   } else{
36543     u32 h = BITVEC_HASH(i++);
36544     while( p->u.aHash[h] ){
36545       if( p->u.aHash[h]==i ) return 1;
36546       h = (h+1) % BITVEC_NINT;
36547     }
36548     return 0;
36549   }
36550 }
36551 
36552 /*
36553 ** Set the i-th bit.  Return 0 on success and an error code if
36554 ** anything goes wrong.
36555 **
36556 ** This routine might cause sub-bitmaps to be allocated.  Failing
36557 ** to get the memory needed to hold the sub-bitmap is the only
36558 ** that can go wrong with an insert, assuming p and i are valid.
36559 **
36560 ** The calling function must ensure that p is a valid Bitvec object
36561 ** and that the value for "i" is within range of the Bitvec object.
36562 ** Otherwise the behavior is undefined.
36563 */
36564 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
36565   u32 h;
36566   if( p==0 ) return SQLITE_OK;
36567   assert( i>0 );
36568   assert( i<=p->iSize );
36569   i--;
36570   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
36571     u32 bin = i/p->iDivisor;
36572     i = i%p->iDivisor;
36573     if( p->u.apSub[bin]==0 ){
36574       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
36575       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
36576     }
36577     p = p->u.apSub[bin];
36578   }
36579   if( p->iSize<=BITVEC_NBIT ){
36580     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
36581     return SQLITE_OK;
36582   }
36583   h = BITVEC_HASH(i++);
36584   /* if there wasn't a hash collision, and this doesn't */
36585   /* completely fill the hash, then just add it without */
36586   /* worring about sub-dividing and re-hashing. */
36587   if( !p->u.aHash[h] ){
36588     if (p->nSet<(BITVEC_NINT-1)) {
36589       goto bitvec_set_end;
36590     } else {
36591       goto bitvec_set_rehash;
36592     }
36593   }
36594   /* there was a collision, check to see if it's already */
36595   /* in hash, if not, try to find a spot for it */
36596   do {
36597     if( p->u.aHash[h]==i ) return SQLITE_OK;
36598     h++;
36599     if( h>=BITVEC_NINT ) h = 0;
36600   } while( p->u.aHash[h] );
36601   /* we didn't find it in the hash.  h points to the first */
36602   /* available free spot. check to see if this is going to */
36603   /* make our hash too "full".  */
36604 bitvec_set_rehash:
36605   if( p->nSet>=BITVEC_MXHASH ){
36606     unsigned int j;
36607     int rc;
36608     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
36609     if( aiValues==0 ){
36610       return SQLITE_NOMEM;
36611     }else{
36612       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36613       memset(p->u.apSub, 0, sizeof(p->u.apSub));
36614       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
36615       rc = sqlite3BitvecSet(p, i);
36616       for(j=0; j<BITVEC_NINT; j++){
36617         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
36618       }
36619       sqlite3StackFree(0, aiValues);
36620       return rc;
36621     }
36622   }
36623 bitvec_set_end:
36624   p->nSet++;
36625   p->u.aHash[h] = i;
36626   return SQLITE_OK;
36627 }
36628 
36629 /*
36630 ** Clear the i-th bit.
36631 **
36632 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
36633 ** that BitvecClear can use to rebuilt its hash table.
36634 */
36635 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
36636   if( p==0 ) return;
36637   assert( i>0 );
36638   i--;
36639   while( p->iDivisor ){
36640     u32 bin = i/p->iDivisor;
36641     i = i%p->iDivisor;
36642     p = p->u.apSub[bin];
36643     if (!p) {
36644       return;
36645     }
36646   }
36647   if( p->iSize<=BITVEC_NBIT ){
36648     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
36649   }else{
36650     unsigned int j;
36651     u32 *aiValues = pBuf;
36652     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36653     memset(p->u.aHash, 0, sizeof(p->u.aHash));
36654     p->nSet = 0;
36655     for(j=0; j<BITVEC_NINT; j++){
36656       if( aiValues[j] && aiValues[j]!=(i+1) ){
36657         u32 h = BITVEC_HASH(aiValues[j]-1);
36658         p->nSet++;
36659         while( p->u.aHash[h] ){
36660           h++;
36661           if( h>=BITVEC_NINT ) h = 0;
36662         }
36663         p->u.aHash[h] = aiValues[j];
36664       }
36665     }
36666   }
36667 }
36668 
36669 /*
36670 ** Destroy a bitmap object.  Reclaim all memory used.
36671 */
36672 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
36673   if( p==0 ) return;
36674   if( p->iDivisor ){
36675     unsigned int i;
36676     for(i=0; i<BITVEC_NPTR; i++){
36677       sqlite3BitvecDestroy(p->u.apSub[i]);
36678     }
36679   }
36680   sqlite3_free(p);
36681 }
36682 
36683 /*
36684 ** Return the value of the iSize parameter specified when Bitvec *p
36685 ** was created.
36686 */
36687 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
36688   return p->iSize;
36689 }
36690 
36691 #ifndef SQLITE_OMIT_BUILTIN_TEST
36692 /*
36693 ** Let V[] be an array of unsigned characters sufficient to hold
36694 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
36695 ** Then the following macros can be used to set, clear, or test
36696 ** individual bits within V.
36697 */
36698 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
36699 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
36700 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
36701 
36702 /*
36703 ** This routine runs an extensive test of the Bitvec code.
36704 **
36705 ** The input is an array of integers that acts as a program
36706 ** to test the Bitvec.  The integers are opcodes followed
36707 ** by 0, 1, or 3 operands, depending on the opcode.  Another
36708 ** opcode follows immediately after the last operand.
36709 **
36710 ** There are 6 opcodes numbered from 0 through 5.  0 is the
36711 ** "halt" opcode and causes the test to end.
36712 **
36713 **    0          Halt and return the number of errors
36714 **    1 N S X    Set N bits beginning with S and incrementing by X
36715 **    2 N S X    Clear N bits beginning with S and incrementing by X
36716 **    3 N        Set N randomly chosen bits
36717 **    4 N        Clear N randomly chosen bits
36718 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
36719 **
36720 ** The opcodes 1 through 4 perform set and clear operations are performed
36721 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
36722 ** Opcode 5 works on the linear array only, not on the Bitvec.
36723 ** Opcode 5 is used to deliberately induce a fault in order to
36724 ** confirm that error detection works.
36725 **
36726 ** At the conclusion of the test the linear array is compared
36727 ** against the Bitvec object.  If there are any differences,
36728 ** an error is returned.  If they are the same, zero is returned.
36729 **
36730 ** If a memory allocation error occurs, return -1.
36731 */
36732 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
36733   Bitvec *pBitvec = 0;
36734   unsigned char *pV = 0;
36735   int rc = -1;
36736   int i, nx, pc, op;
36737   void *pTmpSpace;
36738 
36739   /* Allocate the Bitvec to be tested and a linear array of
36740   ** bits to act as the reference */
36741   pBitvec = sqlite3BitvecCreate( sz );
36742   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
36743   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
36744   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
36745 
36746   /* NULL pBitvec tests */
36747   sqlite3BitvecSet(0, 1);
36748   sqlite3BitvecClear(0, 1, pTmpSpace);
36749 
36750   /* Run the program */
36751   pc = 0;
36752   while( (op = aOp[pc])!=0 ){
36753     switch( op ){
36754       case 1:
36755       case 2:
36756       case 5: {
36757         nx = 4;
36758         i = aOp[pc+2] - 1;
36759         aOp[pc+2] += aOp[pc+3];
36760         break;
36761       }
36762       case 3:
36763       case 4: 
36764       default: {
36765         nx = 2;
36766         sqlite3_randomness(sizeof(i), &i);
36767         break;
36768       }
36769     }
36770     if( (--aOp[pc+1]) > 0 ) nx = 0;
36771     pc += nx;
36772     i = (i & 0x7fffffff)%sz;
36773     if( (op & 1)!=0 ){
36774       SETBIT(pV, (i+1));
36775       if( op!=5 ){
36776         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36777       }
36778     }else{
36779       CLEARBIT(pV, (i+1));
36780       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36781     }
36782   }
36783 
36784   /* Test to make sure the linear array exactly matches the
36785   ** Bitvec object.  Start with the assumption that they do
36786   ** match (rc==0).  Change rc to non-zero if a discrepancy
36787   ** is found.
36788   */
36789   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36790           + sqlite3BitvecTest(pBitvec, 0)
36791           + (sqlite3BitvecSize(pBitvec) - sz);
36792   for(i=1; i<=sz; i++){
36793     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36794       rc = i;
36795       break;
36796     }
36797   }
36798 
36799   /* Free allocated structure */
36800 bitvec_end:
36801   sqlite3_free(pTmpSpace);
36802   sqlite3_free(pV);
36803   sqlite3BitvecDestroy(pBitvec);
36804   return rc;
36805 }
36806 #endif /* SQLITE_OMIT_BUILTIN_TEST */
36807 
36808 /************** End of bitvec.c **********************************************/
36809 /************** Begin file pcache.c ******************************************/
36810 /*
36811 ** 2008 August 05
36812 **
36813 ** The author disclaims copyright to this source code.  In place of
36814 ** a legal notice, here is a blessing:
36815 **
36816 **    May you do good and not evil.
36817 **    May you find forgiveness for yourself and forgive others.
36818 **    May you share freely, never taking more than you give.
36819 **
36820 *************************************************************************
36821 ** This file implements that page cache.
36822 */
36823 
36824 /*
36825 ** A complete page cache is an instance of this structure.
36826 */
36827 struct PCache {
36828   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36829   PgHdr *pSynced;                     /* Last synced page in dirty page list */
36830   int nRef;                           /* Number of referenced pages */
36831   int szCache;                        /* Configured cache size */
36832   int szPage;                         /* Size of every page in this cache */
36833   int szExtra;                        /* Size of extra space for each page */
36834   int bPurgeable;                     /* True if pages are on backing store */
36835   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36836   void *pStress;                      /* Argument to xStress */
36837   sqlite3_pcache *pCache;             /* Pluggable cache module */
36838   PgHdr *pPage1;                      /* Reference to page 1 */
36839 };
36840 
36841 /*
36842 ** Some of the assert() macros in this code are too expensive to run
36843 ** even during normal debugging.  Use them only rarely on long-running
36844 ** tests.  Enable the expensive asserts using the
36845 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36846 */
36847 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36848 # define expensive_assert(X)  assert(X)
36849 #else
36850 # define expensive_assert(X)
36851 #endif
36852 
36853 /********************************** Linked List Management ********************/
36854 
36855 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36856 /*
36857 ** Check that the pCache->pSynced variable is set correctly. If it
36858 ** is not, either fail an assert or return zero. Otherwise, return
36859 ** non-zero. This is only used in debugging builds, as follows:
36860 **
36861 **   expensive_assert( pcacheCheckSynced(pCache) );
36862 */
36863 static int pcacheCheckSynced(PCache *pCache){
36864   PgHdr *p;
36865   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36866     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36867   }
36868   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36869 }
36870 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36871 
36872 /*
36873 ** Remove page pPage from the list of dirty pages.
36874 */
36875 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36876   PCache *p = pPage->pCache;
36877 
36878   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36879   assert( pPage->pDirtyPrev || pPage==p->pDirty );
36880 
36881   /* Update the PCache1.pSynced variable if necessary. */
36882   if( p->pSynced==pPage ){
36883     PgHdr *pSynced = pPage->pDirtyPrev;
36884     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36885       pSynced = pSynced->pDirtyPrev;
36886     }
36887     p->pSynced = pSynced;
36888   }
36889 
36890   if( pPage->pDirtyNext ){
36891     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36892   }else{
36893     assert( pPage==p->pDirtyTail );
36894     p->pDirtyTail = pPage->pDirtyPrev;
36895   }
36896   if( pPage->pDirtyPrev ){
36897     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36898   }else{
36899     assert( pPage==p->pDirty );
36900     p->pDirty = pPage->pDirtyNext;
36901   }
36902   pPage->pDirtyNext = 0;
36903   pPage->pDirtyPrev = 0;
36904 
36905   expensive_assert( pcacheCheckSynced(p) );
36906 }
36907 
36908 /*
36909 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36910 ** pPage).
36911 */
36912 static void pcacheAddToDirtyList(PgHdr *pPage){
36913   PCache *p = pPage->pCache;
36914 
36915   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36916 
36917   pPage->pDirtyNext = p->pDirty;
36918   if( pPage->pDirtyNext ){
36919     assert( pPage->pDirtyNext->pDirtyPrev==0 );
36920     pPage->pDirtyNext->pDirtyPrev = pPage;
36921   }
36922   p->pDirty = pPage;
36923   if( !p->pDirtyTail ){
36924     p->pDirtyTail = pPage;
36925   }
36926   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36927     p->pSynced = pPage;
36928   }
36929   expensive_assert( pcacheCheckSynced(p) );
36930 }
36931 
36932 /*
36933 ** Wrapper around the pluggable caches xUnpin method. If the cache is
36934 ** being used for an in-memory database, this function is a no-op.
36935 */
36936 static void pcacheUnpin(PgHdr *p){
36937   PCache *pCache = p->pCache;
36938   if( pCache->bPurgeable ){
36939     if( p->pgno==1 ){
36940       pCache->pPage1 = 0;
36941     }
36942     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36943   }
36944 }
36945 
36946 /*************************************************** General Interfaces ******
36947 **
36948 ** Initialize and shutdown the page cache subsystem. Neither of these 
36949 ** functions are threadsafe.
36950 */
36951 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36952   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36953     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36954     ** built-in default page cache is used instead of the application defined
36955     ** page cache. */
36956     sqlite3PCacheSetDefault();
36957   }
36958   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36959 }
36960 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36961   if( sqlite3GlobalConfig.pcache2.xShutdown ){
36962     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36963     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36964   }
36965 }
36966 
36967 /*
36968 ** Return the size in bytes of a PCache object.
36969 */
36970 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36971 
36972 /*
36973 ** Create a new PCache object. Storage space to hold the object
36974 ** has already been allocated and is passed in as the p pointer. 
36975 ** The caller discovers how much space needs to be allocated by 
36976 ** calling sqlite3PcacheSize().
36977 */
36978 SQLITE_PRIVATE void sqlite3PcacheOpen(
36979   int szPage,                  /* Size of every page */
36980   int szExtra,                 /* Extra space associated with each page */
36981   int bPurgeable,              /* True if pages are on backing store */
36982   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36983   void *pStress,               /* Argument to xStress */
36984   PCache *p                    /* Preallocated space for the PCache */
36985 ){
36986   memset(p, 0, sizeof(PCache));
36987   p->szPage = szPage;
36988   p->szExtra = szExtra;
36989   p->bPurgeable = bPurgeable;
36990   p->xStress = xStress;
36991   p->pStress = pStress;
36992   p->szCache = 100;
36993 }
36994 
36995 /*
36996 ** Change the page size for PCache object. The caller must ensure that there
36997 ** are no outstanding page references when this function is called.
36998 */
36999 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
37000   assert( pCache->nRef==0 && pCache->pDirty==0 );
37001   if( pCache->pCache ){
37002     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37003     pCache->pCache = 0;
37004     pCache->pPage1 = 0;
37005   }
37006   pCache->szPage = szPage;
37007 }
37008 
37009 /*
37010 ** Compute the number of pages of cache requested.
37011 */
37012 static int numberOfCachePages(PCache *p){
37013   if( p->szCache>=0 ){
37014     return p->szCache;
37015   }else{
37016     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
37017   }
37018 }
37019 
37020 /*
37021 ** Try to obtain a page from the cache.
37022 */
37023 SQLITE_PRIVATE int sqlite3PcacheFetch(
37024   PCache *pCache,       /* Obtain the page from this cache */
37025   Pgno pgno,            /* Page number to obtain */
37026   int createFlag,       /* If true, create page if it does not exist already */
37027   PgHdr **ppPage        /* Write the page here */
37028 ){
37029   sqlite3_pcache_page *pPage = 0;
37030   PgHdr *pPgHdr = 0;
37031   int eCreate;
37032 
37033   assert( pCache!=0 );
37034   assert( createFlag==1 || createFlag==0 );
37035   assert( pgno>0 );
37036 
37037   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
37038   ** allocate it now.
37039   */
37040   if( !pCache->pCache && createFlag ){
37041     sqlite3_pcache *p;
37042     p = sqlite3GlobalConfig.pcache2.xCreate(
37043         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
37044     );
37045     if( !p ){
37046       return SQLITE_NOMEM;
37047     }
37048     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
37049     pCache->pCache = p;
37050   }
37051 
37052   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37053   if( pCache->pCache ){
37054     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
37055   }
37056 
37057   if( !pPage && eCreate==1 ){
37058     PgHdr *pPg;
37059 
37060     /* Find a dirty page to write-out and recycle. First try to find a 
37061     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37062     ** cleared), but if that is not possible settle for any other 
37063     ** unreferenced dirty page.
37064     */
37065     expensive_assert( pcacheCheckSynced(pCache) );
37066     for(pPg=pCache->pSynced; 
37067         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
37068         pPg=pPg->pDirtyPrev
37069     );
37070     pCache->pSynced = pPg;
37071     if( !pPg ){
37072       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37073     }
37074     if( pPg ){
37075       int rc;
37076 #ifdef SQLITE_LOG_CACHE_SPILL
37077       sqlite3_log(SQLITE_FULL, 
37078                   "spill page %d making room for %d - cache used: %d/%d",
37079                   pPg->pgno, pgno,
37080                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
37081                   numberOfCachePages(pCache));
37082 #endif
37083       rc = pCache->xStress(pCache->pStress, pPg);
37084       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
37085         return rc;
37086       }
37087     }
37088 
37089     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
37090   }
37091 
37092   if( pPage ){
37093     pPgHdr = (PgHdr *)pPage->pExtra;
37094 
37095     if( !pPgHdr->pPage ){
37096       memset(pPgHdr, 0, sizeof(PgHdr));
37097       pPgHdr->pPage = pPage;
37098       pPgHdr->pData = pPage->pBuf;
37099       pPgHdr->pExtra = (void *)&pPgHdr[1];
37100       memset(pPgHdr->pExtra, 0, pCache->szExtra);
37101       pPgHdr->pCache = pCache;
37102       pPgHdr->pgno = pgno;
37103     }
37104     assert( pPgHdr->pCache==pCache );
37105     assert( pPgHdr->pgno==pgno );
37106     assert( pPgHdr->pData==pPage->pBuf );
37107     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
37108 
37109     if( 0==pPgHdr->nRef ){
37110       pCache->nRef++;
37111     }
37112     pPgHdr->nRef++;
37113     if( pgno==1 ){
37114       pCache->pPage1 = pPgHdr;
37115     }
37116   }
37117   *ppPage = pPgHdr;
37118   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
37119 }
37120 
37121 /*
37122 ** Decrement the reference count on a page. If the page is clean and the
37123 ** reference count drops to 0, then it is made elible for recycling.
37124 */
37125 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
37126   assert( p->nRef>0 );
37127   p->nRef--;
37128   if( p->nRef==0 ){
37129     PCache *pCache = p->pCache;
37130     pCache->nRef--;
37131     if( (p->flags&PGHDR_DIRTY)==0 ){
37132       pcacheUnpin(p);
37133     }else{
37134       /* Move the page to the head of the dirty list. */
37135       pcacheRemoveFromDirtyList(p);
37136       pcacheAddToDirtyList(p);
37137     }
37138   }
37139 }
37140 
37141 /*
37142 ** Increase the reference count of a supplied page by 1.
37143 */
37144 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
37145   assert(p->nRef>0);
37146   p->nRef++;
37147 }
37148 
37149 /*
37150 ** Drop a page from the cache. There must be exactly one reference to the
37151 ** page. This function deletes that reference, so after it returns the
37152 ** page pointed to by p is invalid.
37153 */
37154 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
37155   PCache *pCache;
37156   assert( p->nRef==1 );
37157   if( p->flags&PGHDR_DIRTY ){
37158     pcacheRemoveFromDirtyList(p);
37159   }
37160   pCache = p->pCache;
37161   pCache->nRef--;
37162   if( p->pgno==1 ){
37163     pCache->pPage1 = 0;
37164   }
37165   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
37166 }
37167 
37168 /*
37169 ** Make sure the page is marked as dirty. If it isn't dirty already,
37170 ** make it so.
37171 */
37172 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
37173   p->flags &= ~PGHDR_DONT_WRITE;
37174   assert( p->nRef>0 );
37175   if( 0==(p->flags & PGHDR_DIRTY) ){
37176     p->flags |= PGHDR_DIRTY;
37177     pcacheAddToDirtyList( p);
37178   }
37179 }
37180 
37181 /*
37182 ** Make sure the page is marked as clean. If it isn't clean already,
37183 ** make it so.
37184 */
37185 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
37186   if( (p->flags & PGHDR_DIRTY) ){
37187     pcacheRemoveFromDirtyList(p);
37188     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37189     if( p->nRef==0 ){
37190       pcacheUnpin(p);
37191     }
37192   }
37193 }
37194 
37195 /*
37196 ** Make every page in the cache clean.
37197 */
37198 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
37199   PgHdr *p;
37200   while( (p = pCache->pDirty)!=0 ){
37201     sqlite3PcacheMakeClean(p);
37202   }
37203 }
37204 
37205 /*
37206 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37207 */
37208 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
37209   PgHdr *p;
37210   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37211     p->flags &= ~PGHDR_NEED_SYNC;
37212   }
37213   pCache->pSynced = pCache->pDirtyTail;
37214 }
37215 
37216 /*
37217 ** Change the page number of page p to newPgno. 
37218 */
37219 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
37220   PCache *pCache = p->pCache;
37221   assert( p->nRef>0 );
37222   assert( newPgno>0 );
37223   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
37224   p->pgno = newPgno;
37225   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37226     pcacheRemoveFromDirtyList(p);
37227     pcacheAddToDirtyList(p);
37228   }
37229 }
37230 
37231 /*
37232 ** Drop every cache entry whose page number is greater than "pgno". The
37233 ** caller must ensure that there are no outstanding references to any pages
37234 ** other than page 1 with a page number greater than pgno.
37235 **
37236 ** If there is a reference to page 1 and the pgno parameter passed to this
37237 ** function is 0, then the data area associated with page 1 is zeroed, but
37238 ** the page object is not dropped.
37239 */
37240 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
37241   if( pCache->pCache ){
37242     PgHdr *p;
37243     PgHdr *pNext;
37244     for(p=pCache->pDirty; p; p=pNext){
37245       pNext = p->pDirtyNext;
37246       /* This routine never gets call with a positive pgno except right
37247       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
37248       ** it must be that pgno==0.
37249       */
37250       assert( p->pgno>0 );
37251       if( ALWAYS(p->pgno>pgno) ){
37252         assert( p->flags&PGHDR_DIRTY );
37253         sqlite3PcacheMakeClean(p);
37254       }
37255     }
37256     if( pgno==0 && pCache->pPage1 ){
37257       memset(pCache->pPage1->pData, 0, pCache->szPage);
37258       pgno = 1;
37259     }
37260     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
37261   }
37262 }
37263 
37264 /*
37265 ** Close a cache.
37266 */
37267 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
37268   if( pCache->pCache ){
37269     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37270   }
37271 }
37272 
37273 /* 
37274 ** Discard the contents of the cache.
37275 */
37276 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
37277   sqlite3PcacheTruncate(pCache, 0);
37278 }
37279 
37280 /*
37281 ** Merge two lists of pages connected by pDirty and in pgno order.
37282 ** Do not both fixing the pDirtyPrev pointers.
37283 */
37284 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37285   PgHdr result, *pTail;
37286   pTail = &result;
37287   while( pA && pB ){
37288     if( pA->pgno<pB->pgno ){
37289       pTail->pDirty = pA;
37290       pTail = pA;
37291       pA = pA->pDirty;
37292     }else{
37293       pTail->pDirty = pB;
37294       pTail = pB;
37295       pB = pB->pDirty;
37296     }
37297   }
37298   if( pA ){
37299     pTail->pDirty = pA;
37300   }else if( pB ){
37301     pTail->pDirty = pB;
37302   }else{
37303     pTail->pDirty = 0;
37304   }
37305   return result.pDirty;
37306 }
37307 
37308 /*
37309 ** Sort the list of pages in accending order by pgno.  Pages are
37310 ** connected by pDirty pointers.  The pDirtyPrev pointers are
37311 ** corrupted by this sort.
37312 **
37313 ** Since there cannot be more than 2^31 distinct pages in a database,
37314 ** there cannot be more than 31 buckets required by the merge sorter.
37315 ** One extra bucket is added to catch overflow in case something
37316 ** ever changes to make the previous sentence incorrect.
37317 */
37318 #define N_SORT_BUCKET  32
37319 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37320   PgHdr *a[N_SORT_BUCKET], *p;
37321   int i;
37322   memset(a, 0, sizeof(a));
37323   while( pIn ){
37324     p = pIn;
37325     pIn = p->pDirty;
37326     p->pDirty = 0;
37327     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37328       if( a[i]==0 ){
37329         a[i] = p;
37330         break;
37331       }else{
37332         p = pcacheMergeDirtyList(a[i], p);
37333         a[i] = 0;
37334       }
37335     }
37336     if( NEVER(i==N_SORT_BUCKET-1) ){
37337       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37338       ** the input list.  But that is impossible.
37339       */
37340       a[i] = pcacheMergeDirtyList(a[i], p);
37341     }
37342   }
37343   p = a[0];
37344   for(i=1; i<N_SORT_BUCKET; i++){
37345     p = pcacheMergeDirtyList(p, a[i]);
37346   }
37347   return p;
37348 }
37349 
37350 /*
37351 ** Return a list of all dirty pages in the cache, sorted by page number.
37352 */
37353 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
37354   PgHdr *p;
37355   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37356     p->pDirty = p->pDirtyNext;
37357   }
37358   return pcacheSortDirtyList(pCache->pDirty);
37359 }
37360 
37361 /* 
37362 ** Return the total number of referenced pages held by the cache.
37363 */
37364 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
37365   return pCache->nRef;
37366 }
37367 
37368 /*
37369 ** Return the number of references to the page supplied as an argument.
37370 */
37371 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
37372   return p->nRef;
37373 }
37374 
37375 /* 
37376 ** Return the total number of pages in the cache.
37377 */
37378 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
37379   int nPage = 0;
37380   if( pCache->pCache ){
37381     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
37382   }
37383   return nPage;
37384 }
37385 
37386 #ifdef SQLITE_TEST
37387 /*
37388 ** Get the suggested cache-size value.
37389 */
37390 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
37391   return numberOfCachePages(pCache);
37392 }
37393 #endif
37394 
37395 /*
37396 ** Set the suggested cache-size value.
37397 */
37398 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
37399   pCache->szCache = mxPage;
37400   if( pCache->pCache ){
37401     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
37402                                            numberOfCachePages(pCache));
37403   }
37404 }
37405 
37406 /*
37407 ** Free up as much memory as possible from the page cache.
37408 */
37409 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
37410   if( pCache->pCache ){
37411     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
37412   }
37413 }
37414 
37415 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
37416 /*
37417 ** For all dirty pages currently in the cache, invoke the specified
37418 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
37419 ** defined.
37420 */
37421 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37422   PgHdr *pDirty;
37423   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37424     xIter(pDirty);
37425   }
37426 }
37427 #endif
37428 
37429 /************** End of pcache.c **********************************************/
37430 /************** Begin file pcache1.c *****************************************/
37431 /*
37432 ** 2008 November 05
37433 **
37434 ** The author disclaims copyright to this source code.  In place of
37435 ** a legal notice, here is a blessing:
37436 **
37437 **    May you do good and not evil.
37438 **    May you find forgiveness for yourself and forgive others.
37439 **    May you share freely, never taking more than you give.
37440 **
37441 *************************************************************************
37442 **
37443 ** This file implements the default page cache implementation (the
37444 ** sqlite3_pcache interface). It also contains part of the implementation
37445 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
37446 ** If the default page cache implementation is overriden, then neither of
37447 ** these two features are available.
37448 */
37449 
37450 
37451 typedef struct PCache1 PCache1;
37452 typedef struct PgHdr1 PgHdr1;
37453 typedef struct PgFreeslot PgFreeslot;
37454 typedef struct PGroup PGroup;
37455 
37456 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
37457 ** of one or more PCaches that are able to recycle each others unpinned
37458 ** pages when they are under memory pressure.  A PGroup is an instance of
37459 ** the following object.
37460 **
37461 ** This page cache implementation works in one of two modes:
37462 **
37463 **   (1)  Every PCache is the sole member of its own PGroup.  There is
37464 **        one PGroup per PCache.
37465 **
37466 **   (2)  There is a single global PGroup that all PCaches are a member
37467 **        of.
37468 **
37469 ** Mode 1 uses more memory (since PCache instances are not able to rob
37470 ** unused pages from other PCaches) but it also operates without a mutex,
37471 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
37472 ** threadsafe, but recycles pages more efficiently.
37473 **
37474 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
37475 ** PGroup which is the pcache1.grp global variable and its mutex is
37476 ** SQLITE_MUTEX_STATIC_LRU.
37477 */
37478 struct PGroup {
37479   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
37480   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
37481   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
37482   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
37483   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
37484   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
37485 };
37486 
37487 /* Each page cache is an instance of the following object.  Every
37488 ** open database file (including each in-memory database and each
37489 ** temporary or transient database) has a single page cache which
37490 ** is an instance of this object.
37491 **
37492 ** Pointers to structures of this type are cast and returned as 
37493 ** opaque sqlite3_pcache* handles.
37494 */
37495 struct PCache1 {
37496   /* Cache configuration parameters. Page size (szPage) and the purgeable
37497   ** flag (bPurgeable) are set when the cache is created. nMax may be 
37498   ** modified at any time by a call to the pcache1Cachesize() method.
37499   ** The PGroup mutex must be held when accessing nMax.
37500   */
37501   PGroup *pGroup;                     /* PGroup this cache belongs to */
37502   int szPage;                         /* Size of allocated pages in bytes */
37503   int szExtra;                        /* Size of extra space in bytes */
37504   int bPurgeable;                     /* True if cache is purgeable */
37505   unsigned int nMin;                  /* Minimum number of pages reserved */
37506   unsigned int nMax;                  /* Configured "cache_size" value */
37507   unsigned int n90pct;                /* nMax*9/10 */
37508   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
37509 
37510   /* Hash table of all pages. The following variables may only be accessed
37511   ** when the accessor is holding the PGroup mutex.
37512   */
37513   unsigned int nRecyclable;           /* Number of pages in the LRU list */
37514   unsigned int nPage;                 /* Total number of pages in apHash */
37515   unsigned int nHash;                 /* Number of slots in apHash[] */
37516   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
37517 };
37518 
37519 /*
37520 ** Each cache entry is represented by an instance of the following 
37521 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
37522 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
37523 ** in memory.
37524 */
37525 struct PgHdr1 {
37526   sqlite3_pcache_page page;
37527   unsigned int iKey;             /* Key value (page number) */
37528   PgHdr1 *pNext;                 /* Next in hash table chain */
37529   PCache1 *pCache;               /* Cache that currently owns this page */
37530   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
37531   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
37532 };
37533 
37534 /*
37535 ** Free slots in the allocator used to divide up the buffer provided using
37536 ** the SQLITE_CONFIG_PAGECACHE mechanism.
37537 */
37538 struct PgFreeslot {
37539   PgFreeslot *pNext;  /* Next free slot */
37540 };
37541 
37542 /*
37543 ** Global data used by this cache.
37544 */
37545 static SQLITE_WSD struct PCacheGlobal {
37546   PGroup grp;                    /* The global PGroup for mode (2) */
37547 
37548   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
37549   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
37550   ** fixed at sqlite3_initialize() time and do not require mutex protection.
37551   ** The nFreeSlot and pFree values do require mutex protection.
37552   */
37553   int isInit;                    /* True if initialized */
37554   int szSlot;                    /* Size of each free slot */
37555   int nSlot;                     /* The number of pcache slots */
37556   int nReserve;                  /* Try to keep nFreeSlot above this */
37557   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
37558   /* Above requires no mutex.  Use mutex below for variable that follow. */
37559   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
37560   PgFreeslot *pFree;             /* Free page blocks */
37561   int nFreeSlot;                 /* Number of unused pcache slots */
37562   /* The following value requires a mutex to change.  We skip the mutex on
37563   ** reading because (1) most platforms read a 32-bit integer atomically and
37564   ** (2) even if an incorrect value is read, no great harm is done since this
37565   ** is really just an optimization. */
37566   int bUnderPressure;            /* True if low on PAGECACHE memory */
37567 } pcache1_g;
37568 
37569 /*
37570 ** All code in this file should access the global structure above via the
37571 ** alias "pcache1". This ensures that the WSD emulation is used when
37572 ** compiling for systems that do not support real WSD.
37573 */
37574 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
37575 
37576 /*
37577 ** Macros to enter and leave the PCache LRU mutex.
37578 */
37579 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
37580 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
37581 
37582 /******************************************************************************/
37583 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
37584 
37585 /*
37586 ** This function is called during initialization if a static buffer is 
37587 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
37588 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
37589 ** enough to contain 'n' buffers of 'sz' bytes each.
37590 **
37591 ** This routine is called from sqlite3_initialize() and so it is guaranteed
37592 ** to be serialized already.  There is no need for further mutexing.
37593 */
37594 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
37595   if( pcache1.isInit ){
37596     PgFreeslot *p;
37597     sz = ROUNDDOWN8(sz);
37598     pcache1.szSlot = sz;
37599     pcache1.nSlot = pcache1.nFreeSlot = n;
37600     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
37601     pcache1.pStart = pBuf;
37602     pcache1.pFree = 0;
37603     pcache1.bUnderPressure = 0;
37604     while( n-- ){
37605       p = (PgFreeslot*)pBuf;
37606       p->pNext = pcache1.pFree;
37607       pcache1.pFree = p;
37608       pBuf = (void*)&((char*)pBuf)[sz];
37609     }
37610     pcache1.pEnd = pBuf;
37611   }
37612 }
37613 
37614 /*
37615 ** Malloc function used within this file to allocate space from the buffer
37616 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
37617 ** such buffer exists or there is no space left in it, this function falls 
37618 ** back to sqlite3Malloc().
37619 **
37620 ** Multiple threads can run this routine at the same time.  Global variables
37621 ** in pcache1 need to be protected via mutex.
37622 */
37623 static void *pcache1Alloc(int nByte){
37624   void *p = 0;
37625   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37626   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
37627   if( nByte<=pcache1.szSlot ){
37628     sqlite3_mutex_enter(pcache1.mutex);
37629     p = (PgHdr1 *)pcache1.pFree;
37630     if( p ){
37631       pcache1.pFree = pcache1.pFree->pNext;
37632       pcache1.nFreeSlot--;
37633       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37634       assert( pcache1.nFreeSlot>=0 );
37635       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
37636     }
37637     sqlite3_mutex_leave(pcache1.mutex);
37638   }
37639   if( p==0 ){
37640     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
37641     ** it from sqlite3Malloc instead.
37642     */
37643     p = sqlite3Malloc(nByte);
37644 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37645     if( p ){
37646       int sz = sqlite3MallocSize(p);
37647       sqlite3_mutex_enter(pcache1.mutex);
37648       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
37649       sqlite3_mutex_leave(pcache1.mutex);
37650     }
37651 #endif
37652     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37653   }
37654   return p;
37655 }
37656 
37657 /*
37658 ** Free an allocated buffer obtained from pcache1Alloc().
37659 */
37660 static int pcache1Free(void *p){
37661   int nFreed = 0;
37662   if( p==0 ) return 0;
37663   if( p>=pcache1.pStart && p<pcache1.pEnd ){
37664     PgFreeslot *pSlot;
37665     sqlite3_mutex_enter(pcache1.mutex);
37666     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
37667     pSlot = (PgFreeslot*)p;
37668     pSlot->pNext = pcache1.pFree;
37669     pcache1.pFree = pSlot;
37670     pcache1.nFreeSlot++;
37671     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37672     assert( pcache1.nFreeSlot<=pcache1.nSlot );
37673     sqlite3_mutex_leave(pcache1.mutex);
37674   }else{
37675     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37676     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37677     nFreed = sqlite3MallocSize(p);
37678 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37679     sqlite3_mutex_enter(pcache1.mutex);
37680     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
37681     sqlite3_mutex_leave(pcache1.mutex);
37682 #endif
37683     sqlite3_free(p);
37684   }
37685   return nFreed;
37686 }
37687 
37688 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37689 /*
37690 ** Return the size of a pcache allocation
37691 */
37692 static int pcache1MemSize(void *p){
37693   if( p>=pcache1.pStart && p<pcache1.pEnd ){
37694     return pcache1.szSlot;
37695   }else{
37696     int iSize;
37697     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37698     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37699     iSize = sqlite3MallocSize(p);
37700     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37701     return iSize;
37702   }
37703 }
37704 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37705 
37706 /*
37707 ** Allocate a new page object initially associated with cache pCache.
37708 */
37709 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
37710   PgHdr1 *p = 0;
37711   void *pPg;
37712 
37713   /* The group mutex must be released before pcache1Alloc() is called. This
37714   ** is because it may call sqlite3_release_memory(), which assumes that 
37715   ** this mutex is not held. */
37716   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37717   pcache1LeaveMutex(pCache->pGroup);
37718 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37719   pPg = pcache1Alloc(pCache->szPage);
37720   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
37721   if( !pPg || !p ){
37722     pcache1Free(pPg);
37723     sqlite3_free(p);
37724     pPg = 0;
37725   }
37726 #else
37727   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
37728   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
37729 #endif
37730   pcache1EnterMutex(pCache->pGroup);
37731 
37732   if( pPg ){
37733     p->page.pBuf = pPg;
37734     p->page.pExtra = &p[1];
37735     if( pCache->bPurgeable ){
37736       pCache->pGroup->nCurrentPage++;
37737     }
37738     return p;
37739   }
37740   return 0;
37741 }
37742 
37743 /*
37744 ** Free a page object allocated by pcache1AllocPage().
37745 **
37746 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
37747 ** that the current implementation happens to never call this routine
37748 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
37749 */
37750 static void pcache1FreePage(PgHdr1 *p){
37751   if( ALWAYS(p) ){
37752     PCache1 *pCache = p->pCache;
37753     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
37754     pcache1Free(p->page.pBuf);
37755 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37756     sqlite3_free(p);
37757 #endif
37758     if( pCache->bPurgeable ){
37759       pCache->pGroup->nCurrentPage--;
37760     }
37761   }
37762 }
37763 
37764 /*
37765 ** Malloc function used by SQLite to obtain space from the buffer configured
37766 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
37767 ** exists, this function falls back to sqlite3Malloc().
37768 */
37769 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37770   return pcache1Alloc(sz);
37771 }
37772 
37773 /*
37774 ** Free an allocated buffer obtained from sqlite3PageMalloc().
37775 */
37776 SQLITE_PRIVATE void sqlite3PageFree(void *p){
37777   pcache1Free(p);
37778 }
37779 
37780 
37781 /*
37782 ** Return true if it desirable to avoid allocating a new page cache
37783 ** entry.
37784 **
37785 ** If memory was allocated specifically to the page cache using
37786 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37787 ** it is desirable to avoid allocating a new page cache entry because
37788 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37789 ** for all page cache needs and we should not need to spill the
37790 ** allocation onto the heap.
37791 **
37792 ** Or, the heap is used for all page cache memory but the heap is
37793 ** under memory pressure, then again it is desirable to avoid
37794 ** allocating a new page cache entry in order to avoid stressing
37795 ** the heap even further.
37796 */
37797 static int pcache1UnderMemoryPressure(PCache1 *pCache){
37798   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37799     return pcache1.bUnderPressure;
37800   }else{
37801     return sqlite3HeapNearlyFull();
37802   }
37803 }
37804 
37805 /******************************************************************************/
37806 /******** General Implementation Functions ************************************/
37807 
37808 /*
37809 ** This function is used to resize the hash table used by the cache passed
37810 ** as the first argument.
37811 **
37812 ** The PCache mutex must be held when this function is called.
37813 */
37814 static int pcache1ResizeHash(PCache1 *p){
37815   PgHdr1 **apNew;
37816   unsigned int nNew;
37817   unsigned int i;
37818 
37819   assert( sqlite3_mutex_held(p->pGroup->mutex) );
37820 
37821   nNew = p->nHash*2;
37822   if( nNew<256 ){
37823     nNew = 256;
37824   }
37825 
37826   pcache1LeaveMutex(p->pGroup);
37827   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37828   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
37829   if( p->nHash ){ sqlite3EndBenignMalloc(); }
37830   pcache1EnterMutex(p->pGroup);
37831   if( apNew ){
37832     for(i=0; i<p->nHash; i++){
37833       PgHdr1 *pPage;
37834       PgHdr1 *pNext = p->apHash[i];
37835       while( (pPage = pNext)!=0 ){
37836         unsigned int h = pPage->iKey % nNew;
37837         pNext = pPage->pNext;
37838         pPage->pNext = apNew[h];
37839         apNew[h] = pPage;
37840       }
37841     }
37842     sqlite3_free(p->apHash);
37843     p->apHash = apNew;
37844     p->nHash = nNew;
37845   }
37846 
37847   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37848 }
37849 
37850 /*
37851 ** This function is used internally to remove the page pPage from the 
37852 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37853 ** LRU list, then this function is a no-op.
37854 **
37855 ** The PGroup mutex must be held when this function is called.
37856 **
37857 ** If pPage is NULL then this routine is a no-op.
37858 */
37859 static void pcache1PinPage(PgHdr1 *pPage){
37860   PCache1 *pCache;
37861   PGroup *pGroup;
37862 
37863   if( pPage==0 ) return;
37864   pCache = pPage->pCache;
37865   pGroup = pCache->pGroup;
37866   assert( sqlite3_mutex_held(pGroup->mutex) );
37867   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37868     if( pPage->pLruPrev ){
37869       pPage->pLruPrev->pLruNext = pPage->pLruNext;
37870     }
37871     if( pPage->pLruNext ){
37872       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37873     }
37874     if( pGroup->pLruHead==pPage ){
37875       pGroup->pLruHead = pPage->pLruNext;
37876     }
37877     if( pGroup->pLruTail==pPage ){
37878       pGroup->pLruTail = pPage->pLruPrev;
37879     }
37880     pPage->pLruNext = 0;
37881     pPage->pLruPrev = 0;
37882     pPage->pCache->nRecyclable--;
37883   }
37884 }
37885 
37886 
37887 /*
37888 ** Remove the page supplied as an argument from the hash table 
37889 ** (PCache1.apHash structure) that it is currently stored in.
37890 **
37891 ** The PGroup mutex must be held when this function is called.
37892 */
37893 static void pcache1RemoveFromHash(PgHdr1 *pPage){
37894   unsigned int h;
37895   PCache1 *pCache = pPage->pCache;
37896   PgHdr1 **pp;
37897 
37898   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37899   h = pPage->iKey % pCache->nHash;
37900   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37901   *pp = (*pp)->pNext;
37902 
37903   pCache->nPage--;
37904 }
37905 
37906 /*
37907 ** If there are currently more than nMaxPage pages allocated, try
37908 ** to recycle pages to reduce the number allocated to nMaxPage.
37909 */
37910 static void pcache1EnforceMaxPage(PGroup *pGroup){
37911   assert( sqlite3_mutex_held(pGroup->mutex) );
37912   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37913     PgHdr1 *p = pGroup->pLruTail;
37914     assert( p->pCache->pGroup==pGroup );
37915     pcache1PinPage(p);
37916     pcache1RemoveFromHash(p);
37917     pcache1FreePage(p);
37918   }
37919 }
37920 
37921 /*
37922 ** Discard all pages from cache pCache with a page number (key value) 
37923 ** greater than or equal to iLimit. Any pinned pages that meet this 
37924 ** criteria are unpinned before they are discarded.
37925 **
37926 ** The PCache mutex must be held when this function is called.
37927 */
37928 static void pcache1TruncateUnsafe(
37929   PCache1 *pCache,             /* The cache to truncate */
37930   unsigned int iLimit          /* Drop pages with this pgno or larger */
37931 ){
37932   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
37933   unsigned int h;
37934   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37935   for(h=0; h<pCache->nHash; h++){
37936     PgHdr1 **pp = &pCache->apHash[h]; 
37937     PgHdr1 *pPage;
37938     while( (pPage = *pp)!=0 ){
37939       if( pPage->iKey>=iLimit ){
37940         pCache->nPage--;
37941         *pp = pPage->pNext;
37942         pcache1PinPage(pPage);
37943         pcache1FreePage(pPage);
37944       }else{
37945         pp = &pPage->pNext;
37946         TESTONLY( nPage++; )
37947       }
37948     }
37949   }
37950   assert( pCache->nPage==nPage );
37951 }
37952 
37953 /******************************************************************************/
37954 /******** sqlite3_pcache Methods **********************************************/
37955 
37956 /*
37957 ** Implementation of the sqlite3_pcache.xInit method.
37958 */
37959 static int pcache1Init(void *NotUsed){
37960   UNUSED_PARAMETER(NotUsed);
37961   assert( pcache1.isInit==0 );
37962   memset(&pcache1, 0, sizeof(pcache1));
37963   if( sqlite3GlobalConfig.bCoreMutex ){
37964     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37965     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37966   }
37967   pcache1.grp.mxPinned = 10;
37968   pcache1.isInit = 1;
37969   return SQLITE_OK;
37970 }
37971 
37972 /*
37973 ** Implementation of the sqlite3_pcache.xShutdown method.
37974 ** Note that the static mutex allocated in xInit does 
37975 ** not need to be freed.
37976 */
37977 static void pcache1Shutdown(void *NotUsed){
37978   UNUSED_PARAMETER(NotUsed);
37979   assert( pcache1.isInit!=0 );
37980   memset(&pcache1, 0, sizeof(pcache1));
37981 }
37982 
37983 /*
37984 ** Implementation of the sqlite3_pcache.xCreate method.
37985 **
37986 ** Allocate a new cache.
37987 */
37988 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37989   PCache1 *pCache;      /* The newly created page cache */
37990   PGroup *pGroup;       /* The group the new page cache will belong to */
37991   int sz;               /* Bytes of memory required to allocate the new cache */
37992 
37993   /*
37994   ** The separateCache variable is true if each PCache has its own private
37995   ** PGroup.  In other words, separateCache is true for mode (1) where no
37996   ** mutexing is required.
37997   **
37998   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37999   **
38000   **   *  Always use a unified cache in single-threaded applications
38001   **
38002   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38003   **      use separate caches (mode-1)
38004   */
38005 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
38006   const int separateCache = 0;
38007 #else
38008   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
38009 #endif
38010 
38011   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
38012   assert( szExtra < 300 );
38013 
38014   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38015   pCache = (PCache1 *)sqlite3MallocZero(sz);
38016   if( pCache ){
38017     if( separateCache ){
38018       pGroup = (PGroup*)&pCache[1];
38019       pGroup->mxPinned = 10;
38020     }else{
38021       pGroup = &pcache1.grp;
38022     }
38023     pCache->pGroup = pGroup;
38024     pCache->szPage = szPage;
38025     pCache->szExtra = szExtra;
38026     pCache->bPurgeable = (bPurgeable ? 1 : 0);
38027     if( bPurgeable ){
38028       pCache->nMin = 10;
38029       pcache1EnterMutex(pGroup);
38030       pGroup->nMinPage += pCache->nMin;
38031       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38032       pcache1LeaveMutex(pGroup);
38033     }
38034   }
38035   return (sqlite3_pcache *)pCache;
38036 }
38037 
38038 /*
38039 ** Implementation of the sqlite3_pcache.xCachesize method. 
38040 **
38041 ** Configure the cache_size limit for a cache.
38042 */
38043 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
38044   PCache1 *pCache = (PCache1 *)p;
38045   if( pCache->bPurgeable ){
38046     PGroup *pGroup = pCache->pGroup;
38047     pcache1EnterMutex(pGroup);
38048     pGroup->nMaxPage += (nMax - pCache->nMax);
38049     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38050     pCache->nMax = nMax;
38051     pCache->n90pct = pCache->nMax*9/10;
38052     pcache1EnforceMaxPage(pGroup);
38053     pcache1LeaveMutex(pGroup);
38054   }
38055 }
38056 
38057 /*
38058 ** Implementation of the sqlite3_pcache.xShrink method. 
38059 **
38060 ** Free up as much memory as possible.
38061 */
38062 static void pcache1Shrink(sqlite3_pcache *p){
38063   PCache1 *pCache = (PCache1*)p;
38064   if( pCache->bPurgeable ){
38065     PGroup *pGroup = pCache->pGroup;
38066     int savedMaxPage;
38067     pcache1EnterMutex(pGroup);
38068     savedMaxPage = pGroup->nMaxPage;
38069     pGroup->nMaxPage = 0;
38070     pcache1EnforceMaxPage(pGroup);
38071     pGroup->nMaxPage = savedMaxPage;
38072     pcache1LeaveMutex(pGroup);
38073   }
38074 }
38075 
38076 /*
38077 ** Implementation of the sqlite3_pcache.xPagecount method. 
38078 */
38079 static int pcache1Pagecount(sqlite3_pcache *p){
38080   int n;
38081   PCache1 *pCache = (PCache1*)p;
38082   pcache1EnterMutex(pCache->pGroup);
38083   n = pCache->nPage;
38084   pcache1LeaveMutex(pCache->pGroup);
38085   return n;
38086 }
38087 
38088 /*
38089 ** Implementation of the sqlite3_pcache.xFetch method. 
38090 **
38091 ** Fetch a page by key value.
38092 **
38093 ** Whether or not a new page may be allocated by this function depends on
38094 ** the value of the createFlag argument.  0 means do not allocate a new
38095 ** page.  1 means allocate a new page if space is easily available.  2 
38096 ** means to try really hard to allocate a new page.
38097 **
38098 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38099 ** database) there is really no difference between createFlag 1 and 2.  So
38100 ** the calling function (pcache.c) will never have a createFlag of 1 on
38101 ** a non-purgeable cache.
38102 **
38103 ** There are three different approaches to obtaining space for a page,
38104 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38105 **
38106 **   1. Regardless of the value of createFlag, the cache is searched for a 
38107 **      copy of the requested page. If one is found, it is returned.
38108 **
38109 **   2. If createFlag==0 and the page is not already in the cache, NULL is
38110 **      returned.
38111 **
38112 **   3. If createFlag is 1, and the page is not already in the cache, then
38113 **      return NULL (do not allocate a new page) if any of the following
38114 **      conditions are true:
38115 **
38116 **       (a) the number of pages pinned by the cache is greater than
38117 **           PCache1.nMax, or
38118 **
38119 **       (b) the number of pages pinned by the cache is greater than
38120 **           the sum of nMax for all purgeable caches, less the sum of 
38121 **           nMin for all other purgeable caches, or
38122 **
38123 **   4. If none of the first three conditions apply and the cache is marked
38124 **      as purgeable, and if one of the following is true:
38125 **
38126 **       (a) The number of pages allocated for the cache is already 
38127 **           PCache1.nMax, or
38128 **
38129 **       (b) The number of pages allocated for all purgeable caches is
38130 **           already equal to or greater than the sum of nMax for all
38131 **           purgeable caches,
38132 **
38133 **       (c) The system is under memory pressure and wants to avoid
38134 **           unnecessary pages cache entry allocations
38135 **
38136 **      then attempt to recycle a page from the LRU list. If it is the right
38137 **      size, return the recycled buffer. Otherwise, free the buffer and
38138 **      proceed to step 5. 
38139 **
38140 **   5. Otherwise, allocate and return a new page buffer.
38141 */
38142 static sqlite3_pcache_page *pcache1Fetch(
38143   sqlite3_pcache *p, 
38144   unsigned int iKey, 
38145   int createFlag
38146 ){
38147   unsigned int nPinned;
38148   PCache1 *pCache = (PCache1 *)p;
38149   PGroup *pGroup;
38150   PgHdr1 *pPage = 0;
38151 
38152   assert( pCache->bPurgeable || createFlag!=1 );
38153   assert( pCache->bPurgeable || pCache->nMin==0 );
38154   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38155   assert( pCache->nMin==0 || pCache->bPurgeable );
38156   pcache1EnterMutex(pGroup = pCache->pGroup);
38157 
38158   /* Step 1: Search the hash table for an existing entry. */
38159   if( pCache->nHash>0 ){
38160     unsigned int h = iKey % pCache->nHash;
38161     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38162   }
38163 
38164   /* Step 2: Abort if no existing page is found and createFlag is 0 */
38165   if( pPage || createFlag==0 ){
38166     pcache1PinPage(pPage);
38167     goto fetch_out;
38168   }
38169 
38170   /* The pGroup local variable will normally be initialized by the
38171   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
38172   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38173   ** local variable here.  Delaying the initialization of pGroup is an
38174   ** optimization:  The common case is to exit the module before reaching
38175   ** this point.
38176   */
38177 #ifdef SQLITE_MUTEX_OMIT
38178   pGroup = pCache->pGroup;
38179 #endif
38180 
38181   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38182   assert( pCache->nPage >= pCache->nRecyclable );
38183   nPinned = pCache->nPage - pCache->nRecyclable;
38184   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38185   assert( pCache->n90pct == pCache->nMax*9/10 );
38186   if( createFlag==1 && (
38187         nPinned>=pGroup->mxPinned
38188      || nPinned>=pCache->n90pct
38189      || pcache1UnderMemoryPressure(pCache)
38190   )){
38191     goto fetch_out;
38192   }
38193 
38194   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38195     goto fetch_out;
38196   }
38197   assert( pCache->nHash>0 && pCache->apHash );
38198 
38199   /* Step 4. Try to recycle a page. */
38200   if( pCache->bPurgeable && pGroup->pLruTail && (
38201          (pCache->nPage+1>=pCache->nMax)
38202       || pGroup->nCurrentPage>=pGroup->nMaxPage
38203       || pcache1UnderMemoryPressure(pCache)
38204   )){
38205     PCache1 *pOther;
38206     pPage = pGroup->pLruTail;
38207     pcache1RemoveFromHash(pPage);
38208     pcache1PinPage(pPage);
38209     pOther = pPage->pCache;
38210 
38211     /* We want to verify that szPage and szExtra are the same for pOther
38212     ** and pCache.  Assert that we can verify this by comparing sums. */
38213     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
38214     assert( pCache->szExtra<512 );
38215     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
38216     assert( pOther->szExtra<512 );
38217 
38218     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
38219       pcache1FreePage(pPage);
38220       pPage = 0;
38221     }else{
38222       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
38223     }
38224   }
38225 
38226   /* Step 5. If a usable page buffer has still not been found, 
38227   ** attempt to allocate a new one. 
38228   */
38229   if( !pPage ){
38230     if( createFlag==1 ) sqlite3BeginBenignMalloc();
38231     pPage = pcache1AllocPage(pCache);
38232     if( createFlag==1 ) sqlite3EndBenignMalloc();
38233   }
38234 
38235   if( pPage ){
38236     unsigned int h = iKey % pCache->nHash;
38237     pCache->nPage++;
38238     pPage->iKey = iKey;
38239     pPage->pNext = pCache->apHash[h];
38240     pPage->pCache = pCache;
38241     pPage->pLruPrev = 0;
38242     pPage->pLruNext = 0;
38243     *(void **)pPage->page.pExtra = 0;
38244     pCache->apHash[h] = pPage;
38245   }
38246 
38247 fetch_out:
38248   if( pPage && iKey>pCache->iMaxKey ){
38249     pCache->iMaxKey = iKey;
38250   }
38251   pcache1LeaveMutex(pGroup);
38252   return &pPage->page;
38253 }
38254 
38255 
38256 /*
38257 ** Implementation of the sqlite3_pcache.xUnpin method.
38258 **
38259 ** Mark a page as unpinned (eligible for asynchronous recycling).
38260 */
38261 static void pcache1Unpin(
38262   sqlite3_pcache *p, 
38263   sqlite3_pcache_page *pPg, 
38264   int reuseUnlikely
38265 ){
38266   PCache1 *pCache = (PCache1 *)p;
38267   PgHdr1 *pPage = (PgHdr1 *)pPg;
38268   PGroup *pGroup = pCache->pGroup;
38269  
38270   assert( pPage->pCache==pCache );
38271   pcache1EnterMutex(pGroup);
38272 
38273   /* It is an error to call this function if the page is already 
38274   ** part of the PGroup LRU list.
38275   */
38276   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38277   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38278 
38279   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38280     pcache1RemoveFromHash(pPage);
38281     pcache1FreePage(pPage);
38282   }else{
38283     /* Add the page to the PGroup LRU list. */
38284     if( pGroup->pLruHead ){
38285       pGroup->pLruHead->pLruPrev = pPage;
38286       pPage->pLruNext = pGroup->pLruHead;
38287       pGroup->pLruHead = pPage;
38288     }else{
38289       pGroup->pLruTail = pPage;
38290       pGroup->pLruHead = pPage;
38291     }
38292     pCache->nRecyclable++;
38293   }
38294 
38295   pcache1LeaveMutex(pCache->pGroup);
38296 }
38297 
38298 /*
38299 ** Implementation of the sqlite3_pcache.xRekey method. 
38300 */
38301 static void pcache1Rekey(
38302   sqlite3_pcache *p,
38303   sqlite3_pcache_page *pPg,
38304   unsigned int iOld,
38305   unsigned int iNew
38306 ){
38307   PCache1 *pCache = (PCache1 *)p;
38308   PgHdr1 *pPage = (PgHdr1 *)pPg;
38309   PgHdr1 **pp;
38310   unsigned int h; 
38311   assert( pPage->iKey==iOld );
38312   assert( pPage->pCache==pCache );
38313 
38314   pcache1EnterMutex(pCache->pGroup);
38315 
38316   h = iOld%pCache->nHash;
38317   pp = &pCache->apHash[h];
38318   while( (*pp)!=pPage ){
38319     pp = &(*pp)->pNext;
38320   }
38321   *pp = pPage->pNext;
38322 
38323   h = iNew%pCache->nHash;
38324   pPage->iKey = iNew;
38325   pPage->pNext = pCache->apHash[h];
38326   pCache->apHash[h] = pPage;
38327   if( iNew>pCache->iMaxKey ){
38328     pCache->iMaxKey = iNew;
38329   }
38330 
38331   pcache1LeaveMutex(pCache->pGroup);
38332 }
38333 
38334 /*
38335 ** Implementation of the sqlite3_pcache.xTruncate method. 
38336 **
38337 ** Discard all unpinned pages in the cache with a page number equal to
38338 ** or greater than parameter iLimit. Any pinned pages with a page number
38339 ** equal to or greater than iLimit are implicitly unpinned.
38340 */
38341 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
38342   PCache1 *pCache = (PCache1 *)p;
38343   pcache1EnterMutex(pCache->pGroup);
38344   if( iLimit<=pCache->iMaxKey ){
38345     pcache1TruncateUnsafe(pCache, iLimit);
38346     pCache->iMaxKey = iLimit-1;
38347   }
38348   pcache1LeaveMutex(pCache->pGroup);
38349 }
38350 
38351 /*
38352 ** Implementation of the sqlite3_pcache.xDestroy method. 
38353 **
38354 ** Destroy a cache allocated using pcache1Create().
38355 */
38356 static void pcache1Destroy(sqlite3_pcache *p){
38357   PCache1 *pCache = (PCache1 *)p;
38358   PGroup *pGroup = pCache->pGroup;
38359   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38360   pcache1EnterMutex(pGroup);
38361   pcache1TruncateUnsafe(pCache, 0);
38362   assert( pGroup->nMaxPage >= pCache->nMax );
38363   pGroup->nMaxPage -= pCache->nMax;
38364   assert( pGroup->nMinPage >= pCache->nMin );
38365   pGroup->nMinPage -= pCache->nMin;
38366   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38367   pcache1EnforceMaxPage(pGroup);
38368   pcache1LeaveMutex(pGroup);
38369   sqlite3_free(pCache->apHash);
38370   sqlite3_free(pCache);
38371 }
38372 
38373 /*
38374 ** This function is called during initialization (sqlite3_initialize()) to
38375 ** install the default pluggable cache module, assuming the user has not
38376 ** already provided an alternative.
38377 */
38378 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
38379   static const sqlite3_pcache_methods2 defaultMethods = {
38380     1,                       /* iVersion */
38381     0,                       /* pArg */
38382     pcache1Init,             /* xInit */
38383     pcache1Shutdown,         /* xShutdown */
38384     pcache1Create,           /* xCreate */
38385     pcache1Cachesize,        /* xCachesize */
38386     pcache1Pagecount,        /* xPagecount */
38387     pcache1Fetch,            /* xFetch */
38388     pcache1Unpin,            /* xUnpin */
38389     pcache1Rekey,            /* xRekey */
38390     pcache1Truncate,         /* xTruncate */
38391     pcache1Destroy,          /* xDestroy */
38392     pcache1Shrink            /* xShrink */
38393   };
38394   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
38395 }
38396 
38397 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38398 /*
38399 ** This function is called to free superfluous dynamically allocated memory
38400 ** held by the pager system. Memory in use by any SQLite pager allocated
38401 ** by the current thread may be sqlite3_free()ed.
38402 **
38403 ** nReq is the number of bytes of memory required. Once this much has
38404 ** been released, the function returns. The return value is the total number 
38405 ** of bytes of memory released.
38406 */
38407 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
38408   int nFree = 0;
38409   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38410   assert( sqlite3_mutex_notheld(pcache1.mutex) );
38411   if( pcache1.pStart==0 ){
38412     PgHdr1 *p;
38413     pcache1EnterMutex(&pcache1.grp);
38414     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38415       nFree += pcache1MemSize(p->page.pBuf);
38416 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38417       nFree += sqlite3MemSize(p);
38418 #endif
38419       pcache1PinPage(p);
38420       pcache1RemoveFromHash(p);
38421       pcache1FreePage(p);
38422     }
38423     pcache1LeaveMutex(&pcache1.grp);
38424   }
38425   return nFree;
38426 }
38427 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38428 
38429 #ifdef SQLITE_TEST
38430 /*
38431 ** This function is used by test procedures to inspect the internal state
38432 ** of the global cache.
38433 */
38434 SQLITE_PRIVATE void sqlite3PcacheStats(
38435   int *pnCurrent,      /* OUT: Total number of pages cached */
38436   int *pnMax,          /* OUT: Global maximum cache size */
38437   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
38438   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
38439 ){
38440   PgHdr1 *p;
38441   int nRecyclable = 0;
38442   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38443     nRecyclable++;
38444   }
38445   *pnCurrent = pcache1.grp.nCurrentPage;
38446   *pnMax = (int)pcache1.grp.nMaxPage;
38447   *pnMin = (int)pcache1.grp.nMinPage;
38448   *pnRecyclable = nRecyclable;
38449 }
38450 #endif
38451 
38452 /************** End of pcache1.c *********************************************/
38453 /************** Begin file rowset.c ******************************************/
38454 /*
38455 ** 2008 December 3
38456 **
38457 ** The author disclaims copyright to this source code.  In place of
38458 ** a legal notice, here is a blessing:
38459 **
38460 **    May you do good and not evil.
38461 **    May you find forgiveness for yourself and forgive others.
38462 **    May you share freely, never taking more than you give.
38463 **
38464 *************************************************************************
38465 **
38466 ** This module implements an object we call a "RowSet".
38467 **
38468 ** The RowSet object is a collection of rowids.  Rowids
38469 ** are inserted into the RowSet in an arbitrary order.  Inserts
38470 ** can be intermixed with tests to see if a given rowid has been
38471 ** previously inserted into the RowSet.
38472 **
38473 ** After all inserts are finished, it is possible to extract the
38474 ** elements of the RowSet in sorted order.  Once this extraction
38475 ** process has started, no new elements may be inserted.
38476 **
38477 ** Hence, the primitive operations for a RowSet are:
38478 **
38479 **    CREATE
38480 **    INSERT
38481 **    TEST
38482 **    SMALLEST
38483 **    DESTROY
38484 **
38485 ** The CREATE and DESTROY primitives are the constructor and destructor,
38486 ** obviously.  The INSERT primitive adds a new element to the RowSet.
38487 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
38488 ** extracts the least value from the RowSet.
38489 **
38490 ** The INSERT primitive might allocate additional memory.  Memory is
38491 ** allocated in chunks so most INSERTs do no allocation.  There is an 
38492 ** upper bound on the size of allocated memory.  No memory is freed
38493 ** until DESTROY.
38494 **
38495 ** The TEST primitive includes a "batch" number.  The TEST primitive
38496 ** will only see elements that were inserted before the last change
38497 ** in the batch number.  In other words, if an INSERT occurs between
38498 ** two TESTs where the TESTs have the same batch nubmer, then the
38499 ** value added by the INSERT will not be visible to the second TEST.
38500 ** The initial batch number is zero, so if the very first TEST contains
38501 ** a non-zero batch number, it will see all prior INSERTs.
38502 **
38503 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
38504 ** that is attempted.
38505 **
38506 ** The cost of an INSERT is roughly constant.  (Sometime new memory
38507 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
38508 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
38509 ** The cost of a TEST using the same batch number is O(logN).  The cost
38510 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
38511 ** primitives are constant time.  The cost of DESTROY is O(N).
38512 **
38513 ** There is an added cost of O(N) when switching between TEST and
38514 ** SMALLEST primitives.
38515 */
38516 
38517 
38518 /*
38519 ** Target size for allocation chunks.
38520 */
38521 #define ROWSET_ALLOCATION_SIZE 1024
38522 
38523 /*
38524 ** The number of rowset entries per allocation chunk.
38525 */
38526 #define ROWSET_ENTRY_PER_CHUNK  \
38527                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
38528 
38529 /*
38530 ** Each entry in a RowSet is an instance of the following object.
38531 **
38532 ** This same object is reused to store a linked list of trees of RowSetEntry
38533 ** objects.  In that alternative use, pRight points to the next entry
38534 ** in the list, pLeft points to the tree, and v is unused.  The
38535 ** RowSet.pForest value points to the head of this forest list.
38536 */
38537 struct RowSetEntry {            
38538   i64 v;                        /* ROWID value for this entry */
38539   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
38540   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
38541 };
38542 
38543 /*
38544 ** RowSetEntry objects are allocated in large chunks (instances of the
38545 ** following structure) to reduce memory allocation overhead.  The
38546 ** chunks are kept on a linked list so that they can be deallocated
38547 ** when the RowSet is destroyed.
38548 */
38549 struct RowSetChunk {
38550   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
38551   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
38552 };
38553 
38554 /*
38555 ** A RowSet in an instance of the following structure.
38556 **
38557 ** A typedef of this structure if found in sqliteInt.h.
38558 */
38559 struct RowSet {
38560   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
38561   sqlite3 *db;                   /* The database connection */
38562   struct RowSetEntry *pEntry;    /* List of entries using pRight */
38563   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
38564   struct RowSetEntry *pFresh;    /* Source of new entry objects */
38565   struct RowSetEntry *pForest;   /* List of binary trees of entries */
38566   u16 nFresh;                    /* Number of objects on pFresh */
38567   u8 rsFlags;                    /* Various flags */
38568   u8 iBatch;                     /* Current insert batch */
38569 };
38570 
38571 /*
38572 ** Allowed values for RowSet.rsFlags
38573 */
38574 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
38575 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
38576 
38577 /*
38578 ** Turn bulk memory into a RowSet object.  N bytes of memory
38579 ** are available at pSpace.  The db pointer is used as a memory context
38580 ** for any subsequent allocations that need to occur.
38581 ** Return a pointer to the new RowSet object.
38582 **
38583 ** It must be the case that N is sufficient to make a Rowset.  If not
38584 ** an assertion fault occurs.
38585 ** 
38586 ** If N is larger than the minimum, use the surplus as an initial
38587 ** allocation of entries available to be filled.
38588 */
38589 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
38590   RowSet *p;
38591   assert( N >= ROUND8(sizeof(*p)) );
38592   p = pSpace;
38593   p->pChunk = 0;
38594   p->db = db;
38595   p->pEntry = 0;
38596   p->pLast = 0;
38597   p->pForest = 0;
38598   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38599   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38600   p->rsFlags = ROWSET_SORTED;
38601   p->iBatch = 0;
38602   return p;
38603 }
38604 
38605 /*
38606 ** Deallocate all chunks from a RowSet.  This frees all memory that
38607 ** the RowSet has allocated over its lifetime.  This routine is
38608 ** the destructor for the RowSet.
38609 */
38610 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
38611   struct RowSetChunk *pChunk, *pNextChunk;
38612   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38613     pNextChunk = pChunk->pNextChunk;
38614     sqlite3DbFree(p->db, pChunk);
38615   }
38616   p->pChunk = 0;
38617   p->nFresh = 0;
38618   p->pEntry = 0;
38619   p->pLast = 0;
38620   p->pForest = 0;
38621   p->rsFlags = ROWSET_SORTED;
38622 }
38623 
38624 /*
38625 ** Allocate a new RowSetEntry object that is associated with the
38626 ** given RowSet.  Return a pointer to the new and completely uninitialized
38627 ** objected.
38628 **
38629 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
38630 ** routine returns NULL.
38631 */
38632 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
38633   assert( p!=0 );
38634   if( p->nFresh==0 ){
38635     struct RowSetChunk *pNew;
38636     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
38637     if( pNew==0 ){
38638       return 0;
38639     }
38640     pNew->pNextChunk = p->pChunk;
38641     p->pChunk = pNew;
38642     p->pFresh = pNew->aEntry;
38643     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38644   }
38645   p->nFresh--;
38646   return p->pFresh++;
38647 }
38648 
38649 /*
38650 ** Insert a new value into a RowSet.
38651 **
38652 ** The mallocFailed flag of the database connection is set if a
38653 ** memory allocation fails.
38654 */
38655 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
38656   struct RowSetEntry *pEntry;  /* The new entry */
38657   struct RowSetEntry *pLast;   /* The last prior entry */
38658 
38659   /* This routine is never called after sqlite3RowSetNext() */
38660   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38661 
38662   pEntry = rowSetEntryAlloc(p);
38663   if( pEntry==0 ) return;
38664   pEntry->v = rowid;
38665   pEntry->pRight = 0;
38666   pLast = p->pLast;
38667   if( pLast ){
38668     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
38669       p->rsFlags &= ~ROWSET_SORTED;
38670     }
38671     pLast->pRight = pEntry;
38672   }else{
38673     p->pEntry = pEntry;
38674   }
38675   p->pLast = pEntry;
38676 }
38677 
38678 /*
38679 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
38680 **
38681 ** The input lists are connected via pRight pointers and are 
38682 ** assumed to each already be in sorted order.
38683 */
38684 static struct RowSetEntry *rowSetEntryMerge(
38685   struct RowSetEntry *pA,    /* First sorted list to be merged */
38686   struct RowSetEntry *pB     /* Second sorted list to be merged */
38687 ){
38688   struct RowSetEntry head;
38689   struct RowSetEntry *pTail;
38690 
38691   pTail = &head;
38692   while( pA && pB ){
38693     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38694     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
38695     if( pA->v<pB->v ){
38696       pTail->pRight = pA;
38697       pA = pA->pRight;
38698       pTail = pTail->pRight;
38699     }else if( pB->v<pA->v ){
38700       pTail->pRight = pB;
38701       pB = pB->pRight;
38702       pTail = pTail->pRight;
38703     }else{
38704       pA = pA->pRight;
38705     }
38706   }
38707   if( pA ){
38708     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38709     pTail->pRight = pA;
38710   }else{
38711     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
38712     pTail->pRight = pB;
38713   }
38714   return head.pRight;
38715 }
38716 
38717 /*
38718 ** Sort all elements on the list of RowSetEntry objects into order of
38719 ** increasing v.
38720 */ 
38721 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
38722   unsigned int i;
38723   struct RowSetEntry *pNext, *aBucket[40];
38724 
38725   memset(aBucket, 0, sizeof(aBucket));
38726   while( pIn ){
38727     pNext = pIn->pRight;
38728     pIn->pRight = 0;
38729     for(i=0; aBucket[i]; i++){
38730       pIn = rowSetEntryMerge(aBucket[i], pIn);
38731       aBucket[i] = 0;
38732     }
38733     aBucket[i] = pIn;
38734     pIn = pNext;
38735   }
38736   pIn = 0;
38737   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
38738     pIn = rowSetEntryMerge(pIn, aBucket[i]);
38739   }
38740   return pIn;
38741 }
38742 
38743 
38744 /*
38745 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
38746 ** Convert this tree into a linked list connected by the pRight pointers
38747 ** and return pointers to the first and last elements of the new list.
38748 */
38749 static void rowSetTreeToList(
38750   struct RowSetEntry *pIn,         /* Root of the input tree */
38751   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
38752   struct RowSetEntry **ppLast      /* Write tail of the output list here */
38753 ){
38754   assert( pIn!=0 );
38755   if( pIn->pLeft ){
38756     struct RowSetEntry *p;
38757     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
38758     p->pRight = pIn;
38759   }else{
38760     *ppFirst = pIn;
38761   }
38762   if( pIn->pRight ){
38763     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
38764   }else{
38765     *ppLast = pIn;
38766   }
38767   assert( (*ppLast)->pRight==0 );
38768 }
38769 
38770 
38771 /*
38772 ** Convert a sorted list of elements (connected by pRight) into a binary
38773 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38774 ** node taken from the head of *ppList.  A depth of 2 means a tree with
38775 ** three nodes.  And so forth.
38776 **
38777 ** Use as many entries from the input list as required and update the
38778 ** *ppList to point to the unused elements of the list.  If the input
38779 ** list contains too few elements, then construct an incomplete tree
38780 ** and leave *ppList set to NULL.
38781 **
38782 ** Return a pointer to the root of the constructed binary tree.
38783 */
38784 static struct RowSetEntry *rowSetNDeepTree(
38785   struct RowSetEntry **ppList,
38786   int iDepth
38787 ){
38788   struct RowSetEntry *p;         /* Root of the new tree */
38789   struct RowSetEntry *pLeft;     /* Left subtree */
38790   if( *ppList==0 ){
38791     return 0;
38792   }
38793   if( iDepth==1 ){
38794     p = *ppList;
38795     *ppList = p->pRight;
38796     p->pLeft = p->pRight = 0;
38797     return p;
38798   }
38799   pLeft = rowSetNDeepTree(ppList, iDepth-1);
38800   p = *ppList;
38801   if( p==0 ){
38802     return pLeft;
38803   }
38804   p->pLeft = pLeft;
38805   *ppList = p->pRight;
38806   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38807   return p;
38808 }
38809 
38810 /*
38811 ** Convert a sorted list of elements into a binary tree. Make the tree
38812 ** as deep as it needs to be in order to contain the entire list.
38813 */
38814 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38815   int iDepth;           /* Depth of the tree so far */
38816   struct RowSetEntry *p;       /* Current tree root */
38817   struct RowSetEntry *pLeft;   /* Left subtree */
38818 
38819   assert( pList!=0 );
38820   p = pList;
38821   pList = p->pRight;
38822   p->pLeft = p->pRight = 0;
38823   for(iDepth=1; pList; iDepth++){
38824     pLeft = p;
38825     p = pList;
38826     pList = p->pRight;
38827     p->pLeft = pLeft;
38828     p->pRight = rowSetNDeepTree(&pList, iDepth);
38829   }
38830   return p;
38831 }
38832 
38833 /*
38834 ** Take all the entries on p->pEntry and on the trees in p->pForest and
38835 ** sort them all together into one big ordered list on p->pEntry.
38836 **
38837 ** This routine should only be called once in the life of a RowSet.
38838 */
38839 static void rowSetToList(RowSet *p){
38840 
38841   /* This routine is called only once */
38842   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38843 
38844   if( (p->rsFlags & ROWSET_SORTED)==0 ){
38845     p->pEntry = rowSetEntrySort(p->pEntry);
38846   }
38847 
38848   /* While this module could theoretically support it, sqlite3RowSetNext()
38849   ** is never called after sqlite3RowSetText() for the same RowSet.  So
38850   ** there is never a forest to deal with.  Should this change, simply
38851   ** remove the assert() and the #if 0. */
38852   assert( p->pForest==0 );
38853 #if 0
38854   while( p->pForest ){
38855     struct RowSetEntry *pTree = p->pForest->pLeft;
38856     if( pTree ){
38857       struct RowSetEntry *pHead, *pTail;
38858       rowSetTreeToList(pTree, &pHead, &pTail);
38859       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
38860     }
38861     p->pForest = p->pForest->pRight;
38862   }
38863 #endif
38864   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
38865 }
38866 
38867 /*
38868 ** Extract the smallest element from the RowSet.
38869 ** Write the element into *pRowid.  Return 1 on success.  Return
38870 ** 0 if the RowSet is already empty.
38871 **
38872 ** After this routine has been called, the sqlite3RowSetInsert()
38873 ** routine may not be called again.  
38874 */
38875 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38876   assert( p!=0 );
38877 
38878   /* Merge the forest into a single sorted list on first call */
38879   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
38880 
38881   /* Return the next entry on the list */
38882   if( p->pEntry ){
38883     *pRowid = p->pEntry->v;
38884     p->pEntry = p->pEntry->pRight;
38885     if( p->pEntry==0 ){
38886       sqlite3RowSetClear(p);
38887     }
38888     return 1;
38889   }else{
38890     return 0;
38891   }
38892 }
38893 
38894 /*
38895 ** Check to see if element iRowid was inserted into the rowset as
38896 ** part of any insert batch prior to iBatch.  Return 1 or 0.
38897 **
38898 ** If this is the first test of a new batch and if there exist entires
38899 ** on pRowSet->pEntry, then sort those entires into the forest at
38900 ** pRowSet->pForest so that they can be tested.
38901 */
38902 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38903   struct RowSetEntry *p, *pTree;
38904 
38905   /* This routine is never called after sqlite3RowSetNext() */
38906   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
38907 
38908   /* Sort entries into the forest on the first test of a new batch 
38909   */
38910   if( iBatch!=pRowSet->iBatch ){
38911     p = pRowSet->pEntry;
38912     if( p ){
38913       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
38914       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
38915         p = rowSetEntrySort(p);
38916       }
38917       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38918         ppPrevTree = &pTree->pRight;
38919         if( pTree->pLeft==0 ){
38920           pTree->pLeft = rowSetListToTree(p);
38921           break;
38922         }else{
38923           struct RowSetEntry *pAux, *pTail;
38924           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
38925           pTree->pLeft = 0;
38926           p = rowSetEntryMerge(pAux, p);
38927         }
38928       }
38929       if( pTree==0 ){
38930         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
38931         if( pTree ){
38932           pTree->v = 0;
38933           pTree->pRight = 0;
38934           pTree->pLeft = rowSetListToTree(p);
38935         }
38936       }
38937       pRowSet->pEntry = 0;
38938       pRowSet->pLast = 0;
38939       pRowSet->rsFlags |= ROWSET_SORTED;
38940     }
38941     pRowSet->iBatch = iBatch;
38942   }
38943 
38944   /* Test to see if the iRowid value appears anywhere in the forest.
38945   ** Return 1 if it does and 0 if not.
38946   */
38947   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38948     p = pTree->pLeft;
38949     while( p ){
38950       if( p->v<iRowid ){
38951         p = p->pRight;
38952       }else if( p->v>iRowid ){
38953         p = p->pLeft;
38954       }else{
38955         return 1;
38956       }
38957     }
38958   }
38959   return 0;
38960 }
38961 
38962 /************** End of rowset.c **********************************************/
38963 /************** Begin file pager.c *******************************************/
38964 /*
38965 ** 2001 September 15
38966 **
38967 ** The author disclaims copyright to this source code.  In place of
38968 ** a legal notice, here is a blessing:
38969 **
38970 **    May you do good and not evil.
38971 **    May you find forgiveness for yourself and forgive others.
38972 **    May you share freely, never taking more than you give.
38973 **
38974 *************************************************************************
38975 ** This is the implementation of the page cache subsystem or "pager".
38976 ** 
38977 ** The pager is used to access a database disk file.  It implements
38978 ** atomic commit and rollback through the use of a journal file that
38979 ** is separate from the database file.  The pager also implements file
38980 ** locking to prevent two processes from writing the same database
38981 ** file simultaneously, or one process from reading the database while
38982 ** another is writing.
38983 */
38984 #ifndef SQLITE_OMIT_DISKIO
38985 /************** Include wal.h in the middle of pager.c ***********************/
38986 /************** Begin file wal.h *********************************************/
38987 /*
38988 ** 2010 February 1
38989 **
38990 ** The author disclaims copyright to this source code.  In place of
38991 ** a legal notice, here is a blessing:
38992 **
38993 **    May you do good and not evil.
38994 **    May you find forgiveness for yourself and forgive others.
38995 **    May you share freely, never taking more than you give.
38996 **
38997 *************************************************************************
38998 ** This header file defines the interface to the write-ahead logging 
38999 ** system. Refer to the comments below and the header comment attached to 
39000 ** the implementation of each function in log.c for further details.
39001 */
39002 
39003 #ifndef _WAL_H_
39004 #define _WAL_H_
39005 
39006 
39007 /* Additional values that can be added to the sync_flags argument of
39008 ** sqlite3WalFrames():
39009 */
39010 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
39011 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
39012 
39013 #ifdef SQLITE_OMIT_WAL
39014 # define sqlite3WalOpen(x,y,z)                   0
39015 # define sqlite3WalLimit(x,y)
39016 # define sqlite3WalClose(w,x,y,z)                0
39017 # define sqlite3WalBeginReadTransaction(y,z)     0
39018 # define sqlite3WalEndReadTransaction(z)
39019 # define sqlite3WalDbsize(y)                     0
39020 # define sqlite3WalBeginWriteTransaction(y)      0
39021 # define sqlite3WalEndWriteTransaction(x)        0
39022 # define sqlite3WalUndo(x,y,z)                   0
39023 # define sqlite3WalSavepoint(y,z)
39024 # define sqlite3WalSavepointUndo(y,z)            0
39025 # define sqlite3WalFrames(u,v,w,x,y,z)           0
39026 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39027 # define sqlite3WalCallback(z)                   0
39028 # define sqlite3WalExclusiveMode(y,z)            0
39029 # define sqlite3WalHeapMemory(z)                 0
39030 # define sqlite3WalFramesize(z)                  0
39031 # define sqlite3WalFindFrame(x,y,z)              0
39032 #else
39033 
39034 #define WAL_SAVEPOINT_NDATA 4
39035 
39036 /* Connection to a write-ahead log (WAL) file. 
39037 ** There is one object of this type for each pager. 
39038 */
39039 typedef struct Wal Wal;
39040 
39041 /* Open and close a connection to a write-ahead log. */
39042 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
39043 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39044 
39045 /* Set the limiting size of a WAL file. */
39046 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
39047 
39048 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
39049 ** snapshot is like a read-transaction.  It is the state of the database
39050 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
39051 ** preserves the current state even if the other threads or processes
39052 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
39053 ** transaction and releases the lock.
39054 */
39055 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
39056 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
39057 
39058 /* Read a page from the write-ahead log, if it is present. */
39059 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
39060 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
39061 
39062 /* If the WAL is not empty, return the size of the database. */
39063 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
39064 
39065 /* Obtain or release the WRITER lock. */
39066 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
39067 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
39068 
39069 /* Undo any frames written (but not committed) to the log */
39070 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39071 
39072 /* Return an integer that records the current (uncommitted) write
39073 ** position in the WAL */
39074 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
39075 
39076 /* Move the write position of the WAL back to iFrame.  Called in
39077 ** response to a ROLLBACK TO command. */
39078 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39079 
39080 /* Write a frame or frames to the log. */
39081 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39082 
39083 /* Copy pages from the log to the database file */ 
39084 SQLITE_PRIVATE int sqlite3WalCheckpoint(
39085   Wal *pWal,                      /* Write-ahead log connection */
39086   int eMode,                      /* One of PASSIVE, FULL and RESTART */
39087   int (*xBusy)(void*),            /* Function to call when busy */
39088   void *pBusyArg,                 /* Context argument for xBusyHandler */
39089   int sync_flags,                 /* Flags to sync db file with (or 0) */
39090   int nBuf,                       /* Size of buffer nBuf */
39091   u8 *zBuf,                       /* Temporary buffer to use */
39092   int *pnLog,                     /* OUT: Number of frames in WAL */
39093   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39094 );
39095 
39096 /* Return the value to pass to a sqlite3_wal_hook callback, the
39097 ** number of frames in the WAL at the point of the last commit since
39098 ** sqlite3WalCallback() was called.  If no commits have occurred since
39099 ** the last call, then return 0.
39100 */
39101 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
39102 
39103 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39104 ** by the pager layer on the database file.
39105 */
39106 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
39107 
39108 /* Return true if the argument is non-NULL and the WAL module is using
39109 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39110 ** WAL module is using shared-memory, return false. 
39111 */
39112 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
39113 
39114 #ifdef SQLITE_ENABLE_ZIPVFS
39115 /* If the WAL file is not empty, return the number of bytes of content
39116 ** stored in each frame (i.e. the db page-size when the WAL was created).
39117 */
39118 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
39119 #endif
39120 
39121 #endif /* ifndef SQLITE_OMIT_WAL */
39122 #endif /* _WAL_H_ */
39123 
39124 /************** End of wal.h *************************************************/
39125 /************** Continuing where we left off in pager.c **********************/
39126 
39127 
39128 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39129 **
39130 ** This comment block describes invariants that hold when using a rollback
39131 ** journal.  These invariants do not apply for journal_mode=WAL,
39132 ** journal_mode=MEMORY, or journal_mode=OFF.
39133 **
39134 ** Within this comment block, a page is deemed to have been synced
39135 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39136 ** Otherwise, the page is not synced until the xSync method of the VFS
39137 ** is called successfully on the file containing the page.
39138 **
39139 ** Definition:  A page of the database file is said to be "overwriteable" if
39140 ** one or more of the following are true about the page:
39141 ** 
39142 **     (a)  The original content of the page as it was at the beginning of
39143 **          the transaction has been written into the rollback journal and
39144 **          synced.
39145 ** 
39146 **     (b)  The page was a freelist leaf page at the start of the transaction.
39147 ** 
39148 **     (c)  The page number is greater than the largest page that existed in
39149 **          the database file at the start of the transaction.
39150 ** 
39151 ** (1) A page of the database file is never overwritten unless one of the
39152 **     following are true:
39153 ** 
39154 **     (a) The page and all other pages on the same sector are overwriteable.
39155 ** 
39156 **     (b) The atomic page write optimization is enabled, and the entire
39157 **         transaction other than the update of the transaction sequence
39158 **         number consists of a single page change.
39159 ** 
39160 ** (2) The content of a page written into the rollback journal exactly matches
39161 **     both the content in the database when the rollback journal was written
39162 **     and the content in the database at the beginning of the current
39163 **     transaction.
39164 ** 
39165 ** (3) Writes to the database file are an integer multiple of the page size
39166 **     in length and are aligned on a page boundary.
39167 ** 
39168 ** (4) Reads from the database file are either aligned on a page boundary and
39169 **     an integer multiple of the page size in length or are taken from the
39170 **     first 100 bytes of the database file.
39171 ** 
39172 ** (5) All writes to the database file are synced prior to the rollback journal
39173 **     being deleted, truncated, or zeroed.
39174 ** 
39175 ** (6) If a master journal file is used, then all writes to the database file
39176 **     are synced prior to the master journal being deleted.
39177 ** 
39178 ** Definition: Two databases (or the same database at two points it time)
39179 ** are said to be "logically equivalent" if they give the same answer to
39180 ** all queries.  Note in particular the content of freelist leaf
39181 ** pages can be changed arbitarily without effecting the logical equivalence
39182 ** of the database.
39183 ** 
39184 ** (7) At any time, if any subset, including the empty set and the total set,
39185 **     of the unsynced changes to a rollback journal are removed and the 
39186 **     journal is rolled back, the resulting database file will be logical
39187 **     equivalent to the database file at the beginning of the transaction.
39188 ** 
39189 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39190 **     is called to restore the database file to the same size it was at
39191 **     the beginning of the transaction.  (In some VFSes, the xTruncate
39192 **     method is a no-op, but that does not change the fact the SQLite will
39193 **     invoke it.)
39194 ** 
39195 ** (9) Whenever the database file is modified, at least one bit in the range
39196 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
39197 **     the EXCLUSIVE lock, thus signaling other connections on the same
39198 **     database to flush their caches.
39199 **
39200 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39201 **      than one billion transactions.
39202 **
39203 ** (11) A database file is well-formed at the beginning and at the conclusion
39204 **      of every transaction.
39205 **
39206 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39207 **      the database file.
39208 **
39209 ** (13) A SHARED lock is held on the database file while reading any
39210 **      content out of the database file.
39211 **
39212 ******************************************************************************/
39213 
39214 /*
39215 ** Macros for troubleshooting.  Normally turned off
39216 */
39217 #if 0
39218 int sqlite3PagerTrace=1;  /* True to enable tracing */
39219 #define sqlite3DebugPrintf printf
39220 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
39221 #else
39222 #define PAGERTRACE(X)
39223 #endif
39224 
39225 /*
39226 ** The following two macros are used within the PAGERTRACE() macros above
39227 ** to print out file-descriptors. 
39228 **
39229 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39230 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
39231 ** struct as its argument.
39232 */
39233 #define PAGERID(p) ((int)(p->fd))
39234 #define FILEHANDLEID(fd) ((int)fd)
39235 
39236 /*
39237 ** The Pager.eState variable stores the current 'state' of a pager. A
39238 ** pager may be in any one of the seven states shown in the following
39239 ** state diagram.
39240 **
39241 **                            OPEN <------+------+
39242 **                              |         |      |
39243 **                              V         |      |
39244 **               +---------> READER-------+      |
39245 **               |              |                |
39246 **               |              V                |
39247 **               |<-------WRITER_LOCKED------> ERROR
39248 **               |              |                ^  
39249 **               |              V                |
39250 **               |<------WRITER_CACHEMOD-------->|
39251 **               |              |                |
39252 **               |              V                |
39253 **               |<-------WRITER_DBMOD---------->|
39254 **               |              |                |
39255 **               |              V                |
39256 **               +<------WRITER_FINISHED-------->+
39257 **
39258 **
39259 ** List of state transitions and the C [function] that performs each:
39260 ** 
39261 **   OPEN              -> READER              [sqlite3PagerSharedLock]
39262 **   READER            -> OPEN                [pager_unlock]
39263 **
39264 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
39265 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
39266 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
39267 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
39268 **   WRITER_***        -> READER              [pager_end_transaction]
39269 **
39270 **   WRITER_***        -> ERROR               [pager_error]
39271 **   ERROR             -> OPEN                [pager_unlock]
39272 ** 
39273 **
39274 **  OPEN:
39275 **
39276 **    The pager starts up in this state. Nothing is guaranteed in this
39277 **    state - the file may or may not be locked and the database size is
39278 **    unknown. The database may not be read or written.
39279 **
39280 **    * No read or write transaction is active.
39281 **    * Any lock, or no lock at all, may be held on the database file.
39282 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39283 **
39284 **  READER:
39285 **
39286 **    In this state all the requirements for reading the database in 
39287 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
39288 **    was) in exclusive-locking mode, a user-level read transaction is 
39289 **    open. The database size is known in this state.
39290 **
39291 **    A connection running with locking_mode=normal enters this state when
39292 **    it opens a read-transaction on the database and returns to state
39293 **    OPEN after the read-transaction is completed. However a connection
39294 **    running in locking_mode=exclusive (including temp databases) remains in
39295 **    this state even after the read-transaction is closed. The only way
39296 **    a locking_mode=exclusive connection can transition from READER to OPEN
39297 **    is via the ERROR state (see below).
39298 ** 
39299 **    * A read transaction may be active (but a write-transaction cannot).
39300 **    * A SHARED or greater lock is held on the database file.
39301 **    * The dbSize variable may be trusted (even if a user-level read 
39302 **      transaction is not active). The dbOrigSize and dbFileSize variables
39303 **      may not be trusted at this point.
39304 **    * If the database is a WAL database, then the WAL connection is open.
39305 **    * Even if a read-transaction is not open, it is guaranteed that 
39306 **      there is no hot-journal in the file-system.
39307 **
39308 **  WRITER_LOCKED:
39309 **
39310 **    The pager moves to this state from READER when a write-transaction
39311 **    is first opened on the database. In WRITER_LOCKED state, all locks 
39312 **    required to start a write-transaction are held, but no actual 
39313 **    modifications to the cache or database have taken place.
39314 **
39315 **    In rollback mode, a RESERVED or (if the transaction was opened with 
39316 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39317 **    moving to this state, but the journal file is not written to or opened 
39318 **    to in this state. If the transaction is committed or rolled back while 
39319 **    in WRITER_LOCKED state, all that is required is to unlock the database 
39320 **    file.
39321 **
39322 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39323 **    If the connection is running with locking_mode=exclusive, an attempt
39324 **    is made to obtain an EXCLUSIVE lock on the database file.
39325 **
39326 **    * A write transaction is active.
39327 **    * If the connection is open in rollback-mode, a RESERVED or greater 
39328 **      lock is held on the database file.
39329 **    * If the connection is open in WAL-mode, a WAL write transaction
39330 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
39331 **      called).
39332 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39333 **    * The contents of the pager cache have not been modified.
39334 **    * The journal file may or may not be open.
39335 **    * Nothing (not even the first header) has been written to the journal.
39336 **
39337 **  WRITER_CACHEMOD:
39338 **
39339 **    A pager moves from WRITER_LOCKED state to this state when a page is
39340 **    first modified by the upper layer. In rollback mode the journal file
39341 **    is opened (if it is not already open) and a header written to the
39342 **    start of it. The database file on disk has not been modified.
39343 **
39344 **    * A write transaction is active.
39345 **    * A RESERVED or greater lock is held on the database file.
39346 **    * The journal file is open and the first header has been written 
39347 **      to it, but the header has not been synced to disk.
39348 **    * The contents of the page cache have been modified.
39349 **
39350 **  WRITER_DBMOD:
39351 **
39352 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39353 **    when it modifies the contents of the database file. WAL connections
39354 **    never enter this state (since they do not modify the database file,
39355 **    just the log file).
39356 **
39357 **    * A write transaction is active.
39358 **    * An EXCLUSIVE or greater lock is held on the database file.
39359 **    * The journal file is open and the first header has been written 
39360 **      and synced to disk.
39361 **    * The contents of the page cache have been modified (and possibly
39362 **      written to disk).
39363 **
39364 **  WRITER_FINISHED:
39365 **
39366 **    It is not possible for a WAL connection to enter this state.
39367 **
39368 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39369 **    state after the entire transaction has been successfully written into the
39370 **    database file. In this state the transaction may be committed simply
39371 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
39372 **    not possible to modify the database further. At this point, the upper 
39373 **    layer must either commit or rollback the transaction.
39374 **
39375 **    * A write transaction is active.
39376 **    * An EXCLUSIVE or greater lock is held on the database file.
39377 **    * All writing and syncing of journal and database data has finished.
39378 **      If no error occurred, all that remains is to finalize the journal to
39379 **      commit the transaction. If an error did occur, the caller will need
39380 **      to rollback the transaction. 
39381 **
39382 **  ERROR:
39383 **
39384 **    The ERROR state is entered when an IO or disk-full error (including
39385 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
39386 **    difficult to be sure that the in-memory pager state (cache contents, 
39387 **    db size etc.) are consistent with the contents of the file-system.
39388 **
39389 **    Temporary pager files may enter the ERROR state, but in-memory pagers
39390 **    cannot.
39391 **
39392 **    For example, if an IO error occurs while performing a rollback, 
39393 **    the contents of the page-cache may be left in an inconsistent state.
39394 **    At this point it would be dangerous to change back to READER state
39395 **    (as usually happens after a rollback). Any subsequent readers might
39396 **    report database corruption (due to the inconsistent cache), and if
39397 **    they upgrade to writers, they may inadvertently corrupt the database
39398 **    file. To avoid this hazard, the pager switches into the ERROR state
39399 **    instead of READER following such an error.
39400 **
39401 **    Once it has entered the ERROR state, any attempt to use the pager
39402 **    to read or write data returns an error. Eventually, once all 
39403 **    outstanding transactions have been abandoned, the pager is able to
39404 **    transition back to OPEN state, discarding the contents of the 
39405 **    page-cache and any other in-memory state at the same time. Everything
39406 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39407 **    when a read-transaction is next opened on the pager (transitioning
39408 **    the pager into READER state). At that point the system has recovered 
39409 **    from the error.
39410 **
39411 **    Specifically, the pager jumps into the ERROR state if:
39412 **
39413 **      1. An error occurs while attempting a rollback. This happens in
39414 **         function sqlite3PagerRollback().
39415 **
39416 **      2. An error occurs while attempting to finalize a journal file
39417 **         following a commit in function sqlite3PagerCommitPhaseTwo().
39418 **
39419 **      3. An error occurs while attempting to write to the journal or
39420 **         database file in function pagerStress() in order to free up
39421 **         memory.
39422 **
39423 **    In other cases, the error is returned to the b-tree layer. The b-tree
39424 **    layer then attempts a rollback operation. If the error condition 
39425 **    persists, the pager enters the ERROR state via condition (1) above.
39426 **
39427 **    Condition (3) is necessary because it can be triggered by a read-only
39428 **    statement executed within a transaction. In this case, if the error
39429 **    code were simply returned to the user, the b-tree layer would not
39430 **    automatically attempt a rollback, as it assumes that an error in a
39431 **    read-only statement cannot leave the pager in an internally inconsistent 
39432 **    state.
39433 **
39434 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
39435 **    * There are one or more outstanding references to pages (after the
39436 **      last reference is dropped the pager should move back to OPEN state).
39437 **    * The pager is not an in-memory pager.
39438 **    
39439 **
39440 ** Notes:
39441 **
39442 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39443 **     connection is open in WAL mode. A WAL connection is always in one
39444 **     of the first four states.
39445 **
39446 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39447 **     state. There are two exceptions: immediately after exclusive-mode has
39448 **     been turned on (and before any read or write transactions are 
39449 **     executed), and when the pager is leaving the "error state".
39450 **
39451 **   * See also: assert_pager_state().
39452 */
39453 #define PAGER_OPEN                  0
39454 #define PAGER_READER                1
39455 #define PAGER_WRITER_LOCKED         2
39456 #define PAGER_WRITER_CACHEMOD       3
39457 #define PAGER_WRITER_DBMOD          4
39458 #define PAGER_WRITER_FINISHED       5
39459 #define PAGER_ERROR                 6
39460 
39461 /*
39462 ** The Pager.eLock variable is almost always set to one of the 
39463 ** following locking-states, according to the lock currently held on
39464 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39465 ** This variable is kept up to date as locks are taken and released by
39466 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39467 **
39468 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
39469 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
39470 ** the operation was successful. In these circumstances pagerLockDb() and
39471 ** pagerUnlockDb() take a conservative approach - eLock is always updated
39472 ** when unlocking the file, and only updated when locking the file if the
39473 ** VFS call is successful. This way, the Pager.eLock variable may be set
39474 ** to a less exclusive (lower) value than the lock that is actually held
39475 ** at the system level, but it is never set to a more exclusive value.
39476 **
39477 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
39478 ** be a few redundant xLock() calls or a lock may be held for longer than
39479 ** required, but nothing really goes wrong.
39480 **
39481 ** The exception is when the database file is unlocked as the pager moves
39482 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
39483 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
39484 ** transition, by the same pager or any other). If the call to xUnlock()
39485 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
39486 ** can confuse the call to xCheckReservedLock() call made later as part
39487 ** of hot-journal detection.
39488 **
39489 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
39490 ** lock held by this process or any others". So xCheckReservedLock may 
39491 ** return true because the caller itself is holding an EXCLUSIVE lock (but
39492 ** doesn't know it because of a previous error in xUnlock). If this happens
39493 ** a hot-journal may be mistaken for a journal being created by an active
39494 ** transaction in another process, causing SQLite to read from the database
39495 ** without rolling it back.
39496 **
39497 ** To work around this, if a call to xUnlock() fails when unlocking the
39498 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39499 ** is only changed back to a real locking state after a successful call
39500 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39501 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
39502 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
39503 ** lock on the database file before attempting to roll it back. See function
39504 ** PagerSharedLock() for more detail.
39505 **
39506 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
39507 ** PAGER_OPEN state.
39508 */
39509 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
39510 
39511 /*
39512 ** A macro used for invoking the codec if there is one
39513 */
39514 #ifdef SQLITE_HAS_CODEC
39515 # define CODEC1(P,D,N,X,E) \
39516     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
39517 # define CODEC2(P,D,N,X,E,O) \
39518     if( P->xCodec==0 ){ O=(char*)D; }else \
39519     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
39520 #else
39521 # define CODEC1(P,D,N,X,E)   /* NO-OP */
39522 # define CODEC2(P,D,N,X,E,O) O=(char*)D
39523 #endif
39524 
39525 /*
39526 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
39527 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
39528 ** This could conceivably cause corruption following a power failure on
39529 ** such a system. This is currently an undocumented limit.
39530 */
39531 #define MAX_SECTOR_SIZE 0x10000
39532 
39533 /*
39534 ** An instance of the following structure is allocated for each active
39535 ** savepoint and statement transaction in the system. All such structures
39536 ** are stored in the Pager.aSavepoint[] array, which is allocated and
39537 ** resized using sqlite3Realloc().
39538 **
39539 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
39540 ** set to 0. If a journal-header is written into the main journal while
39541 ** the savepoint is active, then iHdrOffset is set to the byte offset 
39542 ** immediately following the last journal record written into the main
39543 ** journal before the journal-header. This is required during savepoint
39544 ** rollback (see pagerPlaybackSavepoint()).
39545 */
39546 typedef struct PagerSavepoint PagerSavepoint;
39547 struct PagerSavepoint {
39548   i64 iOffset;                 /* Starting offset in main journal */
39549   i64 iHdrOffset;              /* See above */
39550   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
39551   Pgno nOrig;                  /* Original number of pages in file */
39552   Pgno iSubRec;                /* Index of first record in sub-journal */
39553 #ifndef SQLITE_OMIT_WAL
39554   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
39555 #endif
39556 };
39557 
39558 /*
39559 ** Bits of the Pager.doNotSpill flag.  See further description below.
39560 */
39561 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
39562 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
39563 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
39564 
39565 /*
39566 ** A open page cache is an instance of struct Pager. A description of
39567 ** some of the more important member variables follows:
39568 **
39569 ** eState
39570 **
39571 **   The current 'state' of the pager object. See the comment and state
39572 **   diagram above for a description of the pager state.
39573 **
39574 ** eLock
39575 **
39576 **   For a real on-disk database, the current lock held on the database file -
39577 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39578 **
39579 **   For a temporary or in-memory database (neither of which require any
39580 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
39581 **   databases always have Pager.exclusiveMode==1, this tricks the pager
39582 **   logic into thinking that it already has all the locks it will ever
39583 **   need (and no reason to release them).
39584 **
39585 **   In some (obscure) circumstances, this variable may also be set to
39586 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
39587 **   details.
39588 **
39589 ** changeCountDone
39590 **
39591 **   This boolean variable is used to make sure that the change-counter 
39592 **   (the 4-byte header field at byte offset 24 of the database file) is 
39593 **   not updated more often than necessary. 
39594 **
39595 **   It is set to true when the change-counter field is updated, which 
39596 **   can only happen if an exclusive lock is held on the database file.
39597 **   It is cleared (set to false) whenever an exclusive lock is 
39598 **   relinquished on the database file. Each time a transaction is committed,
39599 **   The changeCountDone flag is inspected. If it is true, the work of
39600 **   updating the change-counter is omitted for the current transaction.
39601 **
39602 **   This mechanism means that when running in exclusive mode, a connection 
39603 **   need only update the change-counter once, for the first transaction
39604 **   committed.
39605 **
39606 ** setMaster
39607 **
39608 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
39609 **   (or may not) specify a master-journal name to be written into the 
39610 **   journal file before it is synced to disk.
39611 **
39612 **   Whether or not a journal file contains a master-journal pointer affects 
39613 **   the way in which the journal file is finalized after the transaction is 
39614 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
39615 **   If a journal file does not contain a master-journal pointer, it is
39616 **   finalized by overwriting the first journal header with zeroes. If
39617 **   it does contain a master-journal pointer the journal file is finalized 
39618 **   by truncating it to zero bytes, just as if the connection were 
39619 **   running in "journal_mode=truncate" mode.
39620 **
39621 **   Journal files that contain master journal pointers cannot be finalized
39622 **   simply by overwriting the first journal-header with zeroes, as the
39623 **   master journal pointer could interfere with hot-journal rollback of any
39624 **   subsequently interrupted transaction that reuses the journal file.
39625 **
39626 **   The flag is cleared as soon as the journal file is finalized (either
39627 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
39628 **   journal file from being successfully finalized, the setMaster flag
39629 **   is cleared anyway (and the pager will move to ERROR state).
39630 **
39631 ** doNotSpill
39632 **
39633 **   This variables control the behavior of cache-spills  (calls made by
39634 **   the pcache module to the pagerStress() routine to write cached data
39635 **   to the file-system in order to free up memory).
39636 **
39637 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
39638 **   writing to the database from pagerStress() is disabled altogether.
39639 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
39640 **   comes up during savepoint rollback that requires the pcache module
39641 **   to allocate a new page to prevent the journal file from being written
39642 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
39643 **   case is a user preference.
39644 ** 
39645 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
39646 **   is permitted, but syncing the journal file is not. This flag is set
39647 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
39648 **   the database page-size in order to prevent a journal sync from happening 
39649 **   in between the journalling of two pages on the same sector. 
39650 **
39651 ** subjInMemory
39652 **
39653 **   This is a boolean variable. If true, then any required sub-journal
39654 **   is opened as an in-memory journal file. If false, then in-memory
39655 **   sub-journals are only used for in-memory pager files.
39656 **
39657 **   This variable is updated by the upper layer each time a new 
39658 **   write-transaction is opened.
39659 **
39660 ** dbSize, dbOrigSize, dbFileSize
39661 **
39662 **   Variable dbSize is set to the number of pages in the database file.
39663 **   It is valid in PAGER_READER and higher states (all states except for
39664 **   OPEN and ERROR). 
39665 **
39666 **   dbSize is set based on the size of the database file, which may be 
39667 **   larger than the size of the database (the value stored at offset
39668 **   28 of the database header by the btree). If the size of the file
39669 **   is not an integer multiple of the page-size, the value stored in
39670 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
39671 **   Except, any file that is greater than 0 bytes in size is considered
39672 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
39673 **   to dbSize==1).
39674 **
39675 **   During a write-transaction, if pages with page-numbers greater than
39676 **   dbSize are modified in the cache, dbSize is updated accordingly.
39677 **   Similarly, if the database is truncated using PagerTruncateImage(), 
39678 **   dbSize is updated.
39679 **
39680 **   Variables dbOrigSize and dbFileSize are valid in states 
39681 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
39682 **   variable at the start of the transaction. It is used during rollback,
39683 **   and to determine whether or not pages need to be journalled before
39684 **   being modified.
39685 **
39686 **   Throughout a write-transaction, dbFileSize contains the size of
39687 **   the file on disk in pages. It is set to a copy of dbSize when the
39688 **   write-transaction is first opened, and updated when VFS calls are made
39689 **   to write or truncate the database file on disk. 
39690 **
39691 **   The only reason the dbFileSize variable is required is to suppress 
39692 **   unnecessary calls to xTruncate() after committing a transaction. If, 
39693 **   when a transaction is committed, the dbFileSize variable indicates 
39694 **   that the database file is larger than the database image (Pager.dbSize), 
39695 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39696 **   to measure the database file on disk, and then truncates it if required.
39697 **   dbFileSize is not used when rolling back a transaction. In this case
39698 **   pager_truncate() is called unconditionally (which means there may be
39699 **   a call to xFilesize() that is not strictly required). In either case,
39700 **   pager_truncate() may cause the file to become smaller or larger.
39701 **
39702 ** dbHintSize
39703 **
39704 **   The dbHintSize variable is used to limit the number of calls made to
39705 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
39706 **
39707 **   dbHintSize is set to a copy of the dbSize variable when a
39708 **   write-transaction is opened (at the same time as dbFileSize and
39709 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39710 **   dbHintSize is increased to the number of pages that correspond to the
39711 **   size-hint passed to the method call. See pager_write_pagelist() for 
39712 **   details.
39713 **
39714 ** errCode
39715 **
39716 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39717 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
39718 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
39719 **   sub-codes.
39720 */
39721 struct Pager {
39722   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
39723   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39724   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39725   u8 useJournal;              /* Use a rollback journal on this file */
39726   u8 noSync;                  /* Do not sync the journal if true */
39727   u8 fullSync;                /* Do extra syncs of the journal for robustness */
39728   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39729   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
39730   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39731   u8 tempFile;                /* zFilename is a temporary file */
39732   u8 readOnly;                /* True for a read-only database */
39733   u8 memDb;                   /* True to inhibit all file I/O */
39734 
39735   /**************************************************************************
39736   ** The following block contains those class members that change during
39737   ** routine opertion.  Class members not in this block are either fixed
39738   ** when the pager is first created or else only change when there is a
39739   ** significant mode change (such as changing the page_size, locking_mode,
39740   ** or the journal_mode).  From another view, these class members describe
39741   ** the "state" of the pager, while other class members describe the
39742   ** "configuration" of the pager.
39743   */
39744   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
39745   u8 eLock;                   /* Current lock held on database file */
39746   u8 changeCountDone;         /* Set after incrementing the change-counter */
39747   u8 setMaster;               /* True if a m-j name has been written to jrnl */
39748   u8 doNotSpill;              /* Do not spill the cache when non-zero */
39749   u8 subjInMemory;            /* True to use in-memory sub-journals */
39750   Pgno dbSize;                /* Number of pages in the database */
39751   Pgno dbOrigSize;            /* dbSize before the current transaction */
39752   Pgno dbFileSize;            /* Number of pages in the database file */
39753   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
39754   int errCode;                /* One of several kinds of errors */
39755   int nRec;                   /* Pages journalled since last j-header written */
39756   u32 cksumInit;              /* Quasi-random value added to every checksum */
39757   u32 nSubRec;                /* Number of records written to sub-journal */
39758   Bitvec *pInJournal;         /* One bit for each page in the database file */
39759   sqlite3_file *fd;           /* File descriptor for database */
39760   sqlite3_file *jfd;          /* File descriptor for main journal */
39761   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
39762   i64 journalOff;             /* Current write offset in the journal file */
39763   i64 journalHdr;             /* Byte offset to previous journal header */
39764   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
39765   PagerSavepoint *aSavepoint; /* Array of active savepoints */
39766   int nSavepoint;             /* Number of elements in aSavepoint[] */
39767   char dbFileVers[16];        /* Changes whenever database file changes */
39768 
39769   u8 bUseFetch;               /* True to use xFetch() */
39770   int nMmapOut;               /* Number of mmap pages currently outstanding */
39771   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
39772   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
39773   /*
39774   ** End of the routinely-changing class members
39775   ***************************************************************************/
39776 
39777   u16 nExtra;                 /* Add this many bytes to each in-memory page */
39778   i16 nReserve;               /* Number of unused bytes at end of each page */
39779   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39780   u32 sectorSize;             /* Assumed sector size during rollback */
39781   int pageSize;               /* Number of bytes in a page */
39782   Pgno mxPgno;                /* Maximum allowed size of the database */
39783   i64 journalSizeLimit;       /* Size limit for persistent journal files */
39784   char *zFilename;            /* Name of the database file */
39785   char *zJournal;             /* Name of the journal file */
39786   int (*xBusyHandler)(void*); /* Function to call when busy */
39787   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39788   int aStat[3];               /* Total cache hits, misses and writes */
39789 #ifdef SQLITE_TEST
39790   int nRead;                  /* Database pages read */
39791 #endif
39792   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39793 #ifdef SQLITE_HAS_CODEC
39794   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39795   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39796   void (*xCodecFree)(void*);             /* Destructor for the codec */
39797   void *pCodec;               /* First argument to xCodec... methods */
39798 #endif
39799   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39800   PCache *pPCache;            /* Pointer to page cache object */
39801 #ifndef SQLITE_OMIT_WAL
39802   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39803   char *zWal;                 /* File name for write-ahead log */
39804 #endif
39805 };
39806 
39807 /*
39808 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
39809 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
39810 ** or CACHE_WRITE to sqlite3_db_status().
39811 */
39812 #define PAGER_STAT_HIT   0
39813 #define PAGER_STAT_MISS  1
39814 #define PAGER_STAT_WRITE 2
39815 
39816 /*
39817 ** The following global variables hold counters used for
39818 ** testing purposes only.  These variables do not exist in
39819 ** a non-testing build.  These variables are not thread-safe.
39820 */
39821 #ifdef SQLITE_TEST
39822 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39823 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39824 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39825 # define PAGER_INCR(v)  v++
39826 #else
39827 # define PAGER_INCR(v)
39828 #endif
39829 
39830 
39831 
39832 /*
39833 ** Journal files begin with the following magic string.  The data
39834 ** was obtained from /dev/random.  It is used only as a sanity check.
39835 **
39836 ** Since version 2.8.0, the journal format contains additional sanity
39837 ** checking information.  If the power fails while the journal is being
39838 ** written, semi-random garbage data might appear in the journal
39839 ** file after power is restored.  If an attempt is then made
39840 ** to roll the journal back, the database could be corrupted.  The additional
39841 ** sanity checking data is an attempt to discover the garbage in the
39842 ** journal and ignore it.
39843 **
39844 ** The sanity checking information for the new journal format consists
39845 ** of a 32-bit checksum on each page of data.  The checksum covers both
39846 ** the page number and the pPager->pageSize bytes of data for the page.
39847 ** This cksum is initialized to a 32-bit random value that appears in the
39848 ** journal file right after the header.  The random initializer is important,
39849 ** because garbage data that appears at the end of a journal is likely
39850 ** data that was once in other files that have now been deleted.  If the
39851 ** garbage data came from an obsolete journal file, the checksums might
39852 ** be correct.  But by initializing the checksum to random value which
39853 ** is different for every journal, we minimize that risk.
39854 */
39855 static const unsigned char aJournalMagic[] = {
39856   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39857 };
39858 
39859 /*
39860 ** The size of the of each page record in the journal is given by
39861 ** the following macro.
39862 */
39863 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39864 
39865 /*
39866 ** The journal header size for this pager. This is usually the same 
39867 ** size as a single disk sector. See also setSectorSize().
39868 */
39869 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39870 
39871 /*
39872 ** The macro MEMDB is true if we are dealing with an in-memory database.
39873 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39874 ** the value of MEMDB will be a constant and the compiler will optimize
39875 ** out code that would never execute.
39876 */
39877 #ifdef SQLITE_OMIT_MEMORYDB
39878 # define MEMDB 0
39879 #else
39880 # define MEMDB pPager->memDb
39881 #endif
39882 
39883 /*
39884 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
39885 ** interfaces to access the database using memory-mapped I/O.
39886 */
39887 #if SQLITE_MAX_MMAP_SIZE>0
39888 # define USEFETCH(x) ((x)->bUseFetch)
39889 #else
39890 # define USEFETCH(x) 0
39891 #endif
39892 
39893 /*
39894 ** The maximum legal page number is (2^31 - 1).
39895 */
39896 #define PAGER_MAX_PGNO 2147483647
39897 
39898 /*
39899 ** The argument to this macro is a file descriptor (type sqlite3_file*).
39900 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
39901 **
39902 ** This is so that expressions can be written as:
39903 **
39904 **   if( isOpen(pPager->jfd) ){ ...
39905 **
39906 ** instead of
39907 **
39908 **   if( pPager->jfd->pMethods ){ ...
39909 */
39910 #define isOpen(pFd) ((pFd)->pMethods)
39911 
39912 /*
39913 ** Return true if this pager uses a write-ahead log instead of the usual
39914 ** rollback journal. Otherwise false.
39915 */
39916 #ifndef SQLITE_OMIT_WAL
39917 static int pagerUseWal(Pager *pPager){
39918   return (pPager->pWal!=0);
39919 }
39920 #else
39921 # define pagerUseWal(x) 0
39922 # define pagerRollbackWal(x) 0
39923 # define pagerWalFrames(v,w,x,y) 0
39924 # define pagerOpenWalIfPresent(z) SQLITE_OK
39925 # define pagerBeginReadTransaction(z) SQLITE_OK
39926 #endif
39927 
39928 #ifndef NDEBUG 
39929 /*
39930 ** Usage:
39931 **
39932 **   assert( assert_pager_state(pPager) );
39933 **
39934 ** This function runs many asserts to try to find inconsistencies in
39935 ** the internal state of the Pager object.
39936 */
39937 static int assert_pager_state(Pager *p){
39938   Pager *pPager = p;
39939 
39940   /* State must be valid. */
39941   assert( p->eState==PAGER_OPEN
39942        || p->eState==PAGER_READER
39943        || p->eState==PAGER_WRITER_LOCKED
39944        || p->eState==PAGER_WRITER_CACHEMOD
39945        || p->eState==PAGER_WRITER_DBMOD
39946        || p->eState==PAGER_WRITER_FINISHED
39947        || p->eState==PAGER_ERROR
39948   );
39949 
39950   /* Regardless of the current state, a temp-file connection always behaves
39951   ** as if it has an exclusive lock on the database file. It never updates
39952   ** the change-counter field, so the changeCountDone flag is always set.
39953   */
39954   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39955   assert( p->tempFile==0 || pPager->changeCountDone );
39956 
39957   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
39958   ** And if the journal-mode is "OFF", the journal file must not be open.
39959   */
39960   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39961   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39962 
39963   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
39964   ** this means an in-memory pager performs no IO at all, it cannot encounter 
39965   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
39966   ** a journal file. (although the in-memory journal implementation may 
39967   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
39968   ** is therefore not possible for an in-memory pager to enter the ERROR 
39969   ** state.
39970   */
39971   if( MEMDB ){
39972     assert( p->noSync );
39973     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
39974          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
39975     );
39976     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39977     assert( pagerUseWal(p)==0 );
39978   }
39979 
39980   /* If changeCountDone is set, a RESERVED lock or greater must be held
39981   ** on the file.
39982   */
39983   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39984   assert( p->eLock!=PENDING_LOCK );
39985 
39986   switch( p->eState ){
39987     case PAGER_OPEN:
39988       assert( !MEMDB );
39989       assert( pPager->errCode==SQLITE_OK );
39990       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39991       break;
39992 
39993     case PAGER_READER:
39994       assert( pPager->errCode==SQLITE_OK );
39995       assert( p->eLock!=UNKNOWN_LOCK );
39996       assert( p->eLock>=SHARED_LOCK );
39997       break;
39998 
39999     case PAGER_WRITER_LOCKED:
40000       assert( p->eLock!=UNKNOWN_LOCK );
40001       assert( pPager->errCode==SQLITE_OK );
40002       if( !pagerUseWal(pPager) ){
40003         assert( p->eLock>=RESERVED_LOCK );
40004       }
40005       assert( pPager->dbSize==pPager->dbOrigSize );
40006       assert( pPager->dbOrigSize==pPager->dbFileSize );
40007       assert( pPager->dbOrigSize==pPager->dbHintSize );
40008       assert( pPager->setMaster==0 );
40009       break;
40010 
40011     case PAGER_WRITER_CACHEMOD:
40012       assert( p->eLock!=UNKNOWN_LOCK );
40013       assert( pPager->errCode==SQLITE_OK );
40014       if( !pagerUseWal(pPager) ){
40015         /* It is possible that if journal_mode=wal here that neither the
40016         ** journal file nor the WAL file are open. This happens during
40017         ** a rollback transaction that switches from journal_mode=off
40018         ** to journal_mode=wal.
40019         */
40020         assert( p->eLock>=RESERVED_LOCK );
40021         assert( isOpen(p->jfd) 
40022              || p->journalMode==PAGER_JOURNALMODE_OFF 
40023              || p->journalMode==PAGER_JOURNALMODE_WAL 
40024         );
40025       }
40026       assert( pPager->dbOrigSize==pPager->dbFileSize );
40027       assert( pPager->dbOrigSize==pPager->dbHintSize );
40028       break;
40029 
40030     case PAGER_WRITER_DBMOD:
40031       assert( p->eLock==EXCLUSIVE_LOCK );
40032       assert( pPager->errCode==SQLITE_OK );
40033       assert( !pagerUseWal(pPager) );
40034       assert( p->eLock>=EXCLUSIVE_LOCK );
40035       assert( isOpen(p->jfd) 
40036            || p->journalMode==PAGER_JOURNALMODE_OFF 
40037            || p->journalMode==PAGER_JOURNALMODE_WAL 
40038       );
40039       assert( pPager->dbOrigSize<=pPager->dbHintSize );
40040       break;
40041 
40042     case PAGER_WRITER_FINISHED:
40043       assert( p->eLock==EXCLUSIVE_LOCK );
40044       assert( pPager->errCode==SQLITE_OK );
40045       assert( !pagerUseWal(pPager) );
40046       assert( isOpen(p->jfd) 
40047            || p->journalMode==PAGER_JOURNALMODE_OFF 
40048            || p->journalMode==PAGER_JOURNALMODE_WAL 
40049       );
40050       break;
40051 
40052     case PAGER_ERROR:
40053       /* There must be at least one outstanding reference to the pager if
40054       ** in ERROR state. Otherwise the pager should have already dropped
40055       ** back to OPEN state.
40056       */
40057       assert( pPager->errCode!=SQLITE_OK );
40058       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
40059       break;
40060   }
40061 
40062   return 1;
40063 }
40064 #endif /* ifndef NDEBUG */
40065 
40066 #ifdef SQLITE_DEBUG 
40067 /*
40068 ** Return a pointer to a human readable string in a static buffer
40069 ** containing the state of the Pager object passed as an argument. This
40070 ** is intended to be used within debuggers. For example, as an alternative
40071 ** to "print *pPager" in gdb:
40072 **
40073 ** (gdb) printf "%s", print_pager_state(pPager)
40074 */
40075 static char *print_pager_state(Pager *p){
40076   static char zRet[1024];
40077 
40078   sqlite3_snprintf(1024, zRet,
40079       "Filename:      %s\n"
40080       "State:         %s errCode=%d\n"
40081       "Lock:          %s\n"
40082       "Locking mode:  locking_mode=%s\n"
40083       "Journal mode:  journal_mode=%s\n"
40084       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40085       "Journal:       journalOff=%lld journalHdr=%lld\n"
40086       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40087       , p->zFilename
40088       , p->eState==PAGER_OPEN            ? "OPEN" :
40089         p->eState==PAGER_READER          ? "READER" :
40090         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40091         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40092         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40093         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40094         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40095       , (int)p->errCode
40096       , p->eLock==NO_LOCK         ? "NO_LOCK" :
40097         p->eLock==RESERVED_LOCK   ? "RESERVED" :
40098         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40099         p->eLock==SHARED_LOCK     ? "SHARED" :
40100         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40101       , p->exclusiveMode ? "exclusive" : "normal"
40102       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40103         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40104         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40105         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40106         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40107         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40108       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40109       , p->journalOff, p->journalHdr
40110       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40111   );
40112 
40113   return zRet;
40114 }
40115 #endif
40116 
40117 /*
40118 ** Return true if it is necessary to write page *pPg into the sub-journal.
40119 ** A page needs to be written into the sub-journal if there exists one
40120 ** or more open savepoints for which:
40121 **
40122 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40123 **   * The bit corresponding to the page-number is not set in
40124 **     PagerSavepoint.pInSavepoint.
40125 */
40126 static int subjRequiresPage(PgHdr *pPg){
40127   Pager *pPager = pPg->pPager;
40128   PagerSavepoint *p;
40129   Pgno pgno;
40130   int i;
40131   if( pPager->nSavepoint ){
40132     pgno = pPg->pgno;
40133     for(i=0; i<pPager->nSavepoint; i++){
40134       p = &pPager->aSavepoint[i];
40135       if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
40136         return 1;
40137       }
40138     }
40139   }
40140   return 0;
40141 }
40142 
40143 /*
40144 ** Return true if the page is already in the journal file.
40145 */
40146 static int pageInJournal(PgHdr *pPg){
40147   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
40148 }
40149 
40150 /*
40151 ** Read a 32-bit integer from the given file descriptor.  Store the integer
40152 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
40153 ** error code is something goes wrong.
40154 **
40155 ** All values are stored on disk as big-endian.
40156 */
40157 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
40158   unsigned char ac[4];
40159   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
40160   if( rc==SQLITE_OK ){
40161     *pRes = sqlite3Get4byte(ac);
40162   }
40163   return rc;
40164 }
40165 
40166 /*
40167 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40168 */
40169 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
40170 
40171 
40172 /*
40173 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
40174 ** on success or an error code is something goes wrong.
40175 */
40176 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
40177   char ac[4];
40178   put32bits(ac, val);
40179   return sqlite3OsWrite(fd, ac, 4, offset);
40180 }
40181 
40182 /*
40183 ** Unlock the database file to level eLock, which must be either NO_LOCK
40184 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40185 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40186 **
40187 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40188 ** called, do not modify it. See the comment above the #define of 
40189 ** UNKNOWN_LOCK for an explanation of this.
40190 */
40191 static int pagerUnlockDb(Pager *pPager, int eLock){
40192   int rc = SQLITE_OK;
40193 
40194   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40195   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40196   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40197   if( isOpen(pPager->fd) ){
40198     assert( pPager->eLock>=eLock );
40199     rc = sqlite3OsUnlock(pPager->fd, eLock);
40200     if( pPager->eLock!=UNKNOWN_LOCK ){
40201       pPager->eLock = (u8)eLock;
40202     }
40203     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40204   }
40205   return rc;
40206 }
40207 
40208 /*
40209 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40210 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40211 ** Pager.eLock variable to the new locking state. 
40212 **
40213 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
40214 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
40215 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
40216 ** of this.
40217 */
40218 static int pagerLockDb(Pager *pPager, int eLock){
40219   int rc = SQLITE_OK;
40220 
40221   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40222   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40223     rc = sqlite3OsLock(pPager->fd, eLock);
40224     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40225       pPager->eLock = (u8)eLock;
40226       IOTRACE(("LOCK %p %d\n", pPager, eLock))
40227     }
40228   }
40229   return rc;
40230 }
40231 
40232 /*
40233 ** This function determines whether or not the atomic-write optimization
40234 ** can be used with this pager. The optimization can be used if:
40235 **
40236 **  (a) the value returned by OsDeviceCharacteristics() indicates that
40237 **      a database page may be written atomically, and
40238 **  (b) the value returned by OsSectorSize() is less than or equal
40239 **      to the page size.
40240 **
40241 ** The optimization is also always enabled for temporary files. It is
40242 ** an error to call this function if pPager is opened on an in-memory
40243 ** database.
40244 **
40245 ** If the optimization cannot be used, 0 is returned. If it can be used,
40246 ** then the value returned is the size of the journal file when it
40247 ** contains rollback data for exactly one page.
40248 */
40249 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40250 static int jrnlBufferSize(Pager *pPager){
40251   assert( !MEMDB );
40252   if( !pPager->tempFile ){
40253     int dc;                           /* Device characteristics */
40254     int nSector;                      /* Sector size */
40255     int szPage;                       /* Page size */
40256 
40257     assert( isOpen(pPager->fd) );
40258     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
40259     nSector = pPager->sectorSize;
40260     szPage = pPager->pageSize;
40261 
40262     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40263     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40264     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40265       return 0;
40266     }
40267   }
40268 
40269   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40270 }
40271 #endif
40272 
40273 /*
40274 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
40275 ** on the cache using a hash function.  This is used for testing
40276 ** and debugging only.
40277 */
40278 #ifdef SQLITE_CHECK_PAGES
40279 /*
40280 ** Return a 32-bit hash of the page data for pPage.
40281 */
40282 static u32 pager_datahash(int nByte, unsigned char *pData){
40283   u32 hash = 0;
40284   int i;
40285   for(i=0; i<nByte; i++){
40286     hash = (hash*1039) + pData[i];
40287   }
40288   return hash;
40289 }
40290 static u32 pager_pagehash(PgHdr *pPage){
40291   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40292 }
40293 static void pager_set_pagehash(PgHdr *pPage){
40294   pPage->pageHash = pager_pagehash(pPage);
40295 }
40296 
40297 /*
40298 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
40299 ** is defined, and NDEBUG is not defined, an assert() statement checks
40300 ** that the page is either dirty or still matches the calculated page-hash.
40301 */
40302 #define CHECK_PAGE(x) checkPage(x)
40303 static void checkPage(PgHdr *pPg){
40304   Pager *pPager = pPg->pPager;
40305   assert( pPager->eState!=PAGER_ERROR );
40306   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40307 }
40308 
40309 #else
40310 #define pager_datahash(X,Y)  0
40311 #define pager_pagehash(X)  0
40312 #define pager_set_pagehash(X)
40313 #define CHECK_PAGE(x)
40314 #endif  /* SQLITE_CHECK_PAGES */
40315 
40316 /*
40317 ** When this is called the journal file for pager pPager must be open.
40318 ** This function attempts to read a master journal file name from the 
40319 ** end of the file and, if successful, copies it into memory supplied 
40320 ** by the caller. See comments above writeMasterJournal() for the format
40321 ** used to store a master journal file name at the end of a journal file.
40322 **
40323 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40324 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
40325 ** enough space to write the master journal name). If the master journal
40326 ** name in the journal is longer than nMaster bytes (including a
40327 ** nul-terminator), then this is handled as if no master journal name
40328 ** were present in the journal.
40329 **
40330 ** If a master journal file name is present at the end of the journal
40331 ** file, then it is copied into the buffer pointed to by zMaster. A
40332 ** nul-terminator byte is appended to the buffer following the master
40333 ** journal file name.
40334 **
40335 ** If it is determined that no master journal file name is present 
40336 ** zMaster[0] is set to 0 and SQLITE_OK returned.
40337 **
40338 ** If an error occurs while reading from the journal file, an SQLite
40339 ** error code is returned.
40340 */
40341 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
40342   int rc;                    /* Return code */
40343   u32 len;                   /* Length in bytes of master journal name */
40344   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
40345   u32 cksum;                 /* MJ checksum value read from journal */
40346   u32 u;                     /* Unsigned loop counter */
40347   unsigned char aMagic[8];   /* A buffer to hold the magic header */
40348   zMaster[0] = '\0';
40349 
40350   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
40351    || szJ<16
40352    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40353    || len>=nMaster 
40354    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40355    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
40356    || memcmp(aMagic, aJournalMagic, 8)
40357    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
40358   ){
40359     return rc;
40360   }
40361 
40362   /* See if the checksum matches the master journal name */
40363   for(u=0; u<len; u++){
40364     cksum -= zMaster[u];
40365   }
40366   if( cksum ){
40367     /* If the checksum doesn't add up, then one or more of the disk sectors
40368     ** containing the master journal filename is corrupted. This means
40369     ** definitely roll back, so just return SQLITE_OK and report a (nul)
40370     ** master-journal filename.
40371     */
40372     len = 0;
40373   }
40374   zMaster[len] = '\0';
40375    
40376   return SQLITE_OK;
40377 }
40378 
40379 /*
40380 ** Return the offset of the sector boundary at or immediately 
40381 ** following the value in pPager->journalOff, assuming a sector 
40382 ** size of pPager->sectorSize bytes.
40383 **
40384 ** i.e for a sector size of 512:
40385 **
40386 **   Pager.journalOff          Return value
40387 **   ---------------------------------------
40388 **   0                         0
40389 **   512                       512
40390 **   100                       512
40391 **   2000                      2048
40392 ** 
40393 */
40394 static i64 journalHdrOffset(Pager *pPager){
40395   i64 offset = 0;
40396   i64 c = pPager->journalOff;
40397   if( c ){
40398     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40399   }
40400   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40401   assert( offset>=c );
40402   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40403   return offset;
40404 }
40405 
40406 /*
40407 ** The journal file must be open when this function is called.
40408 **
40409 ** This function is a no-op if the journal file has not been written to
40410 ** within the current transaction (i.e. if Pager.journalOff==0).
40411 **
40412 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40413 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40414 ** zero the 28-byte header at the start of the journal file. In either case, 
40415 ** if the pager is not in no-sync mode, sync the journal file immediately 
40416 ** after writing or truncating it.
40417 **
40418 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40419 ** following the truncation or zeroing described above the size of the 
40420 ** journal file in bytes is larger than this value, then truncate the
40421 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40422 ** not need to be synced following this operation.
40423 **
40424 ** If an IO error occurs, abandon processing and return the IO error code.
40425 ** Otherwise, return SQLITE_OK.
40426 */
40427 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40428   int rc = SQLITE_OK;                               /* Return code */
40429   assert( isOpen(pPager->jfd) );
40430   if( pPager->journalOff ){
40431     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
40432 
40433     IOTRACE(("JZEROHDR %p\n", pPager))
40434     if( doTruncate || iLimit==0 ){
40435       rc = sqlite3OsTruncate(pPager->jfd, 0);
40436     }else{
40437       static const char zeroHdr[28] = {0};
40438       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40439     }
40440     if( rc==SQLITE_OK && !pPager->noSync ){
40441       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
40442     }
40443 
40444     /* At this point the transaction is committed but the write lock 
40445     ** is still held on the file. If there is a size limit configured for 
40446     ** the persistent journal and the journal file currently consumes more
40447     ** space than that limit allows for, truncate it now. There is no need
40448     ** to sync the file following this operation.
40449     */
40450     if( rc==SQLITE_OK && iLimit>0 ){
40451       i64 sz;
40452       rc = sqlite3OsFileSize(pPager->jfd, &sz);
40453       if( rc==SQLITE_OK && sz>iLimit ){
40454         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
40455       }
40456     }
40457   }
40458   return rc;
40459 }
40460 
40461 /*
40462 ** The journal file must be open when this routine is called. A journal
40463 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40464 ** current location.
40465 **
40466 ** The format for the journal header is as follows:
40467 ** - 8 bytes: Magic identifying journal format.
40468 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40469 ** - 4 bytes: Random number used for page hash.
40470 ** - 4 bytes: Initial database page count.
40471 ** - 4 bytes: Sector size used by the process that wrote this journal.
40472 ** - 4 bytes: Database page size.
40473 ** 
40474 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40475 */
40476 static int writeJournalHdr(Pager *pPager){
40477   int rc = SQLITE_OK;                 /* Return code */
40478   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
40479   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40480   u32 nWrite;                         /* Bytes of header sector written */
40481   int ii;                             /* Loop counter */
40482 
40483   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40484 
40485   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40486     nHeader = JOURNAL_HDR_SZ(pPager);
40487   }
40488 
40489   /* If there are active savepoints and any of them were created 
40490   ** since the most recent journal header was written, update the 
40491   ** PagerSavepoint.iHdrOffset fields now.
40492   */
40493   for(ii=0; ii<pPager->nSavepoint; ii++){
40494     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40495       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40496     }
40497   }
40498 
40499   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
40500 
40501   /* 
40502   ** Write the nRec Field - the number of page records that follow this
40503   ** journal header. Normally, zero is written to this value at this time.
40504   ** After the records are added to the journal (and the journal synced, 
40505   ** if in full-sync mode), the zero is overwritten with the true number
40506   ** of records (see syncJournal()).
40507   **
40508   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
40509   ** reading the journal this value tells SQLite to assume that the
40510   ** rest of the journal file contains valid page records. This assumption
40511   ** is dangerous, as if a failure occurred whilst writing to the journal
40512   ** file it may contain some garbage data. There are two scenarios
40513   ** where this risk can be ignored:
40514   **
40515   **   * When the pager is in no-sync mode. Corruption can follow a
40516   **     power failure in this case anyway.
40517   **
40518   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
40519   **     that garbage data is never appended to the journal file.
40520   */
40521   assert( isOpen(pPager->fd) || pPager->noSync );
40522   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
40523    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
40524   ){
40525     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40526     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
40527   }else{
40528     memset(zHeader, 0, sizeof(aJournalMagic)+4);
40529   }
40530 
40531   /* The random check-hash initializer */ 
40532   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
40533   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
40534   /* The initial database size */
40535   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
40536   /* The assumed sector size for this process */
40537   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
40538 
40539   /* The page size */
40540   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
40541 
40542   /* Initializing the tail of the buffer is not necessary.  Everything
40543   ** works find if the following memset() is omitted.  But initializing
40544   ** the memory prevents valgrind from complaining, so we are willing to
40545   ** take the performance hit.
40546   */
40547   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
40548          nHeader-(sizeof(aJournalMagic)+20));
40549 
40550   /* In theory, it is only necessary to write the 28 bytes that the 
40551   ** journal header consumes to the journal file here. Then increment the 
40552   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
40553   ** record is written to the following sector (leaving a gap in the file
40554   ** that will be implicitly filled in by the OS).
40555   **
40556   ** However it has been discovered that on some systems this pattern can 
40557   ** be significantly slower than contiguously writing data to the file,
40558   ** even if that means explicitly writing data to the block of 
40559   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
40560   ** is done. 
40561   **
40562   ** The loop is required here in case the sector-size is larger than the 
40563   ** database page size. Since the zHeader buffer is only Pager.pageSize
40564   ** bytes in size, more than one call to sqlite3OsWrite() may be required
40565   ** to populate the entire journal header sector.
40566   */ 
40567   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
40568     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
40569     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
40570     assert( pPager->journalHdr <= pPager->journalOff );
40571     pPager->journalOff += nHeader;
40572   }
40573 
40574   return rc;
40575 }
40576 
40577 /*
40578 ** The journal file must be open when this is called. A journal header file
40579 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
40580 ** file. The current location in the journal file is given by
40581 ** pPager->journalOff. See comments above function writeJournalHdr() for
40582 ** a description of the journal header format.
40583 **
40584 ** If the header is read successfully, *pNRec is set to the number of
40585 ** page records following this header and *pDbSize is set to the size of the
40586 ** database before the transaction began, in pages. Also, pPager->cksumInit
40587 ** is set to the value read from the journal header. SQLITE_OK is returned
40588 ** in this case.
40589 **
40590 ** If the journal header file appears to be corrupted, SQLITE_DONE is
40591 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
40592 ** cannot be read from the journal file an error code is returned.
40593 */
40594 static int readJournalHdr(
40595   Pager *pPager,               /* Pager object */
40596   int isHot,
40597   i64 journalSize,             /* Size of the open journal file in bytes */
40598   u32 *pNRec,                  /* OUT: Value read from the nRec field */
40599   u32 *pDbSize                 /* OUT: Value of original database size field */
40600 ){
40601   int rc;                      /* Return code */
40602   unsigned char aMagic[8];     /* A buffer to hold the magic header */
40603   i64 iHdrOff;                 /* Offset of journal header being read */
40604 
40605   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40606 
40607   /* Advance Pager.journalOff to the start of the next sector. If the
40608   ** journal file is too small for there to be a header stored at this
40609   ** point, return SQLITE_DONE.
40610   */
40611   pPager->journalOff = journalHdrOffset(pPager);
40612   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
40613     return SQLITE_DONE;
40614   }
40615   iHdrOff = pPager->journalOff;
40616 
40617   /* Read in the first 8 bytes of the journal header. If they do not match
40618   ** the  magic string found at the start of each journal header, return
40619   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
40620   ** proceed.
40621   */
40622   if( isHot || iHdrOff!=pPager->journalHdr ){
40623     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
40624     if( rc ){
40625       return rc;
40626     }
40627     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
40628       return SQLITE_DONE;
40629     }
40630   }
40631 
40632   /* Read the first three 32-bit fields of the journal header: The nRec
40633   ** field, the checksum-initializer and the database size at the start
40634   ** of the transaction. Return an error code if anything goes wrong.
40635   */
40636   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
40637    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
40638    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
40639   ){
40640     return rc;
40641   }
40642 
40643   if( pPager->journalOff==0 ){
40644     u32 iPageSize;               /* Page-size field of journal header */
40645     u32 iSectorSize;             /* Sector-size field of journal header */
40646 
40647     /* Read the page-size and sector-size journal header fields. */
40648     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
40649      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
40650     ){
40651       return rc;
40652     }
40653 
40654     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
40655     ** journal header to zero. In this case, assume that the Pager.pageSize
40656     ** variable is already set to the correct page size.
40657     */
40658     if( iPageSize==0 ){
40659       iPageSize = pPager->pageSize;
40660     }
40661 
40662     /* Check that the values read from the page-size and sector-size fields
40663     ** are within range. To be 'in range', both values need to be a power
40664     ** of two greater than or equal to 512 or 32, and not greater than their 
40665     ** respective compile time maximum limits.
40666     */
40667     if( iPageSize<512                  || iSectorSize<32
40668      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
40669      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
40670     ){
40671       /* If the either the page-size or sector-size in the journal-header is 
40672       ** invalid, then the process that wrote the journal-header must have 
40673       ** crashed before the header was synced. In this case stop reading 
40674       ** the journal file here.
40675       */
40676       return SQLITE_DONE;
40677     }
40678 
40679     /* Update the page-size to match the value read from the journal. 
40680     ** Use a testcase() macro to make sure that malloc failure within 
40681     ** PagerSetPagesize() is tested.
40682     */
40683     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
40684     testcase( rc!=SQLITE_OK );
40685 
40686     /* Update the assumed sector-size to match the value used by 
40687     ** the process that created this journal. If this journal was
40688     ** created by a process other than this one, then this routine
40689     ** is being called from within pager_playback(). The local value
40690     ** of Pager.sectorSize is restored at the end of that routine.
40691     */
40692     pPager->sectorSize = iSectorSize;
40693   }
40694 
40695   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
40696   return rc;
40697 }
40698 
40699 
40700 /*
40701 ** Write the supplied master journal name into the journal file for pager
40702 ** pPager at the current location. The master journal name must be the last
40703 ** thing written to a journal file. If the pager is in full-sync mode, the
40704 ** journal file descriptor is advanced to the next sector boundary before
40705 ** anything is written. The format is:
40706 **
40707 **   + 4 bytes: PAGER_MJ_PGNO.
40708 **   + N bytes: Master journal filename in utf-8.
40709 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
40710 **   + 4 bytes: Master journal name checksum.
40711 **   + 8 bytes: aJournalMagic[].
40712 **
40713 ** The master journal page checksum is the sum of the bytes in the master
40714 ** journal name, where each byte is interpreted as a signed 8-bit integer.
40715 **
40716 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
40717 ** this call is a no-op.
40718 */
40719 static int writeMasterJournal(Pager *pPager, const char *zMaster){
40720   int rc;                          /* Return code */
40721   int nMaster;                     /* Length of string zMaster */
40722   i64 iHdrOff;                     /* Offset of header in journal file */
40723   i64 jrnlSize;                    /* Size of journal file on disk */
40724   u32 cksum = 0;                   /* Checksum of string zMaster */
40725 
40726   assert( pPager->setMaster==0 );
40727   assert( !pagerUseWal(pPager) );
40728 
40729   if( !zMaster 
40730    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
40731    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40732   ){
40733     return SQLITE_OK;
40734   }
40735   pPager->setMaster = 1;
40736   assert( isOpen(pPager->jfd) );
40737   assert( pPager->journalHdr <= pPager->journalOff );
40738 
40739   /* Calculate the length in bytes and the checksum of zMaster */
40740   for(nMaster=0; zMaster[nMaster]; nMaster++){
40741     cksum += zMaster[nMaster];
40742   }
40743 
40744   /* If in full-sync mode, advance to the next disk sector before writing
40745   ** the master journal name. This is in case the previous page written to
40746   ** the journal has already been synced.
40747   */
40748   if( pPager->fullSync ){
40749     pPager->journalOff = journalHdrOffset(pPager);
40750   }
40751   iHdrOff = pPager->journalOff;
40752 
40753   /* Write the master journal data to the end of the journal file. If
40754   ** an error occurs, return the error code to the caller.
40755   */
40756   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40757    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40758    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40759    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40760    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
40761   ){
40762     return rc;
40763   }
40764   pPager->journalOff += (nMaster+20);
40765 
40766   /* If the pager is in peristent-journal mode, then the physical 
40767   ** journal-file may extend past the end of the master-journal name
40768   ** and 8 bytes of magic data just written to the file. This is 
40769   ** dangerous because the code to rollback a hot-journal file
40770   ** will not be able to find the master-journal name to determine 
40771   ** whether or not the journal is hot. 
40772   **
40773   ** Easiest thing to do in this scenario is to truncate the journal 
40774   ** file to the required size.
40775   */ 
40776   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
40777    && jrnlSize>pPager->journalOff
40778   ){
40779     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40780   }
40781   return rc;
40782 }
40783 
40784 /*
40785 ** Find a page in the hash table given its page number. Return
40786 ** a pointer to the page or NULL if the requested page is not 
40787 ** already in memory.
40788 */
40789 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40790   PgHdr *p;                         /* Return value */
40791 
40792   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40793   ** fail, since no attempt to allocate dynamic memory will be made.
40794   */
40795   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40796   return p;
40797 }
40798 
40799 /*
40800 ** Discard the entire contents of the in-memory page-cache.
40801 */
40802 static void pager_reset(Pager *pPager){
40803   sqlite3BackupRestart(pPager->pBackup);
40804   sqlite3PcacheClear(pPager->pPCache);
40805 }
40806 
40807 /*
40808 ** Free all structures in the Pager.aSavepoint[] array and set both
40809 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40810 ** if it is open and the pager is not in exclusive mode.
40811 */
40812 static void releaseAllSavepoints(Pager *pPager){
40813   int ii;               /* Iterator for looping through Pager.aSavepoint */
40814   for(ii=0; ii<pPager->nSavepoint; ii++){
40815     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40816   }
40817   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40818     sqlite3OsClose(pPager->sjfd);
40819   }
40820   sqlite3_free(pPager->aSavepoint);
40821   pPager->aSavepoint = 0;
40822   pPager->nSavepoint = 0;
40823   pPager->nSubRec = 0;
40824 }
40825 
40826 /*
40827 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
40828 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
40829 ** or SQLITE_NOMEM if a malloc failure occurs.
40830 */
40831 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40832   int ii;                   /* Loop counter */
40833   int rc = SQLITE_OK;       /* Result code */
40834 
40835   for(ii=0; ii<pPager->nSavepoint; ii++){
40836     PagerSavepoint *p = &pPager->aSavepoint[ii];
40837     if( pgno<=p->nOrig ){
40838       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40839       testcase( rc==SQLITE_NOMEM );
40840       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40841     }
40842   }
40843   return rc;
40844 }
40845 
40846 /*
40847 ** This function is a no-op if the pager is in exclusive mode and not
40848 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40849 ** state.
40850 **
40851 ** If the pager is not in exclusive-access mode, the database file is
40852 ** completely unlocked. If the file is unlocked and the file-system does
40853 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40854 ** closed (if it is open).
40855 **
40856 ** If the pager is in ERROR state when this function is called, the 
40857 ** contents of the pager cache are discarded before switching back to 
40858 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
40859 ** or not, any journal file left in the file-system will be treated
40860 ** as a hot-journal and rolled back the next time a read-transaction
40861 ** is opened (by this or by any other connection).
40862 */
40863 static void pager_unlock(Pager *pPager){
40864 
40865   assert( pPager->eState==PAGER_READER 
40866        || pPager->eState==PAGER_OPEN 
40867        || pPager->eState==PAGER_ERROR 
40868   );
40869 
40870   sqlite3BitvecDestroy(pPager->pInJournal);
40871   pPager->pInJournal = 0;
40872   releaseAllSavepoints(pPager);
40873 
40874   if( pagerUseWal(pPager) ){
40875     assert( !isOpen(pPager->jfd) );
40876     sqlite3WalEndReadTransaction(pPager->pWal);
40877     pPager->eState = PAGER_OPEN;
40878   }else if( !pPager->exclusiveMode ){
40879     int rc;                       /* Error code returned by pagerUnlockDb() */
40880     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40881 
40882     /* If the operating system support deletion of open files, then
40883     ** close the journal file when dropping the database lock.  Otherwise
40884     ** another connection with journal_mode=delete might delete the file
40885     ** out from under us.
40886     */
40887     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
40888     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
40889     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
40890     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
40891     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40892     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
40893     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40894      || 1!=(pPager->journalMode & 5)
40895     ){
40896       sqlite3OsClose(pPager->jfd);
40897     }
40898 
40899     /* If the pager is in the ERROR state and the call to unlock the database
40900     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40901     ** above the #define for UNKNOWN_LOCK for an explanation of why this
40902     ** is necessary.
40903     */
40904     rc = pagerUnlockDb(pPager, NO_LOCK);
40905     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40906       pPager->eLock = UNKNOWN_LOCK;
40907     }
40908 
40909     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40910     ** without clearing the error code. This is intentional - the error
40911     ** code is cleared and the cache reset in the block below.
40912     */
40913     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40914     pPager->changeCountDone = 0;
40915     pPager->eState = PAGER_OPEN;
40916   }
40917 
40918   /* If Pager.errCode is set, the contents of the pager cache cannot be
40919   ** trusted. Now that there are no outstanding references to the pager,
40920   ** it can safely move back to PAGER_OPEN state. This happens in both
40921   ** normal and exclusive-locking mode.
40922   */
40923   if( pPager->errCode ){
40924     assert( !MEMDB );
40925     pager_reset(pPager);
40926     pPager->changeCountDone = pPager->tempFile;
40927     pPager->eState = PAGER_OPEN;
40928     pPager->errCode = SQLITE_OK;
40929     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
40930   }
40931 
40932   pPager->journalOff = 0;
40933   pPager->journalHdr = 0;
40934   pPager->setMaster = 0;
40935 }
40936 
40937 /*
40938 ** This function is called whenever an IOERR or FULL error that requires
40939 ** the pager to transition into the ERROR state may ahve occurred.
40940 ** The first argument is a pointer to the pager structure, the second 
40941 ** the error-code about to be returned by a pager API function. The 
40942 ** value returned is a copy of the second argument to this function. 
40943 **
40944 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40945 ** IOERR sub-codes, the pager enters the ERROR state and the error code
40946 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
40947 ** all major API calls on the Pager will immediately return Pager.errCode.
40948 **
40949 ** The ERROR state indicates that the contents of the pager-cache 
40950 ** cannot be trusted. This state can be cleared by completely discarding 
40951 ** the contents of the pager-cache. If a transaction was active when
40952 ** the persistent error occurred, then the rollback journal may need
40953 ** to be replayed to restore the contents of the database file (as if
40954 ** it were a hot-journal).
40955 */
40956 static int pager_error(Pager *pPager, int rc){
40957   int rc2 = rc & 0xff;
40958   assert( rc==SQLITE_OK || !MEMDB );
40959   assert(
40960        pPager->errCode==SQLITE_FULL ||
40961        pPager->errCode==SQLITE_OK ||
40962        (pPager->errCode & 0xff)==SQLITE_IOERR
40963   );
40964   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40965     pPager->errCode = rc;
40966     pPager->eState = PAGER_ERROR;
40967   }
40968   return rc;
40969 }
40970 
40971 static int pager_truncate(Pager *pPager, Pgno nPage);
40972 
40973 /*
40974 ** This routine ends a transaction. A transaction is usually ended by 
40975 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
40976 ** after rollback of a hot-journal, or if an error occurs while opening
40977 ** the journal file or writing the very first journal-header of a
40978 ** database transaction.
40979 ** 
40980 ** This routine is never called in PAGER_ERROR state. If it is called
40981 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40982 ** exclusive than a RESERVED lock, it is a no-op.
40983 **
40984 ** Otherwise, any active savepoints are released.
40985 **
40986 ** If the journal file is open, then it is "finalized". Once a journal 
40987 ** file has been finalized it is not possible to use it to roll back a 
40988 ** transaction. Nor will it be considered to be a hot-journal by this
40989 ** or any other database connection. Exactly how a journal is finalized
40990 ** depends on whether or not the pager is running in exclusive mode and
40991 ** the current journal-mode (Pager.journalMode value), as follows:
40992 **
40993 **   journalMode==MEMORY
40994 **     Journal file descriptor is simply closed. This destroys an 
40995 **     in-memory journal.
40996 **
40997 **   journalMode==TRUNCATE
40998 **     Journal file is truncated to zero bytes in size.
40999 **
41000 **   journalMode==PERSIST
41001 **     The first 28 bytes of the journal file are zeroed. This invalidates
41002 **     the first journal header in the file, and hence the entire journal
41003 **     file. An invalid journal file cannot be rolled back.
41004 **
41005 **   journalMode==DELETE
41006 **     The journal file is closed and deleted using sqlite3OsDelete().
41007 **
41008 **     If the pager is running in exclusive mode, this method of finalizing
41009 **     the journal file is never used. Instead, if the journalMode is
41010 **     DELETE and the pager is in exclusive mode, the method described under
41011 **     journalMode==PERSIST is used instead.
41012 **
41013 ** After the journal is finalized, the pager moves to PAGER_READER state.
41014 ** If running in non-exclusive rollback mode, the lock on the file is 
41015 ** downgraded to a SHARED_LOCK.
41016 **
41017 ** SQLITE_OK is returned if no error occurs. If an error occurs during
41018 ** any of the IO operations to finalize the journal file or unlock the
41019 ** database then the IO error code is returned to the user. If the 
41020 ** operation to finalize the journal file fails, then the code still
41021 ** tries to unlock the database file if not in exclusive mode. If the
41022 ** unlock operation fails as well, then the first error code related
41023 ** to the first error encountered (the journal finalization one) is
41024 ** returned.
41025 */
41026 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
41027   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
41028   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
41029 
41030   /* Do nothing if the pager does not have an open write transaction
41031   ** or at least a RESERVED lock. This function may be called when there
41032   ** is no write-transaction active but a RESERVED or greater lock is
41033   ** held under two circumstances:
41034   **
41035   **   1. After a successful hot-journal rollback, it is called with
41036   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41037   **
41038   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
41039   **      lock switches back to locking_mode=normal and then executes a
41040   **      read-transaction, this function is called with eState==PAGER_READER 
41041   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41042   */
41043   assert( assert_pager_state(pPager) );
41044   assert( pPager->eState!=PAGER_ERROR );
41045   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41046     return SQLITE_OK;
41047   }
41048 
41049   releaseAllSavepoints(pPager);
41050   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41051   if( isOpen(pPager->jfd) ){
41052     assert( !pagerUseWal(pPager) );
41053 
41054     /* Finalize the journal file. */
41055     if( sqlite3IsMemJournal(pPager->jfd) ){
41056       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41057       sqlite3OsClose(pPager->jfd);
41058     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41059       if( pPager->journalOff==0 ){
41060         rc = SQLITE_OK;
41061       }else{
41062         rc = sqlite3OsTruncate(pPager->jfd, 0);
41063       }
41064       pPager->journalOff = 0;
41065     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41066       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41067     ){
41068       rc = zeroJournalHdr(pPager, hasMaster);
41069       pPager->journalOff = 0;
41070     }else{
41071       /* This branch may be executed with Pager.journalMode==MEMORY if
41072       ** a hot-journal was just rolled back. In this case the journal
41073       ** file should be closed and deleted. If this connection writes to
41074       ** the database file, it will do so using an in-memory journal. 
41075       */
41076       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
41077       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
41078            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
41079            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
41080       );
41081       sqlite3OsClose(pPager->jfd);
41082       if( bDelete ){
41083         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41084       }
41085     }
41086   }
41087 
41088 #ifdef SQLITE_CHECK_PAGES
41089   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41090   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
41091     PgHdr *p = pager_lookup(pPager, 1);
41092     if( p ){
41093       p->pageHash = 0;
41094       sqlite3PagerUnref(p);
41095     }
41096   }
41097 #endif
41098 
41099   sqlite3BitvecDestroy(pPager->pInJournal);
41100   pPager->pInJournal = 0;
41101   pPager->nRec = 0;
41102   sqlite3PcacheCleanAll(pPager->pPCache);
41103   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41104 
41105   if( pagerUseWal(pPager) ){
41106     /* Drop the WAL write-lock, if any. Also, if the connection was in 
41107     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
41108     ** lock held on the database file.
41109     */
41110     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
41111     assert( rc2==SQLITE_OK );
41112   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
41113     /* This branch is taken when committing a transaction in rollback-journal
41114     ** mode if the database file on disk is larger than the database image.
41115     ** At this point the journal has been finalized and the transaction 
41116     ** successfully committed, but the EXCLUSIVE lock is still held on the
41117     ** file. So it is safe to truncate the database file to its minimum
41118     ** required size.  */
41119     assert( pPager->eLock==EXCLUSIVE_LOCK );
41120     rc = pager_truncate(pPager, pPager->dbSize);
41121   }
41122 
41123   if( !pPager->exclusiveMode 
41124    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
41125   ){
41126     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41127     pPager->changeCountDone = 0;
41128   }
41129   pPager->eState = PAGER_READER;
41130   pPager->setMaster = 0;
41131 
41132   return (rc==SQLITE_OK?rc2:rc);
41133 }
41134 
41135 /*
41136 ** Execute a rollback if a transaction is active and unlock the 
41137 ** database file. 
41138 **
41139 ** If the pager has already entered the ERROR state, do not attempt 
41140 ** the rollback at this time. Instead, pager_unlock() is called. The
41141 ** call to pager_unlock() will discard all in-memory pages, unlock
41142 ** the database file and move the pager back to OPEN state. If this 
41143 ** means that there is a hot-journal left in the file-system, the next 
41144 ** connection to obtain a shared lock on the pager (which may be this one) 
41145 ** will roll it back.
41146 **
41147 ** If the pager has not already entered the ERROR state, but an IO or
41148 ** malloc error occurs during a rollback, then this will itself cause 
41149 ** the pager to enter the ERROR state. Which will be cleared by the
41150 ** call to pager_unlock(), as described above.
41151 */
41152 static void pagerUnlockAndRollback(Pager *pPager){
41153   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41154     assert( assert_pager_state(pPager) );
41155     if( pPager->eState>=PAGER_WRITER_LOCKED ){
41156       sqlite3BeginBenignMalloc();
41157       sqlite3PagerRollback(pPager);
41158       sqlite3EndBenignMalloc();
41159     }else if( !pPager->exclusiveMode ){
41160       assert( pPager->eState==PAGER_READER );
41161       pager_end_transaction(pPager, 0, 0);
41162     }
41163   }
41164   pager_unlock(pPager);
41165 }
41166 
41167 /*
41168 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41169 ** of data. Compute and return a checksum based ont the contents of the 
41170 ** page of data and the current value of pPager->cksumInit.
41171 **
41172 ** This is not a real checksum. It is really just the sum of the 
41173 ** random initial value (pPager->cksumInit) and every 200th byte
41174 ** of the page data, starting with byte offset (pPager->pageSize%200).
41175 ** Each byte is interpreted as an 8-bit unsigned integer.
41176 **
41177 ** Changing the formula used to compute this checksum results in an
41178 ** incompatible journal file format.
41179 **
41180 ** If journal corruption occurs due to a power failure, the most likely 
41181 ** scenario is that one end or the other of the record will be changed. 
41182 ** It is much less likely that the two ends of the journal record will be
41183 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41184 ** though fast and simple, catches the mostly likely kind of corruption.
41185 */
41186 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41187   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41188   int i = pPager->pageSize-200;          /* Loop counter */
41189   while( i>0 ){
41190     cksum += aData[i];
41191     i -= 200;
41192   }
41193   return cksum;
41194 }
41195 
41196 /*
41197 ** Report the current page size and number of reserved bytes back
41198 ** to the codec.
41199 */
41200 #ifdef SQLITE_HAS_CODEC
41201 static void pagerReportSize(Pager *pPager){
41202   if( pPager->xCodecSizeChng ){
41203     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41204                            (int)pPager->nReserve);
41205   }
41206 }
41207 #else
41208 # define pagerReportSize(X)     /* No-op if we do not support a codec */
41209 #endif
41210 
41211 /*
41212 ** Read a single page from either the journal file (if isMainJrnl==1) or
41213 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41214 ** The page begins at offset *pOffset into the file. The *pOffset
41215 ** value is increased to the start of the next page in the journal.
41216 **
41217 ** The main rollback journal uses checksums - the statement journal does 
41218 ** not.
41219 **
41220 ** If the page number of the page record read from the (sub-)journal file
41221 ** is greater than the current value of Pager.dbSize, then playback is
41222 ** skipped and SQLITE_OK is returned.
41223 **
41224 ** If pDone is not NULL, then it is a record of pages that have already
41225 ** been played back.  If the page at *pOffset has already been played back
41226 ** (if the corresponding pDone bit is set) then skip the playback.
41227 ** Make sure the pDone bit corresponding to the *pOffset page is set
41228 ** prior to returning.
41229 **
41230 ** If the page record is successfully read from the (sub-)journal file
41231 ** and played back, then SQLITE_OK is returned. If an IO error occurs
41232 ** while reading the record from the (sub-)journal file or while writing
41233 ** to the database file, then the IO error code is returned. If data
41234 ** is successfully read from the (sub-)journal file but appears to be
41235 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
41236 ** two circumstances:
41237 ** 
41238 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41239 **   * If the record is being rolled back from the main journal file
41240 **     and the checksum field does not match the record content.
41241 **
41242 ** Neither of these two scenarios are possible during a savepoint rollback.
41243 **
41244 ** If this is a savepoint rollback, then memory may have to be dynamically
41245 ** allocated by this function. If this is the case and an allocation fails,
41246 ** SQLITE_NOMEM is returned.
41247 */
41248 static int pager_playback_one_page(
41249   Pager *pPager,                /* The pager being played back */
41250   i64 *pOffset,                 /* Offset of record to playback */
41251   Bitvec *pDone,                /* Bitvec of pages already played back */
41252   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
41253   int isSavepnt                 /* True for a savepoint rollback */
41254 ){
41255   int rc;
41256   PgHdr *pPg;                   /* An existing page in the cache */
41257   Pgno pgno;                    /* The page number of a page in journal */
41258   u32 cksum;                    /* Checksum used for sanity checking */
41259   char *aData;                  /* Temporary storage for the page */
41260   sqlite3_file *jfd;            /* The file descriptor for the journal file */
41261   int isSynced;                 /* True if journal page is synced */
41262 
41263   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
41264   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
41265   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
41266   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
41267 
41268   aData = pPager->pTmpSpace;
41269   assert( aData );         /* Temp storage must have already been allocated */
41270   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41271 
41272   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
41273   ** or savepoint rollback done at the request of the caller) or this is
41274   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41275   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41276   ** only reads from the main journal, not the sub-journal.
41277   */
41278   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41279        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41280   );
41281   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41282 
41283   /* Read the page number and page data from the journal or sub-journal
41284   ** file. Return an error code to the caller if an IO error occurs.
41285   */
41286   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41287   rc = read32bits(jfd, *pOffset, &pgno);
41288   if( rc!=SQLITE_OK ) return rc;
41289   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41290   if( rc!=SQLITE_OK ) return rc;
41291   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41292 
41293   /* Sanity checking on the page.  This is more important that I originally
41294   ** thought.  If a power failure occurs while the journal is being written,
41295   ** it could cause invalid data to be written into the journal.  We need to
41296   ** detect this invalid data (with high probability) and ignore it.
41297   */
41298   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41299     assert( !isSavepnt );
41300     return SQLITE_DONE;
41301   }
41302   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
41303     return SQLITE_OK;
41304   }
41305   if( isMainJrnl ){
41306     rc = read32bits(jfd, (*pOffset)-4, &cksum);
41307     if( rc ) return rc;
41308     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41309       return SQLITE_DONE;
41310     }
41311   }
41312 
41313   /* If this page has already been played by before during the current
41314   ** rollback, then don't bother to play it back again.
41315   */
41316   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
41317     return rc;
41318   }
41319 
41320   /* When playing back page 1, restore the nReserve setting
41321   */
41322   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41323     pPager->nReserve = ((u8*)aData)[20];
41324     pagerReportSize(pPager);
41325   }
41326 
41327   /* If the pager is in CACHEMOD state, then there must be a copy of this
41328   ** page in the pager cache. In this case just update the pager cache,
41329   ** not the database file. The page is left marked dirty in this case.
41330   **
41331   ** An exception to the above rule: If the database is in no-sync mode
41332   ** and a page is moved during an incremental vacuum then the page may
41333   ** not be in the pager cache. Later: if a malloc() or IO error occurs
41334   ** during a Movepage() call, then the page may not be in the cache
41335   ** either. So the condition described in the above paragraph is not
41336   ** assert()able.
41337   **
41338   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41339   ** pager cache if it exists and the main file. The page is then marked 
41340   ** not dirty. Since this code is only executed in PAGER_OPEN state for
41341   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41342   ** if the pager is in OPEN state.
41343   **
41344   ** Ticket #1171:  The statement journal might contain page content that is
41345   ** different from the page content at the start of the transaction.
41346   ** This occurs when a page is changed prior to the start of a statement
41347   ** then changed again within the statement.  When rolling back such a
41348   ** statement we must not write to the original database unless we know
41349   ** for certain that original page contents are synced into the main rollback
41350   ** journal.  Otherwise, a power loss might leave modified data in the
41351   ** database file without an entry in the rollback journal that can
41352   ** restore the database to its original form.  Two conditions must be
41353   ** met before writing to the database files. (1) the database must be
41354   ** locked.  (2) we know that the original page content is fully synced
41355   ** in the main journal either because the page is not in cache or else
41356   ** the page is marked as needSync==0.
41357   **
41358   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
41359   ** is possible to fail a statement on a database that does not yet exist.
41360   ** Do not attempt to write if database file has never been opened.
41361   */
41362   if( pagerUseWal(pPager) ){
41363     pPg = 0;
41364   }else{
41365     pPg = pager_lookup(pPager, pgno);
41366   }
41367   assert( pPg || !MEMDB );
41368   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41369   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41370            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41371            (isMainJrnl?"main-journal":"sub-journal")
41372   ));
41373   if( isMainJrnl ){
41374     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41375   }else{
41376     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41377   }
41378   if( isOpen(pPager->fd)
41379    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41380    && isSynced
41381   ){
41382     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41383     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41384     assert( !pagerUseWal(pPager) );
41385     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
41386     if( pgno>pPager->dbFileSize ){
41387       pPager->dbFileSize = pgno;
41388     }
41389     if( pPager->pBackup ){
41390       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
41391       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41392       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
41393     }
41394   }else if( !isMainJrnl && pPg==0 ){
41395     /* If this is a rollback of a savepoint and data was not written to
41396     ** the database and the page is not in-memory, there is a potential
41397     ** problem. When the page is next fetched by the b-tree layer, it 
41398     ** will be read from the database file, which may or may not be 
41399     ** current. 
41400     **
41401     ** There are a couple of different ways this can happen. All are quite
41402     ** obscure. When running in synchronous mode, this can only happen 
41403     ** if the page is on the free-list at the start of the transaction, then
41404     ** populated, then moved using sqlite3PagerMovepage().
41405     **
41406     ** The solution is to add an in-memory page to the cache containing
41407     ** the data just read from the sub-journal. Mark the page as dirty 
41408     ** and if the pager requires a journal-sync, then mark the page as 
41409     ** requiring a journal-sync before it is written.
41410     */
41411     assert( isSavepnt );
41412     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
41413     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
41414     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
41415     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
41416     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
41417     if( rc!=SQLITE_OK ) return rc;
41418     pPg->flags &= ~PGHDR_NEED_READ;
41419     sqlite3PcacheMakeDirty(pPg);
41420   }
41421   if( pPg ){
41422     /* No page should ever be explicitly rolled back that is in use, except
41423     ** for page 1 which is held in use in order to keep the lock on the
41424     ** database active. However such a page may be rolled back as a result
41425     ** of an internal error resulting in an automatic call to
41426     ** sqlite3PagerRollback().
41427     */
41428     void *pData;
41429     pData = pPg->pData;
41430     memcpy(pData, (u8*)aData, pPager->pageSize);
41431     pPager->xReiniter(pPg);
41432     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41433       /* If the contents of this page were just restored from the main 
41434       ** journal file, then its content must be as they were when the 
41435       ** transaction was first opened. In this case we can mark the page
41436       ** as clean, since there will be no need to write it out to the
41437       ** database.
41438       **
41439       ** There is one exception to this rule. If the page is being rolled
41440       ** back as part of a savepoint (or statement) rollback from an 
41441       ** unsynced portion of the main journal file, then it is not safe
41442       ** to mark the page as clean. This is because marking the page as
41443       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41444       ** already in the journal file (recorded in Pager.pInJournal) and
41445       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41446       ** again within this transaction, it will be marked as dirty but
41447       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41448       ** be written out into the database file before its journal file
41449       ** segment is synced. If a crash occurs during or following this,
41450       ** database corruption may ensue.
41451       */
41452       assert( !pagerUseWal(pPager) );
41453       sqlite3PcacheMakeClean(pPg);
41454     }
41455     pager_set_pagehash(pPg);
41456 
41457     /* If this was page 1, then restore the value of Pager.dbFileVers.
41458     ** Do this before any decoding. */
41459     if( pgno==1 ){
41460       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41461     }
41462 
41463     /* Decode the page just read from disk */
41464     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
41465     sqlite3PcacheRelease(pPg);
41466   }
41467   return rc;
41468 }
41469 
41470 /*
41471 ** Parameter zMaster is the name of a master journal file. A single journal
41472 ** file that referred to the master journal file has just been rolled back.
41473 ** This routine checks if it is possible to delete the master journal file,
41474 ** and does so if it is.
41475 **
41476 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
41477 ** available for use within this function.
41478 **
41479 ** When a master journal file is created, it is populated with the names 
41480 ** of all of its child journals, one after another, formatted as utf-8 
41481 ** encoded text. The end of each child journal file is marked with a 
41482 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41483 ** file for a transaction involving two databases might be:
41484 **
41485 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41486 **
41487 ** A master journal file may only be deleted once all of its child 
41488 ** journals have been rolled back.
41489 **
41490 ** This function reads the contents of the master-journal file into 
41491 ** memory and loops through each of the child journal names. For
41492 ** each child journal, it checks if:
41493 **
41494 **   * if the child journal exists, and if so
41495 **   * if the child journal contains a reference to master journal 
41496 **     file zMaster
41497 **
41498 ** If a child journal can be found that matches both of the criteria
41499 ** above, this function returns without doing anything. Otherwise, if
41500 ** no such child journal can be found, file zMaster is deleted from
41501 ** the file-system using sqlite3OsDelete().
41502 **
41503 ** If an IO error within this function, an error code is returned. This
41504 ** function allocates memory by calling sqlite3Malloc(). If an allocation
41505 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
41506 ** occur, SQLITE_OK is returned.
41507 **
41508 ** TODO: This function allocates a single block of memory to load
41509 ** the entire contents of the master journal file. This could be
41510 ** a couple of kilobytes or so - potentially larger than the page 
41511 ** size.
41512 */
41513 static int pager_delmaster(Pager *pPager, const char *zMaster){
41514   sqlite3_vfs *pVfs = pPager->pVfs;
41515   int rc;                   /* Return code */
41516   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
41517   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
41518   char *zMasterJournal = 0; /* Contents of master journal file */
41519   i64 nMasterJournal;       /* Size of master journal file */
41520   char *zJournal;           /* Pointer to one journal within MJ file */
41521   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
41522   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
41523 
41524   /* Allocate space for both the pJournal and pMaster file descriptors.
41525   ** If successful, open the master journal file for reading.
41526   */
41527   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
41528   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
41529   if( !pMaster ){
41530     rc = SQLITE_NOMEM;
41531   }else{
41532     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
41533     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
41534   }
41535   if( rc!=SQLITE_OK ) goto delmaster_out;
41536 
41537   /* Load the entire master journal file into space obtained from
41538   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
41539   ** sufficient space (in zMasterPtr) to hold the names of master
41540   ** journal files extracted from regular rollback-journals.
41541   */
41542   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
41543   if( rc!=SQLITE_OK ) goto delmaster_out;
41544   nMasterPtr = pVfs->mxPathname+1;
41545   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
41546   if( !zMasterJournal ){
41547     rc = SQLITE_NOMEM;
41548     goto delmaster_out;
41549   }
41550   zMasterPtr = &zMasterJournal[nMasterJournal+1];
41551   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
41552   if( rc!=SQLITE_OK ) goto delmaster_out;
41553   zMasterJournal[nMasterJournal] = 0;
41554 
41555   zJournal = zMasterJournal;
41556   while( (zJournal-zMasterJournal)<nMasterJournal ){
41557     int exists;
41558     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
41559     if( rc!=SQLITE_OK ){
41560       goto delmaster_out;
41561     }
41562     if( exists ){
41563       /* One of the journals pointed to by the master journal exists.
41564       ** Open it and check if it points at the master journal. If
41565       ** so, return without deleting the master journal file.
41566       */
41567       int c;
41568       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
41569       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
41570       if( rc!=SQLITE_OK ){
41571         goto delmaster_out;
41572       }
41573 
41574       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
41575       sqlite3OsClose(pJournal);
41576       if( rc!=SQLITE_OK ){
41577         goto delmaster_out;
41578       }
41579 
41580       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
41581       if( c ){
41582         /* We have a match. Do not delete the master journal file. */
41583         goto delmaster_out;
41584       }
41585     }
41586     zJournal += (sqlite3Strlen30(zJournal)+1);
41587   }
41588  
41589   sqlite3OsClose(pMaster);
41590   rc = sqlite3OsDelete(pVfs, zMaster, 0);
41591 
41592 delmaster_out:
41593   sqlite3_free(zMasterJournal);
41594   if( pMaster ){
41595     sqlite3OsClose(pMaster);
41596     assert( !isOpen(pJournal) );
41597     sqlite3_free(pMaster);
41598   }
41599   return rc;
41600 }
41601 
41602 
41603 /*
41604 ** This function is used to change the actual size of the database 
41605 ** file in the file-system. This only happens when committing a transaction,
41606 ** or rolling back a transaction (including rolling back a hot-journal).
41607 **
41608 ** If the main database file is not open, or the pager is not in either
41609 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
41610 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
41611 ** If the file on disk is currently larger than nPage pages, then use the VFS
41612 ** xTruncate() method to truncate it.
41613 **
41614 ** Or, it might might be the case that the file on disk is smaller than 
41615 ** nPage pages. Some operating system implementations can get confused if 
41616 ** you try to truncate a file to some size that is larger than it 
41617 ** currently is, so detect this case and write a single zero byte to 
41618 ** the end of the new file instead.
41619 **
41620 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
41621 ** the database file, return the error code to the caller.
41622 */
41623 static int pager_truncate(Pager *pPager, Pgno nPage){
41624   int rc = SQLITE_OK;
41625   assert( pPager->eState!=PAGER_ERROR );
41626   assert( pPager->eState!=PAGER_READER );
41627   
41628   if( isOpen(pPager->fd) 
41629    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
41630   ){
41631     i64 currentSize, newSize;
41632     int szPage = pPager->pageSize;
41633     assert( pPager->eLock==EXCLUSIVE_LOCK );
41634     /* TODO: Is it safe to use Pager.dbFileSize here? */
41635     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
41636     newSize = szPage*(i64)nPage;
41637     if( rc==SQLITE_OK && currentSize!=newSize ){
41638       if( currentSize>newSize ){
41639         rc = sqlite3OsTruncate(pPager->fd, newSize);
41640       }else if( (currentSize+szPage)<=newSize ){
41641         char *pTmp = pPager->pTmpSpace;
41642         memset(pTmp, 0, szPage);
41643         testcase( (newSize-szPage) == currentSize );
41644         testcase( (newSize-szPage) >  currentSize );
41645         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
41646       }
41647       if( rc==SQLITE_OK ){
41648         pPager->dbFileSize = nPage;
41649       }
41650     }
41651   }
41652   return rc;
41653 }
41654 
41655 /*
41656 ** Return a sanitized version of the sector-size of OS file pFile. The
41657 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
41658 */
41659 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
41660   int iRet = sqlite3OsSectorSize(pFile);
41661   if( iRet<32 ){
41662     iRet = 512;
41663   }else if( iRet>MAX_SECTOR_SIZE ){
41664     assert( MAX_SECTOR_SIZE>=512 );
41665     iRet = MAX_SECTOR_SIZE;
41666   }
41667   return iRet;
41668 }
41669 
41670 /*
41671 ** Set the value of the Pager.sectorSize variable for the given
41672 ** pager based on the value returned by the xSectorSize method
41673 ** of the open database file. The sector size will be used used 
41674 ** to determine the size and alignment of journal header and 
41675 ** master journal pointers within created journal files.
41676 **
41677 ** For temporary files the effective sector size is always 512 bytes.
41678 **
41679 ** Otherwise, for non-temporary files, the effective sector size is
41680 ** the value returned by the xSectorSize() method rounded up to 32 if
41681 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
41682 ** is greater than MAX_SECTOR_SIZE.
41683 **
41684 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
41685 ** the effective sector size to its minimum value (512).  The purpose of
41686 ** pPager->sectorSize is to define the "blast radius" of bytes that
41687 ** might change if a crash occurs while writing to a single byte in
41688 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
41689 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
41690 ** size.  For backwards compatibility of the rollback journal file format,
41691 ** we cannot reduce the effective sector size below 512.
41692 */
41693 static void setSectorSize(Pager *pPager){
41694   assert( isOpen(pPager->fd) || pPager->tempFile );
41695 
41696   if( pPager->tempFile
41697    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
41698               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
41699   ){
41700     /* Sector size doesn't matter for temporary files. Also, the file
41701     ** may not have been opened yet, in which case the OsSectorSize()
41702     ** call will segfault. */
41703     pPager->sectorSize = 512;
41704   }else{
41705     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
41706   }
41707 }
41708 
41709 /*
41710 ** Playback the journal and thus restore the database file to
41711 ** the state it was in before we started making changes.  
41712 **
41713 ** The journal file format is as follows: 
41714 **
41715 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
41716 **  (2)  4 byte big-endian integer which is the number of valid page records
41717 **       in the journal.  If this value is 0xffffffff, then compute the
41718 **       number of page records from the journal size.
41719 **  (3)  4 byte big-endian integer which is the initial value for the 
41720 **       sanity checksum.
41721 **  (4)  4 byte integer which is the number of pages to truncate the
41722 **       database to during a rollback.
41723 **  (5)  4 byte big-endian integer which is the sector size.  The header
41724 **       is this many bytes in size.
41725 **  (6)  4 byte big-endian integer which is the page size.
41726 **  (7)  zero padding out to the next sector size.
41727 **  (8)  Zero or more pages instances, each as follows:
41728 **        +  4 byte page number.
41729 **        +  pPager->pageSize bytes of data.
41730 **        +  4 byte checksum
41731 **
41732 ** When we speak of the journal header, we mean the first 7 items above.
41733 ** Each entry in the journal is an instance of the 8th item.
41734 **
41735 ** Call the value from the second bullet "nRec".  nRec is the number of
41736 ** valid page entries in the journal.  In most cases, you can compute the
41737 ** value of nRec from the size of the journal file.  But if a power
41738 ** failure occurred while the journal was being written, it could be the
41739 ** case that the size of the journal file had already been increased but
41740 ** the extra entries had not yet made it safely to disk.  In such a case,
41741 ** the value of nRec computed from the file size would be too large.  For
41742 ** that reason, we always use the nRec value in the header.
41743 **
41744 ** If the nRec value is 0xffffffff it means that nRec should be computed
41745 ** from the file size.  This value is used when the user selects the
41746 ** no-sync option for the journal.  A power failure could lead to corruption
41747 ** in this case.  But for things like temporary table (which will be
41748 ** deleted when the power is restored) we don't care.  
41749 **
41750 ** If the file opened as the journal file is not a well-formed
41751 ** journal file then all pages up to the first corrupted page are rolled
41752 ** back (or no pages if the journal header is corrupted). The journal file
41753 ** is then deleted and SQLITE_OK returned, just as if no corruption had
41754 ** been encountered.
41755 **
41756 ** If an I/O or malloc() error occurs, the journal-file is not deleted
41757 ** and an error code is returned.
41758 **
41759 ** The isHot parameter indicates that we are trying to rollback a journal
41760 ** that might be a hot journal.  Or, it could be that the journal is 
41761 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41762 ** If the journal really is hot, reset the pager cache prior rolling
41763 ** back any content.  If the journal is merely persistent, no reset is
41764 ** needed.
41765 */
41766 static int pager_playback(Pager *pPager, int isHot){
41767   sqlite3_vfs *pVfs = pPager->pVfs;
41768   i64 szJ;                 /* Size of the journal file in bytes */
41769   u32 nRec;                /* Number of Records in the journal */
41770   u32 u;                   /* Unsigned loop counter */
41771   Pgno mxPg = 0;           /* Size of the original file in pages */
41772   int rc;                  /* Result code of a subroutine */
41773   int res = 1;             /* Value returned by sqlite3OsAccess() */
41774   char *zMaster = 0;       /* Name of master journal file if any */
41775   int needPagerReset;      /* True to reset page prior to first page rollback */
41776   int nPlayback = 0;       /* Total number of pages restored from journal */
41777 
41778   /* Figure out how many records are in the journal.  Abort early if
41779   ** the journal is empty.
41780   */
41781   assert( isOpen(pPager->jfd) );
41782   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41783   if( rc!=SQLITE_OK ){
41784     goto end_playback;
41785   }
41786 
41787   /* Read the master journal name from the journal, if it is present.
41788   ** If a master journal file name is specified, but the file is not
41789   ** present on disk, then the journal is not hot and does not need to be
41790   ** played back.
41791   **
41792   ** TODO: Technically the following is an error because it assumes that
41793   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41794   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41795   **  mxPathname is 512, which is the same as the minimum allowable value
41796   ** for pageSize.
41797   */
41798   zMaster = pPager->pTmpSpace;
41799   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41800   if( rc==SQLITE_OK && zMaster[0] ){
41801     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41802   }
41803   zMaster = 0;
41804   if( rc!=SQLITE_OK || !res ){
41805     goto end_playback;
41806   }
41807   pPager->journalOff = 0;
41808   needPagerReset = isHot;
41809 
41810   /* This loop terminates either when a readJournalHdr() or 
41811   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
41812   ** occurs. 
41813   */
41814   while( 1 ){
41815     /* Read the next journal header from the journal file.  If there are
41816     ** not enough bytes left in the journal file for a complete header, or
41817     ** it is corrupted, then a process must have failed while writing it.
41818     ** This indicates nothing more needs to be rolled back.
41819     */
41820     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41821     if( rc!=SQLITE_OK ){ 
41822       if( rc==SQLITE_DONE ){
41823         rc = SQLITE_OK;
41824       }
41825       goto end_playback;
41826     }
41827 
41828     /* If nRec is 0xffffffff, then this journal was created by a process
41829     ** working in no-sync mode. This means that the rest of the journal
41830     ** file consists of pages, there are no more journal headers. Compute
41831     ** the value of nRec based on this assumption.
41832     */
41833     if( nRec==0xffffffff ){
41834       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41835       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41836     }
41837 
41838     /* If nRec is 0 and this rollback is of a transaction created by this
41839     ** process and if this is the final header in the journal, then it means
41840     ** that this part of the journal was being filled but has not yet been
41841     ** synced to disk.  Compute the number of pages based on the remaining
41842     ** size of the file.
41843     **
41844     ** The third term of the test was added to fix ticket #2565.
41845     ** When rolling back a hot journal, nRec==0 always means that the next
41846     ** chunk of the journal contains zero pages to be rolled back.  But
41847     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41848     ** the journal, it means that the journal might contain additional
41849     ** pages that need to be rolled back and that the number of pages 
41850     ** should be computed based on the journal file size.
41851     */
41852     if( nRec==0 && !isHot &&
41853         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41854       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41855     }
41856 
41857     /* If this is the first header read from the journal, truncate the
41858     ** database file back to its original size.
41859     */
41860     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41861       rc = pager_truncate(pPager, mxPg);
41862       if( rc!=SQLITE_OK ){
41863         goto end_playback;
41864       }
41865       pPager->dbSize = mxPg;
41866     }
41867 
41868     /* Copy original pages out of the journal and back into the 
41869     ** database file and/or page cache.
41870     */
41871     for(u=0; u<nRec; u++){
41872       if( needPagerReset ){
41873         pager_reset(pPager);
41874         needPagerReset = 0;
41875       }
41876       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41877       if( rc==SQLITE_OK ){
41878         nPlayback++;
41879       }else{
41880         if( rc==SQLITE_DONE ){
41881           pPager->journalOff = szJ;
41882           break;
41883         }else if( rc==SQLITE_IOERR_SHORT_READ ){
41884           /* If the journal has been truncated, simply stop reading and
41885           ** processing the journal. This might happen if the journal was
41886           ** not completely written and synced prior to a crash.  In that
41887           ** case, the database should have never been written in the
41888           ** first place so it is OK to simply abandon the rollback. */
41889           rc = SQLITE_OK;
41890           goto end_playback;
41891         }else{
41892           /* If we are unable to rollback, quit and return the error
41893           ** code.  This will cause the pager to enter the error state
41894           ** so that no further harm will be done.  Perhaps the next
41895           ** process to come along will be able to rollback the database.
41896           */
41897           goto end_playback;
41898         }
41899       }
41900     }
41901   }
41902   /*NOTREACHED*/
41903   assert( 0 );
41904 
41905 end_playback:
41906   /* Following a rollback, the database file should be back in its original
41907   ** state prior to the start of the transaction, so invoke the
41908   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41909   ** assertion that the transaction counter was modified.
41910   */
41911 #ifdef SQLITE_DEBUG
41912   if( pPager->fd->pMethods ){
41913     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41914   }
41915 #endif
41916 
41917   /* If this playback is happening automatically as a result of an IO or 
41918   ** malloc error that occurred after the change-counter was updated but 
41919   ** before the transaction was committed, then the change-counter 
41920   ** modification may just have been reverted. If this happens in exclusive 
41921   ** mode, then subsequent transactions performed by the connection will not
41922   ** update the change-counter at all. This may lead to cache inconsistency
41923   ** problems for other processes at some point in the future. So, just
41924   ** in case this has happened, clear the changeCountDone flag now.
41925   */
41926   pPager->changeCountDone = pPager->tempFile;
41927 
41928   if( rc==SQLITE_OK ){
41929     zMaster = pPager->pTmpSpace;
41930     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41931     testcase( rc!=SQLITE_OK );
41932   }
41933   if( rc==SQLITE_OK
41934    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41935   ){
41936     rc = sqlite3PagerSync(pPager);
41937   }
41938   if( rc==SQLITE_OK ){
41939     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
41940     testcase( rc!=SQLITE_OK );
41941   }
41942   if( rc==SQLITE_OK && zMaster[0] && res ){
41943     /* If there was a master journal and this routine will return success,
41944     ** see if it is possible to delete the master journal.
41945     */
41946     rc = pager_delmaster(pPager, zMaster);
41947     testcase( rc!=SQLITE_OK );
41948   }
41949   if( isHot && nPlayback ){
41950     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
41951                 nPlayback, pPager->zJournal);
41952   }
41953 
41954   /* The Pager.sectorSize variable may have been updated while rolling
41955   ** back a journal created by a process with a different sector size
41956   ** value. Reset it to the correct value for this process.
41957   */
41958   setSectorSize(pPager);
41959   return rc;
41960 }
41961 
41962 
41963 /*
41964 ** Read the content for page pPg out of the database file and into 
41965 ** pPg->pData. A shared lock or greater must be held on the database
41966 ** file before this function is called.
41967 **
41968 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41969 ** the value read from the database file.
41970 **
41971 ** If an IO error occurs, then the IO error is returned to the caller.
41972 ** Otherwise, SQLITE_OK is returned.
41973 */
41974 static int readDbPage(PgHdr *pPg, u32 iFrame){
41975   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41976   Pgno pgno = pPg->pgno;       /* Page number to read */
41977   int rc = SQLITE_OK;          /* Return code */
41978   int pgsz = pPager->pageSize; /* Number of bytes to read */
41979 
41980   assert( pPager->eState>=PAGER_READER && !MEMDB );
41981   assert( isOpen(pPager->fd) );
41982 
41983 #ifndef SQLITE_OMIT_WAL
41984   if( iFrame ){
41985     /* Try to pull the page from the write-ahead log. */
41986     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
41987   }else
41988 #endif
41989   {
41990     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41991     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41992     if( rc==SQLITE_IOERR_SHORT_READ ){
41993       rc = SQLITE_OK;
41994     }
41995   }
41996 
41997   if( pgno==1 ){
41998     if( rc ){
41999       /* If the read is unsuccessful, set the dbFileVers[] to something
42000       ** that will never be a valid file version.  dbFileVers[] is a copy
42001       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42002       ** zero or the size of the database in page. Bytes 32..35 and 35..39
42003       ** should be page numbers which are never 0xffffffff.  So filling
42004       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42005       **
42006       ** For an encrypted database, the situation is more complex:  bytes
42007       ** 24..39 of the database are white noise.  But the probability of
42008       ** white noising equaling 16 bytes of 0xff is vanishingly small so
42009       ** we should still be ok.
42010       */
42011       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42012     }else{
42013       u8 *dbFileVers = &((u8*)pPg->pData)[24];
42014       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42015     }
42016   }
42017   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
42018 
42019   PAGER_INCR(sqlite3_pager_readdb_count);
42020   PAGER_INCR(pPager->nRead);
42021   IOTRACE(("PGIN %p %d\n", pPager, pgno));
42022   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42023                PAGERID(pPager), pgno, pager_pagehash(pPg)));
42024 
42025   return rc;
42026 }
42027 
42028 /*
42029 ** Update the value of the change-counter at offsets 24 and 92 in
42030 ** the header and the sqlite version number at offset 96.
42031 **
42032 ** This is an unconditional update.  See also the pager_incr_changecounter()
42033 ** routine which only updates the change-counter if the update is actually
42034 ** needed, as determined by the pPager->changeCountDone state variable.
42035 */
42036 static void pager_write_changecounter(PgHdr *pPg){
42037   u32 change_counter;
42038 
42039   /* Increment the value just read and write it back to byte 24. */
42040   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42041   put32bits(((char*)pPg->pData)+24, change_counter);
42042 
42043   /* Also store the SQLite version number in bytes 96..99 and in
42044   ** bytes 92..95 store the change counter for which the version number
42045   ** is valid. */
42046   put32bits(((char*)pPg->pData)+92, change_counter);
42047   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
42048 }
42049 
42050 #ifndef SQLITE_OMIT_WAL
42051 /*
42052 ** This function is invoked once for each page that has already been 
42053 ** written into the log file when a WAL transaction is rolled back.
42054 ** Parameter iPg is the page number of said page. The pCtx argument 
42055 ** is actually a pointer to the Pager structure.
42056 **
42057 ** If page iPg is present in the cache, and has no outstanding references,
42058 ** it is discarded. Otherwise, if there are one or more outstanding
42059 ** references, the page content is reloaded from the database. If the
42060 ** attempt to reload content from the database is required and fails, 
42061 ** return an SQLite error code. Otherwise, SQLITE_OK.
42062 */
42063 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42064   int rc = SQLITE_OK;
42065   Pager *pPager = (Pager *)pCtx;
42066   PgHdr *pPg;
42067 
42068   assert( pagerUseWal(pPager) );
42069   pPg = sqlite3PagerLookup(pPager, iPg);
42070   if( pPg ){
42071     if( sqlite3PcachePageRefcount(pPg)==1 ){
42072       sqlite3PcacheDrop(pPg);
42073     }else{
42074       u32 iFrame = 0;
42075       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
42076       if( rc==SQLITE_OK ){
42077         rc = readDbPage(pPg, iFrame);
42078       }
42079       if( rc==SQLITE_OK ){
42080         pPager->xReiniter(pPg);
42081       }
42082       sqlite3PagerUnref(pPg);
42083     }
42084   }
42085 
42086   /* Normally, if a transaction is rolled back, any backup processes are
42087   ** updated as data is copied out of the rollback journal and into the
42088   ** database. This is not generally possible with a WAL database, as
42089   ** rollback involves simply truncating the log file. Therefore, if one
42090   ** or more frames have already been written to the log (and therefore 
42091   ** also copied into the backup databases) as part of this transaction,
42092   ** the backups must be restarted.
42093   */
42094   sqlite3BackupRestart(pPager->pBackup);
42095 
42096   return rc;
42097 }
42098 
42099 /*
42100 ** This function is called to rollback a transaction on a WAL database.
42101 */
42102 static int pagerRollbackWal(Pager *pPager){
42103   int rc;                         /* Return Code */
42104   PgHdr *pList;                   /* List of dirty pages to revert */
42105 
42106   /* For all pages in the cache that are currently dirty or have already
42107   ** been written (but not committed) to the log file, do one of the 
42108   ** following:
42109   **
42110   **   + Discard the cached page (if refcount==0), or
42111   **   + Reload page content from the database (if refcount>0).
42112   */
42113   pPager->dbSize = pPager->dbOrigSize;
42114   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42115   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42116   while( pList && rc==SQLITE_OK ){
42117     PgHdr *pNext = pList->pDirty;
42118     rc = pagerUndoCallback((void *)pPager, pList->pgno);
42119     pList = pNext;
42120   }
42121 
42122   return rc;
42123 }
42124 
42125 /*
42126 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
42127 ** the contents of the list of pages headed by pList (connected by pDirty),
42128 ** this function notifies any active backup processes that the pages have
42129 ** changed. 
42130 **
42131 ** The list of pages passed into this routine is always sorted by page number.
42132 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42133 */ 
42134 static int pagerWalFrames(
42135   Pager *pPager,                  /* Pager object */
42136   PgHdr *pList,                   /* List of frames to log */
42137   Pgno nTruncate,                 /* Database size after this commit */
42138   int isCommit                    /* True if this is a commit */
42139 ){
42140   int rc;                         /* Return code */
42141   int nList;                      /* Number of pages in pList */
42142 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
42143   PgHdr *p;                       /* For looping over pages */
42144 #endif
42145 
42146   assert( pPager->pWal );
42147   assert( pList );
42148 #ifdef SQLITE_DEBUG
42149   /* Verify that the page list is in accending order */
42150   for(p=pList; p && p->pDirty; p=p->pDirty){
42151     assert( p->pgno < p->pDirty->pgno );
42152   }
42153 #endif
42154 
42155   assert( pList->pDirty==0 || isCommit );
42156   if( isCommit ){
42157     /* If a WAL transaction is being committed, there is no point in writing
42158     ** any pages with page numbers greater than nTruncate into the WAL file.
42159     ** They will never be read by any client. So remove them from the pDirty
42160     ** list here. */
42161     PgHdr *p;
42162     PgHdr **ppNext = &pList;
42163     nList = 0;
42164     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
42165       if( p->pgno<=nTruncate ){
42166         ppNext = &p->pDirty;
42167         nList++;
42168       }
42169     }
42170     assert( pList );
42171   }else{
42172     nList = 1;
42173   }
42174   pPager->aStat[PAGER_STAT_WRITE] += nList;
42175 
42176   if( pList->pgno==1 ) pager_write_changecounter(pList);
42177   rc = sqlite3WalFrames(pPager->pWal, 
42178       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
42179   );
42180   if( rc==SQLITE_OK && pPager->pBackup ){
42181     PgHdr *p;
42182     for(p=pList; p; p=p->pDirty){
42183       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42184     }
42185   }
42186 
42187 #ifdef SQLITE_CHECK_PAGES
42188   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42189   for(p=pList; p; p=p->pDirty){
42190     pager_set_pagehash(p);
42191   }
42192 #endif
42193 
42194   return rc;
42195 }
42196 
42197 /*
42198 ** Begin a read transaction on the WAL.
42199 **
42200 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42201 ** makes a snapshot of the database at the current point in time and preserves
42202 ** that snapshot for use by the reader in spite of concurrently changes by
42203 ** other writers or checkpointers.
42204 */
42205 static int pagerBeginReadTransaction(Pager *pPager){
42206   int rc;                         /* Return code */
42207   int changed = 0;                /* True if cache must be reset */
42208 
42209   assert( pagerUseWal(pPager) );
42210   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42211 
42212   /* sqlite3WalEndReadTransaction() was not called for the previous
42213   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42214   ** are in locking_mode=NORMAL and EndRead() was previously called,
42215   ** the duplicate call is harmless.
42216   */
42217   sqlite3WalEndReadTransaction(pPager->pWal);
42218 
42219   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
42220   if( rc!=SQLITE_OK || changed ){
42221     pager_reset(pPager);
42222     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42223   }
42224 
42225   return rc;
42226 }
42227 #endif
42228 
42229 /*
42230 ** This function is called as part of the transition from PAGER_OPEN
42231 ** to PAGER_READER state to determine the size of the database file
42232 ** in pages (assuming the page size currently stored in Pager.pageSize).
42233 **
42234 ** If no error occurs, SQLITE_OK is returned and the size of the database
42235 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42236 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42237 */
42238 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42239   Pgno nPage;                     /* Value to return via *pnPage */
42240 
42241   /* Query the WAL sub-system for the database size. The WalDbsize()
42242   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42243   ** if the database size is not available. The database size is not
42244   ** available from the WAL sub-system if the log file is empty or
42245   ** contains no valid committed transactions.
42246   */
42247   assert( pPager->eState==PAGER_OPEN );
42248   assert( pPager->eLock>=SHARED_LOCK );
42249   nPage = sqlite3WalDbsize(pPager->pWal);
42250 
42251   /* If the database size was not available from the WAL sub-system,
42252   ** determine it based on the size of the database file. If the size
42253   ** of the database file is not an integer multiple of the page-size,
42254   ** round down to the nearest page. Except, any file larger than 0
42255   ** bytes in size is considered to contain at least one page.
42256   */
42257   if( nPage==0 ){
42258     i64 n = 0;                    /* Size of db file in bytes */
42259     assert( isOpen(pPager->fd) || pPager->tempFile );
42260     if( isOpen(pPager->fd) ){
42261       int rc = sqlite3OsFileSize(pPager->fd, &n);
42262       if( rc!=SQLITE_OK ){
42263         return rc;
42264       }
42265     }
42266     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
42267   }
42268 
42269   /* If the current number of pages in the file is greater than the
42270   ** configured maximum pager number, increase the allowed limit so
42271   ** that the file can be read.
42272   */
42273   if( nPage>pPager->mxPgno ){
42274     pPager->mxPgno = (Pgno)nPage;
42275   }
42276 
42277   *pnPage = nPage;
42278   return SQLITE_OK;
42279 }
42280 
42281 #ifndef SQLITE_OMIT_WAL
42282 /*
42283 ** Check if the *-wal file that corresponds to the database opened by pPager
42284 ** exists if the database is not empy, or verify that the *-wal file does
42285 ** not exist (by deleting it) if the database file is empty.
42286 **
42287 ** If the database is not empty and the *-wal file exists, open the pager
42288 ** in WAL mode.  If the database is empty or if no *-wal file exists and
42289 ** if no error occurs, make sure Pager.journalMode is not set to
42290 ** PAGER_JOURNALMODE_WAL.
42291 **
42292 ** Return SQLITE_OK or an error code.
42293 **
42294 ** The caller must hold a SHARED lock on the database file to call this
42295 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
42296 ** a WAL on a none-empty database, this ensures there is no race condition 
42297 ** between the xAccess() below and an xDelete() being executed by some 
42298 ** other connection.
42299 */
42300 static int pagerOpenWalIfPresent(Pager *pPager){
42301   int rc = SQLITE_OK;
42302   assert( pPager->eState==PAGER_OPEN );
42303   assert( pPager->eLock>=SHARED_LOCK );
42304 
42305   if( !pPager->tempFile ){
42306     int isWal;                    /* True if WAL file exists */
42307     Pgno nPage;                   /* Size of the database file */
42308 
42309     rc = pagerPagecount(pPager, &nPage);
42310     if( rc ) return rc;
42311     if( nPage==0 ){
42312       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
42313       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
42314       isWal = 0;
42315     }else{
42316       rc = sqlite3OsAccess(
42317           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
42318       );
42319     }
42320     if( rc==SQLITE_OK ){
42321       if( isWal ){
42322         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
42323         rc = sqlite3PagerOpenWal(pPager, 0);
42324       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42325         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42326       }
42327     }
42328   }
42329   return rc;
42330 }
42331 #endif
42332 
42333 /*
42334 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42335 ** the entire master journal file. The case pSavepoint==NULL occurs when 
42336 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
42337 ** savepoint.
42338 **
42339 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
42340 ** being rolled back), then the rollback consists of up to three stages,
42341 ** performed in the order specified:
42342 **
42343 **   * Pages are played back from the main journal starting at byte
42344 **     offset PagerSavepoint.iOffset and continuing to 
42345 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
42346 **     file if PagerSavepoint.iHdrOffset is zero.
42347 **
42348 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42349 **     back starting from the journal header immediately following 
42350 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
42351 **
42352 **   * Pages are then played back from the sub-journal file, starting
42353 **     with the PagerSavepoint.iSubRec and continuing to the end of
42354 **     the journal file.
42355 **
42356 ** Throughout the rollback process, each time a page is rolled back, the
42357 ** corresponding bit is set in a bitvec structure (variable pDone in the
42358 ** implementation below). This is used to ensure that a page is only
42359 ** rolled back the first time it is encountered in either journal.
42360 **
42361 ** If pSavepoint is NULL, then pages are only played back from the main
42362 ** journal file. There is no need for a bitvec in this case.
42363 **
42364 ** In either case, before playback commences the Pager.dbSize variable
42365 ** is reset to the value that it held at the start of the savepoint 
42366 ** (or transaction). No page with a page-number greater than this value
42367 ** is played back. If one is encountered it is simply skipped.
42368 */
42369 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42370   i64 szJ;                 /* Effective size of the main journal */
42371   i64 iHdrOff;             /* End of first segment of main-journal records */
42372   int rc = SQLITE_OK;      /* Return code */
42373   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
42374 
42375   assert( pPager->eState!=PAGER_ERROR );
42376   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42377 
42378   /* Allocate a bitvec to use to store the set of pages rolled back */
42379   if( pSavepoint ){
42380     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
42381     if( !pDone ){
42382       return SQLITE_NOMEM;
42383     }
42384   }
42385 
42386   /* Set the database size back to the value it was before the savepoint 
42387   ** being reverted was opened.
42388   */
42389   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42390   pPager->changeCountDone = pPager->tempFile;
42391 
42392   if( !pSavepoint && pagerUseWal(pPager) ){
42393     return pagerRollbackWal(pPager);
42394   }
42395 
42396   /* Use pPager->journalOff as the effective size of the main rollback
42397   ** journal.  The actual file might be larger than this in
42398   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
42399   ** past pPager->journalOff is off-limits to us.
42400   */
42401   szJ = pPager->journalOff;
42402   assert( pagerUseWal(pPager)==0 || szJ==0 );
42403 
42404   /* Begin by rolling back records from the main journal starting at
42405   ** PagerSavepoint.iOffset and continuing to the next journal header.
42406   ** There might be records in the main journal that have a page number
42407   ** greater than the current database size (pPager->dbSize) but those
42408   ** will be skipped automatically.  Pages are added to pDone as they
42409   ** are played back.
42410   */
42411   if( pSavepoint && !pagerUseWal(pPager) ){
42412     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42413     pPager->journalOff = pSavepoint->iOffset;
42414     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
42415       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42416     }
42417     assert( rc!=SQLITE_DONE );
42418   }else{
42419     pPager->journalOff = 0;
42420   }
42421 
42422   /* Continue rolling back records out of the main journal starting at
42423   ** the first journal header seen and continuing until the effective end
42424   ** of the main journal file.  Continue to skip out-of-range pages and
42425   ** continue adding pages rolled back to pDone.
42426   */
42427   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
42428     u32 ii;            /* Loop counter */
42429     u32 nJRec = 0;     /* Number of Journal Records */
42430     u32 dummy;
42431     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42432     assert( rc!=SQLITE_DONE );
42433 
42434     /*
42435     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42436     ** test is related to ticket #2565.  See the discussion in the
42437     ** pager_playback() function for additional information.
42438     */
42439     if( nJRec==0 
42440      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42441     ){
42442       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42443     }
42444     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42445       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42446     }
42447     assert( rc!=SQLITE_DONE );
42448   }
42449   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
42450 
42451   /* Finally,  rollback pages from the sub-journal.  Page that were
42452   ** previously rolled back out of the main journal (and are hence in pDone)
42453   ** will be skipped.  Out-of-range pages are also skipped.
42454   */
42455   if( pSavepoint ){
42456     u32 ii;            /* Loop counter */
42457     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
42458 
42459     if( pagerUseWal(pPager) ){
42460       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42461     }
42462     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
42463       assert( offset==(i64)ii*(4+pPager->pageSize) );
42464       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42465     }
42466     assert( rc!=SQLITE_DONE );
42467   }
42468 
42469   sqlite3BitvecDestroy(pDone);
42470   if( rc==SQLITE_OK ){
42471     pPager->journalOff = szJ;
42472   }
42473 
42474   return rc;
42475 }
42476 
42477 /*
42478 ** Change the maximum number of in-memory pages that are allowed.
42479 */
42480 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
42481   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
42482 }
42483 
42484 /*
42485 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
42486 */
42487 static void pagerFixMaplimit(Pager *pPager){
42488 #if SQLITE_MAX_MMAP_SIZE>0
42489   sqlite3_file *fd = pPager->fd;
42490   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
42491     sqlite3_int64 sz;
42492     sz = pPager->szMmap;
42493     pPager->bUseFetch = (sz>0);
42494     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
42495   }
42496 #endif
42497 }
42498 
42499 /*
42500 ** Change the maximum size of any memory mapping made of the database file.
42501 */
42502 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
42503   pPager->szMmap = szMmap;
42504   pagerFixMaplimit(pPager);
42505 }
42506 
42507 /*
42508 ** Free as much memory as possible from the pager.
42509 */
42510 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
42511   sqlite3PcacheShrink(pPager->pPCache);
42512 }
42513 
42514 /*
42515 ** Adjust settings of the pager to those specified in the pgFlags parameter.
42516 **
42517 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
42518 ** of the database to damage due to OS crashes or power failures by
42519 ** changing the number of syncs()s when writing the journals.
42520 ** There are three levels:
42521 **
42522 **    OFF       sqlite3OsSync() is never called.  This is the default
42523 **              for temporary and transient files.
42524 **
42525 **    NORMAL    The journal is synced once before writes begin on the
42526 **              database.  This is normally adequate protection, but
42527 **              it is theoretically possible, though very unlikely,
42528 **              that an inopertune power failure could leave the journal
42529 **              in a state which would cause damage to the database
42530 **              when it is rolled back.
42531 **
42532 **    FULL      The journal is synced twice before writes begin on the
42533 **              database (with some additional information - the nRec field
42534 **              of the journal header - being written in between the two
42535 **              syncs).  If we assume that writing a
42536 **              single disk sector is atomic, then this mode provides
42537 **              assurance that the journal will not be corrupted to the
42538 **              point of causing damage to the database during rollback.
42539 **
42540 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
42541 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
42542 ** prior to the start of checkpoint and that the database file is synced
42543 ** at the conclusion of the checkpoint if the entire content of the WAL
42544 ** was written back into the database.  But no sync operations occur for
42545 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
42546 ** file is synced following each commit operation, in addition to the
42547 ** syncs associated with NORMAL.
42548 **
42549 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
42550 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
42551 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
42552 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
42553 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
42554 ** synchronous=FULL versus synchronous=NORMAL setting determines when
42555 ** the xSync primitive is called and is relevant to all platforms.
42556 **
42557 ** Numeric values associated with these states are OFF==1, NORMAL=2,
42558 ** and FULL=3.
42559 */
42560 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
42561 SQLITE_PRIVATE void sqlite3PagerSetFlags(
42562   Pager *pPager,        /* The pager to set safety level for */
42563