System.Data.SQLite
Check-in [9e6956192d]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Update SQLite core library to the latest trunk code.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | core312
Files: files | file ages | folders
SHA1: 9e6956192dd7c0228d6e8c7a7dd24ecb998d7d86
User & Date: mistachkin 2016-03-22 15:16:02
Context
2016-03-22
15:29
Adapt to core library internal API changes and silence some compiler warnings. check-in: d64930a7c7 user: mistachkin tags: core312
15:16
Update SQLite core library to the latest trunk code. check-in: 9e6956192d user: mistachkin tags: core312
15:07
Add test suite infrastructure helper procedure to return the default page size. check-in: 8a5f7d7254 user: mistachkin tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to Doc/Extra/Provider/version.html.

    41     41         </table>
    42     42       </div>
    43     43       <div id="mainSection">
    44     44       <div id="mainBody">
    45     45       <h1 class="heading">Version History</h1>
    46     46       <p><b>1.0.100.0 - April XX, 2016 <font color="red">(release scheduled)</font></b></p>
    47     47       <ul>
    48         -      <li>Updated to <a href="https://www.sqlite.org/releaselog/3_11_1.html">SQLite 3.11.1</a>.</li>
           48  +      <li>Updated to <a href="https://www.sqlite.org/draft/releaselog/3_12_0.html">SQLite 3.12.0</a>.</li>
    49     49         <li>Properly handle NULL values in the &quot;name&quot; column of the results returned by PRAGMA index_info(). Fix for <a href="https://system.data.sqlite.org/index.html/info/5251bd0878">[5251bd0878]</a>.</li>
    50     50         <li>For column types that resolve to boolean, recognize case-insensitive prefixes of &quot;True&quot; and &quot;False&quot;. Fix for <a href="https://system.data.sqlite.org/index.html/info/dbd65441a5">[dbd65441a5]</a>.</li>
    51     51         <li>Add NoVerifyTextAffinity connection flag to skip type affinity checking when fetching a column value as a string. Pursuant to <a href="https://system.data.sqlite.org/index.html/info/dbd65441a5">[dbd65441a5]</a>.</li>
    52     52         <li>The UnixEpoch DateTime format should use Int64 internally, not Int32.&nbsp;<b>** Potentially Incompatible Change **</b></li>
    53     53         <li>Avoid using Path.Combine with null values in the native library pre-loader. Fix for <a href="https://system.data.sqlite.org/index.html/info/da685c0bac">[da685c0bac]</a>.</li>
    54     54         <li>Fix the (unsupported) legacy CryptoAPI based codec so that it no longer prevents page size changes.</li>
    55     55       </ul>

Changes to SQLite.Interop/props/sqlite3.props.

     5      5    *
     6      6    * Written by Joe Mistachkin.
     7      7    * Released to the public domain, use at your own risk!
     8      8    *
     9      9   -->
    10     10   <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
    11     11     <PropertyGroup Label="UserMacros">
    12         -    <SQLITE_MANIFEST_VERSION>3.11.1.0</SQLITE_MANIFEST_VERSION>
    13         -    <SQLITE_RC_VERSION>3,11,1,0</SQLITE_RC_VERSION>
           12  +    <SQLITE_MANIFEST_VERSION>3.12.0.0</SQLITE_MANIFEST_VERSION>
           13  +    <SQLITE_RC_VERSION>3,12,0,0</SQLITE_RC_VERSION>
    14     14       <SQLITE_COMMON_DEFINES>_CRT_SECURE_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;SQLITE_THREADSAFE=1;SQLITE_USE_URI=1;SQLITE_ENABLE_COLUMN_METADATA=1;SQLITE_ENABLE_STAT4=1;SQLITE_ENABLE_FTS3=1;SQLITE_ENABLE_LOAD_EXTENSION=1;SQLITE_ENABLE_RTREE=1;SQLITE_SOUNDEX=1;SQLITE_ENABLE_MEMORY_MANAGEMENT=1;SQLITE_ENABLE_API_ARMOR=1;SQLITE_ENABLE_DBSTAT_VTAB=1</SQLITE_COMMON_DEFINES>
    15     15       <SQLITE_EXTRA_DEFINES>SQLITE_PLACEHOLDER=1;SQLITE_HAS_CODEC=1</SQLITE_EXTRA_DEFINES>
    16     16       <SQLITE_WINCE_200X_DEFINES>SQLITE_OMIT_WAL=1</SQLITE_WINCE_200X_DEFINES>
    17     17       <SQLITE_WINCE_2013_DEFINES>HAVE_ERRNO_H=1;SQLITE_MSVC_LOCALTIME_API=1</SQLITE_WINCE_2013_DEFINES>
    18     18       <SQLITE_DEBUG_DEFINES>SQLITE_DEBUG=1;SQLITE_MEMDEBUG=1;SQLITE_ENABLE_EXPENSIVE_ASSERT=1</SQLITE_DEBUG_DEFINES>
    19     19       <SQLITE_RELEASE_DEFINES>SQLITE_WIN32_MALLOC=1</SQLITE_RELEASE_DEFINES>
    20     20       <SQLITE_DISABLE_WARNINGS>4055;4100;4127;4146;4210;4232;4244;4245;4267;4306;4389;4701;4703;4706</SQLITE_DISABLE_WARNINGS>

Changes to SQLite.Interop/props/sqlite3.vsprops.

    10     10   <VisualStudioPropertySheet
    11     11   	ProjectType="Visual C++"
    12     12   	Version="8.00"
    13     13   	Name="sqlite3"
    14     14   	>
    15     15   	<UserMacro
    16     16   		Name="SQLITE_MANIFEST_VERSION"
    17         -		Value="3.11.1.0"
           17  +		Value="3.12.0.0"
    18     18   		PerformEnvironmentSet="true"
    19     19   	/>
    20     20   	<UserMacro
    21     21   		Name="SQLITE_RC_VERSION"
    22         -		Value="3,11,1,0"
           22  +		Value="3,12,0,0"
    23     23   		PerformEnvironmentSet="true"
    24     24   	/>
    25     25   	<UserMacro
    26     26   		Name="SQLITE_COMMON_DEFINES"
    27     27   		Value="_CRT_SECURE_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;SQLITE_THREADSAFE=1;SQLITE_USE_URI=1;SQLITE_ENABLE_COLUMN_METADATA=1;SQLITE_ENABLE_STAT4=1;SQLITE_ENABLE_FTS3=1;SQLITE_ENABLE_LOAD_EXTENSION=1;SQLITE_ENABLE_RTREE=1;SQLITE_SOUNDEX=1;SQLITE_ENABLE_MEMORY_MANAGEMENT=1;SQLITE_ENABLE_API_ARMOR=1;SQLITE_ENABLE_DBSTAT_VTAB=1"
    28     28   		PerformEnvironmentSet="true"
    29     29   	/>

Changes to SQLite.Interop/src/core/sqlite3.c.

     1      1   /******************************************************************************
     2      2   ** This file is an amalgamation of many separate C source files from SQLite
     3         -** version 3.11.1.  By combining all the individual C code files into this 
            3  +** version 3.12.0.  By combining all the individual C code files into this 
     4      4   ** single large file, the entire code can be compiled as a single translation
     5      5   ** unit.  This allows many compilers to do optimizations that would not be
     6      6   ** possible if the files were compiled separately.  Performance improvements
     7      7   ** of 5% or more are commonly seen when SQLite is compiled as a single
     8      8   ** translation unit.
     9      9   **
    10     10   ** This file is all you need to compile SQLite.  To use SQLite in other
................................................................................
    36     36   *************************************************************************
    37     37   ** Internal interface definitions for SQLite.
    38     38   **
    39     39   */
    40     40   #ifndef _SQLITEINT_H_
    41     41   #define _SQLITEINT_H_
    42     42   
           43  +/*
           44  +** Make sure that rand_s() is available on Windows systems with MSVC 2005
           45  +** or higher.
           46  +*/
           47  +#if defined(_MSC_VER) && _MSC_VER>=1400
           48  +#  define _CRT_RAND_S
           49  +#endif
           50  +
    43     51   /*
    44     52   ** Include the header file used to customize the compiler options for MSVC.
    45     53   ** This should be done first so that it can successfully prevent spurious
    46     54   ** compiler warnings due to subsequent content in this file and other files
    47     55   ** that are included by this file.
    48     56   */
    49     57   /************** Include msvc.h in the middle of sqliteInt.h ******************/
................................................................................
   324    332   ** string contains the date and time of the check-in (UTC) and an SHA1
   325    333   ** hash of the entire source tree.
   326    334   **
   327    335   ** See also: [sqlite3_libversion()],
   328    336   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   329    337   ** [sqlite_version()] and [sqlite_source_id()].
   330    338   */
   331         -#define SQLITE_VERSION        "3.11.1"
   332         -#define SQLITE_VERSION_NUMBER 3011001
   333         -#define SQLITE_SOURCE_ID      "2016-03-03 16:17:53 f047920ce16971e573bc6ec9a48b118c9de2b3a7"
          339  +#define SQLITE_VERSION        "3.12.0"
          340  +#define SQLITE_VERSION_NUMBER 3012000
          341  +#define SQLITE_SOURCE_ID      "2016-03-22 15:01:54 e1ab2d376a72786098125a41c1ea8140fcbd15c6"
   334    342   
   335    343   /*
   336    344   ** CAPI3REF: Run-Time Library Version Numbers
   337    345   ** KEYWORDS: sqlite3_version, sqlite3_sourceid
   338    346   **
   339    347   ** These interfaces provide the same information as the [SQLITE_VERSION],
   340    348   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
  1441   1449     ** Those below are for version 3 and greater.
  1442   1450     */
  1443   1451     int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1444   1452     sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1445   1453     const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1446   1454     /*
  1447   1455     ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1448         -  ** New fields may be appended in figure versions.  The iVersion
         1456  +  ** New fields may be appended in future versions.  The iVersion
  1449   1457     ** value will increment whenever this happens. 
  1450   1458     */
  1451   1459   };
  1452   1460   
  1453   1461   /*
  1454   1462   ** CAPI3REF: Flags for the xAccess VFS method
  1455   1463   **
................................................................................
  2033   2041   ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2034   2042   ** sorter to that integer.  The default minimum PMA Size is set by the
  2035   2043   ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
  2036   2044   ** to help with sort operations when multithreaded sorting
  2037   2045   ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2038   2046   ** to be sorted exceeds the page size times the minimum of the
  2039   2047   ** [PRAGMA cache_size] setting and this value.
         2048  +**
         2049  +** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
         2050  +** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
         2051  +** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
         2052  +** becomes the [statement journal] spill-to-disk threshold.  
         2053  +** [Statement journals] are held in memory until their size (in bytes)
         2054  +** exceeds this threshold, at which point they are written to disk.
         2055  +** Or if the threshold is -1, statement journals are always held
         2056  +** exclusively in memory.
         2057  +** Since many statement journals never become large, setting the spill
         2058  +** threshold to a value such as 64KiB can greatly reduce the amount of
         2059  +** I/O required to support statement rollback.
         2060  +** The default value for this setting is controlled by the
         2061  +** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2040   2062   ** </dl>
  2041   2063   */
  2042   2064   #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  2043   2065   #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  2044   2066   #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  2045   2067   #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  2046   2068   #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
................................................................................
  2060   2082   #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  2061   2083   #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
  2062   2084   #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
  2063   2085   #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
  2064   2086   #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
  2065   2087   #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
  2066   2088   #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
         2089  +#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
  2067   2090   
  2068   2091   /*
  2069   2092   ** CAPI3REF: Database Connection Configuration Options
  2070   2093   **
  2071   2094   ** These constants are the available integer configuration options that
  2072   2095   ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2073   2096   **
................................................................................
  2117   2140   ** The first argument is an integer which is 0 to disable triggers,
  2118   2141   ** positive to enable triggers or negative to leave the setting unchanged.
  2119   2142   ** The second parameter is a pointer to an integer into which
  2120   2143   ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2121   2144   ** following this call.  The second parameter may be a NULL pointer, in
  2122   2145   ** which case the trigger setting is not reported back. </dd>
  2123   2146   **
         2147  +** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
         2148  +** <dd> ^This option is used to enable or disable the two-argument
         2149  +** version of the [fts3_tokenizer()] function which is part of the
         2150  +** [FTS3] full-text search engine extension.
         2151  +** There should be two additional arguments.
         2152  +** The first argument is an integer which is 0 to disable fts3_tokenizer() or
         2153  +** positive to enable fts3_tokenizer() or negative to leave the setting
         2154  +** unchanged.
         2155  +** The second parameter is a pointer to an integer into which
         2156  +** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
         2157  +** following this call.  The second parameter may be a NULL pointer, in
         2158  +** which case the new setting is not reported back. </dd>
         2159  +**
  2124   2160   ** </dl>
  2125   2161   */
  2126         -#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
  2127         -#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
  2128         -#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
         2162  +#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
         2163  +#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
         2164  +#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
         2165  +#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  2129   2166   
  2130   2167   
  2131   2168   /*
  2132   2169   ** CAPI3REF: Enable Or Disable Extended Result Codes
  2133   2170   ** METHOD: sqlite3
  2134   2171   **
  2135   2172   ** ^The sqlite3_extended_result_codes() routine enables or disables the
................................................................................
  7702   7739   ** are undefined.
  7703   7740   **
  7704   7741   ** A single database handle may have at most a single write-ahead log callback 
  7705   7742   ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7706   7743   ** previously registered write-ahead log callback. ^Note that the
  7707   7744   ** [sqlite3_wal_autocheckpoint()] interface and the
  7708   7745   ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7709         -** those overwrite any prior [sqlite3_wal_hook()] settings.
         7746  +** overwrite any prior [sqlite3_wal_hook()] settings.
  7710   7747   */
  7711   7748   SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7712   7749     sqlite3*, 
  7713   7750     int(*)(void *,sqlite3*,const char*,int),
  7714   7751     void*
  7715   7752   );
  7716   7753   
................................................................................
  8099   8136   ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  8100   8137   **
  8101   8138   ** ^This function does not set the database handle error code or message
  8102   8139   ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  8103   8140   */
  8104   8141   SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
  8105   8142   
         8143  +/*
         8144  +** CAPI3REF: Low-level system error code
         8145  +**
         8146  +** ^Attempt to return the underlying operating system error code or error
         8147  +** number that caused the most reason I/O error or failure to open a file.
         8148  +** The return value is OS-dependent.  For example, on unix systems, after
         8149  +** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
         8150  +** called to get back the underlying "errno" that caused the problem, such
         8151  +** as ENOSPC, EAUTH, EISDIR, and so forth.  
         8152  +*/
         8153  +SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3*);
         8154  +
  8106   8155   /*
  8107   8156   ** CAPI3REF: Database Snapshot
  8108   8157   ** KEYWORDS: {snapshot}
  8109   8158   ** EXPERIMENTAL
  8110   8159   **
  8111   8160   ** An instance of the snapshot object records the state of a [WAL mode]
  8112   8161   ** database for some specific point in history.
................................................................................
  8167   8216   ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  8168   8217   ** or an appropriate [error code] if it fails.
  8169   8218   **
  8170   8219   ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  8171   8220   ** the first operation, apart from other sqlite3_snapshot_open() calls,
  8172   8221   ** following the [BEGIN] that starts a new read transaction.
  8173   8222   ** ^A [snapshot] will fail to open if it has been overwritten by a 
  8174         -** [checkpoint].  
         8223  +** [checkpoint].
         8224  +** ^A [snapshot] will fail to open if the database connection D has not
         8225  +** previously completed at least one read operation against the database 
         8226  +** file.  (Hint: Run "[PRAGMA application_id]" against a newly opened
         8227  +** database connection in order to make it ready to use snapshots.)
  8175   8228   **
  8176   8229   ** The [sqlite3_snapshot_open()] interface is only available when the
  8177   8230   ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8178   8231   */
  8179   8232   SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
  8180   8233     sqlite3 *db,
  8181   8234     const char *zSchema,
................................................................................
  9017   9070   #endif
  9018   9071   
  9019   9072   /*
  9020   9073   ** The suggested maximum number of in-memory pages to use for
  9021   9074   ** the main database table and for temporary tables.
  9022   9075   **
  9023   9076   ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
  9024         -** is 2000 pages.
         9077  +** is 2000*1024 bytes.
  9025   9078   ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  9026   9079   ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  9027   9080   */
  9028   9081   #ifndef SQLITE_DEFAULT_CACHE_SIZE
  9029         -# define SQLITE_DEFAULT_CACHE_SIZE  2000
         9082  +# define SQLITE_DEFAULT_CACHE_SIZE  -2000
  9030   9083   #endif
  9031   9084   
  9032   9085   /*
  9033   9086   ** The default number of frames to accumulate in the log file before
  9034   9087   ** checkpointing the database in WAL mode.
  9035   9088   */
  9036   9089   #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  9037   9090   # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
  9038   9091   #endif
  9039   9092   
  9040   9093   /*
  9041   9094   ** The maximum number of attached databases.  This must be between 0
  9042         -** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
  9043         -** is used internally to track attached databases.
         9095  +** and 125.  The upper bound of 125 is because the attached databases are
         9096  +** counted using a signed 8-bit integer which has a maximum value of 127
         9097  +** and we have to allow 2 extra counts for the "main" and "temp" databases.
  9044   9098   */
  9045   9099   #ifndef SQLITE_MAX_ATTACHED
  9046   9100   # define SQLITE_MAX_ATTACHED 10
  9047   9101   #endif
  9048   9102   
  9049   9103   
  9050   9104   /*
................................................................................
  9071   9125   #define SQLITE_MAX_PAGE_SIZE 65536
  9072   9126   
  9073   9127   
  9074   9128   /*
  9075   9129   ** The default size of a database page.
  9076   9130   */
  9077   9131   #ifndef SQLITE_DEFAULT_PAGE_SIZE
  9078         -# define SQLITE_DEFAULT_PAGE_SIZE 1024
         9132  +# define SQLITE_DEFAULT_PAGE_SIZE 4096
  9079   9133   #endif
  9080   9134   #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  9081   9135   # undef SQLITE_DEFAULT_PAGE_SIZE
  9082   9136   # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  9083   9137   #endif
  9084   9138   
  9085   9139   /*
................................................................................
  9152   9206   
  9153   9207   /*
  9154   9208   ** The following macros are used to cast pointers to integers and
  9155   9209   ** integers to pointers.  The way you do this varies from one compiler
  9156   9210   ** to the next, so we have developed the following set of #if statements
  9157   9211   ** to generate appropriate macros for a wide range of compilers.
  9158   9212   **
  9159         -** The correct "ANSI" way to do this is to use the intptr_t type. 
         9213  +** The correct "ANSI" way to do this is to use the intptr_t type.
  9160   9214   ** Unfortunately, that typedef is not available on all compilers, or
  9161   9215   ** if it is available, it requires an #include of specific headers
  9162   9216   ** that vary from one machine to the next.
  9163   9217   **
  9164   9218   ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
  9165   9219   ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
  9166   9220   ** So we have to define the macros in different ways depending on the
................................................................................
  9176   9230   # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
  9177   9231   # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
  9178   9232   #else                          /* Generates a warning - but it always works */
  9179   9233   # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
  9180   9234   # define SQLITE_PTR_TO_INT(X)  ((int)(X))
  9181   9235   #endif
  9182   9236   
  9183         -/*
  9184         -** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  9185         -** something between S (inclusive) and E (exclusive).
  9186         -**
  9187         -** In other words, S is a buffer and E is a pointer to the first byte after
  9188         -** the end of buffer S.  This macro returns true if P points to something
  9189         -** contained within the buffer S.
  9190         -*/
  9191         -#if defined(HAVE_STDINT_H)
  9192         -# define SQLITE_WITHIN(P,S,E) \
  9193         -    ((uintptr_t)(P)>=(uintptr_t)(S) && (uintptr_t)(P)<(uintptr_t)(E))
  9194         -#else
  9195         -# define SQLITE_WITHIN(P,S,E) ((P)>=(S) && (P)<(E))
  9196         -#endif
  9197         -
  9198   9237   /*
  9199   9238   ** A macro to hint to the compiler that a function should not be
  9200   9239   ** inlined.
  9201   9240   */
  9202   9241   #if defined(__GNUC__)
  9203   9242   #  define SQLITE_NOINLINE  __attribute__((noinline))
  9204   9243   #elif defined(_MSC_VER) && _MSC_VER>=1310
................................................................................
  9319   9358   **
  9320   9359   ** Setting NDEBUG makes the code smaller and faster by disabling the
  9321   9360   ** assert() statements in the code.  So we want the default action
  9322   9361   ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  9323   9362   ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
  9324   9363   ** feature.
  9325   9364   */
  9326         -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
         9365  +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  9327   9366   # define NDEBUG 1
  9328   9367   #endif
  9329   9368   #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  9330   9369   # undef NDEBUG
  9331   9370   #endif
  9332   9371   
  9333   9372   /*
................................................................................
  9334   9373   ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  9335   9374   */
  9336   9375   #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  9337   9376   # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  9338   9377   #endif
  9339   9378   
  9340   9379   /*
  9341         -** The testcase() macro is used to aid in coverage testing.  When 
         9380  +** The testcase() macro is used to aid in coverage testing.  When
  9342   9381   ** doing coverage testing, the condition inside the argument to
  9343   9382   ** testcase() must be evaluated both true and false in order to
  9344   9383   ** get full branch coverage.  The testcase() macro is inserted
  9345   9384   ** to help ensure adequate test coverage in places where simple
  9346   9385   ** condition/decision coverage is inadequate.  For example, testcase()
  9347   9386   ** can be used to make sure boundary values are tested.  For
  9348   9387   ** bitmask tests, testcase() can be used to make sure each bit
................................................................................
  9380   9419   #ifndef NDEBUG
  9381   9420   # define VVA_ONLY(X)  X
  9382   9421   #else
  9383   9422   # define VVA_ONLY(X)
  9384   9423   #endif
  9385   9424   
  9386   9425   /*
  9387         -** The ALWAYS and NEVER macros surround boolean expressions which 
         9426  +** The ALWAYS and NEVER macros surround boolean expressions which
  9388   9427   ** are intended to always be true or false, respectively.  Such
  9389   9428   ** expressions could be omitted from the code completely.  But they
  9390   9429   ** are included in a few cases in order to enhance the resilience
  9391   9430   ** of SQLite to unexpected behavior - to make the code "self-healing"
  9392   9431   ** or "ductile" rather than being "brittle" and crashing at the first
  9393   9432   ** hint of unplanned behavior.
  9394   9433   **
................................................................................
  9446   9485   #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  9447   9486       (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  9448   9487   # define SQLITE_NEED_ERR_NAME
  9449   9488   #else
  9450   9489   # undef  SQLITE_NEED_ERR_NAME
  9451   9490   #endif
  9452   9491   
         9492  +/*
         9493  +** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
         9494  +*/
         9495  +#ifdef SQLITE_OMIT_EXPLAIN
         9496  +# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
         9497  +#endif
         9498  +
  9453   9499   /*
  9454   9500   ** Return true (non-zero) if the input is an integer that is too large
  9455   9501   ** to fit in 32-bits.  This macro is used inside of various testcase()
  9456   9502   ** macros to verify that we have tested SQLite for large-file support.
  9457   9503   */
  9458   9504   #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
  9459   9505   
................................................................................
  9724   9770   #define TK_COLUMN                         152
  9725   9771   #define TK_AGG_FUNCTION                   153
  9726   9772   #define TK_AGG_COLUMN                     154
  9727   9773   #define TK_UMINUS                         155
  9728   9774   #define TK_UPLUS                          156
  9729   9775   #define TK_REGISTER                       157
  9730   9776   #define TK_ASTERISK                       158
  9731         -#define TK_SPACE                          159
  9732         -#define TK_ILLEGAL                        160
         9777  +#define TK_SPAN                           159
         9778  +#define TK_SPACE                          160
         9779  +#define TK_ILLEGAL                        161
  9733   9780   
  9734   9781   /* The token codes above must all fit in 8 bits */
  9735   9782   #define TKFLG_MASK           0xff  
  9736   9783   
  9737   9784   /* Flags that can be added to a token code when it is not
  9738   9785   ** being stored in a u8: */
  9739   9786   #define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
................................................................................
  9764   9811   #endif
  9765   9812   #ifndef SQLITE_BIG_DBL
  9766   9813   # define SQLITE_BIG_DBL (1e99)
  9767   9814   #endif
  9768   9815   
  9769   9816   /*
  9770   9817   ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  9771         -** afterward. Having this macro allows us to cause the C compiler 
         9818  +** afterward. Having this macro allows us to cause the C compiler
  9772   9819   ** to omit code used by TEMP tables without messy #ifndef statements.
  9773   9820   */
  9774   9821   #ifdef SQLITE_OMIT_TEMPDB
  9775   9822   #define OMIT_TEMPDB 1
  9776   9823   #else
  9777   9824   #define OMIT_TEMPDB 0
  9778   9825   #endif
................................................................................
  9803   9850   #ifndef SQLITE_TEMP_STORE
  9804   9851   # define SQLITE_TEMP_STORE 1
  9805   9852   # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
  9806   9853   #endif
  9807   9854   
  9808   9855   /*
  9809   9856   ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  9810         -** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it 
         9857  +** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  9811   9858   ** to zero.
  9812   9859   */
  9813   9860   #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  9814   9861   # undef SQLITE_MAX_WORKER_THREADS
  9815   9862   # define SQLITE_MAX_WORKER_THREADS 0
  9816   9863   #endif
  9817   9864   #ifndef SQLITE_MAX_WORKER_THREADS
................................................................................
  9842   9889   #ifndef offsetof
  9843   9890   #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  9844   9891   #endif
  9845   9892   
  9846   9893   /*
  9847   9894   ** Macros to compute minimum and maximum of two numbers.
  9848   9895   */
  9849         -#define MIN(A,B) ((A)<(B)?(A):(B))
  9850         -#define MAX(A,B) ((A)>(B)?(A):(B))
         9896  +#ifndef MIN
         9897  +# define MIN(A,B) ((A)<(B)?(A):(B))
         9898  +#endif
         9899  +#ifndef MAX
         9900  +# define MAX(A,B) ((A)>(B)?(A):(B))
         9901  +#endif
  9851   9902   
  9852   9903   /*
  9853   9904   ** Swap two objects of type TYPE.
  9854   9905   */
  9855   9906   #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  9856   9907   
  9857   9908   /*
................................................................................
  9951  10002   ** Examples:
  9952  10003   **      1 -> 0              20 -> 43          10000 -> 132
  9953  10004   **      2 -> 10             25 -> 46          25000 -> 146
  9954  10005   **      3 -> 16            100 -> 66        1000000 -> 199
  9955  10006   **      4 -> 20           1000 -> 99        1048576 -> 200
  9956  10007   **     10 -> 33           1024 -> 100    4294967296 -> 320
  9957  10008   **
  9958         -** The LogEst can be negative to indicate fractional values. 
        10009  +** The LogEst can be negative to indicate fractional values.
  9959  10010   ** Examples:
  9960  10011   **
  9961  10012   **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
  9962  10013   */
  9963  10014   typedef INT16_TYPE LogEst;
  9964  10015   
  9965  10016   /*
................................................................................
  9971  10022   # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
  9972  10023          defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
  9973  10024   #   define SQLITE_PTRSIZE 4
  9974  10025   # else
  9975  10026   #   define SQLITE_PTRSIZE 8
  9976  10027   # endif
  9977  10028   #endif
        10029  +
        10030  +/* The uptr type is an unsigned integer large enough to hold a pointer
        10031  +*/
        10032  +#if defined(HAVE_STDINT_H)
        10033  +  typedef uintptr_t uptr;
        10034  +#elif SQLITE_PTRSIZE==4
        10035  +  typedef u32 uptr;
        10036  +#else
        10037  +  typedef u64 uptr;
        10038  +#endif
        10039  +
        10040  +/*
        10041  +** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
        10042  +** something between S (inclusive) and E (exclusive).
        10043  +**
        10044  +** In other words, S is a buffer and E is a pointer to the first byte after
        10045  +** the end of buffer S.  This macro returns true if P points to something
        10046  +** contained within the buffer S.
        10047  +*/
        10048  +#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
        10049  +
  9978  10050   
  9979  10051   /*
  9980  10052   ** Macros to determine whether the machine is big or little endian,
  9981  10053   ** and whether or not that determination is run-time or compile-time.
  9982  10054   **
  9983  10055   ** For best performance, an attempt is made to guess at the byte-order
  9984  10056   ** using C-preprocessor macros.  If that is unsuccessful, or if
................................................................................
 10017  10089   ** Constants for the largest and smallest possible 64-bit signed integers.
 10018  10090   ** These macros are designed to work correctly on both 32-bit and 64-bit
 10019  10091   ** compilers.
 10020  10092   */
 10021  10093   #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
 10022  10094   #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
 10023  10095   
 10024         -/* 
        10096  +/*
 10025  10097   ** Round up a number to the next larger multiple of 8.  This is used
 10026  10098   ** to force 8-byte alignment on 64-bit architectures.
 10027  10099   */
 10028  10100   #define ROUND8(x)     (((x)+7)&~7)
 10029  10101   
 10030  10102   /*
 10031  10103   ** Round down to the nearest multiple of 8
................................................................................
 10111  10183   # define SELECTTRACE_ENABLED 1
 10112  10184   #else
 10113  10185   # define SELECTTRACE_ENABLED 0
 10114  10186   #endif
 10115  10187   
 10116  10188   /*
 10117  10189   ** An instance of the following structure is used to store the busy-handler
 10118         -** callback for a given sqlite handle. 
        10190  +** callback for a given sqlite handle.
 10119  10191   **
 10120  10192   ** The sqlite.busyHandler member of the sqlite struct contains the busy
 10121  10193   ** callback for the database handle. Each pager opened via the sqlite
 10122  10194   ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
 10123  10195   ** callback is currently invoked only from within pager.c.
 10124  10196   */
 10125  10197   typedef struct BusyHandler BusyHandler;
................................................................................
 10156  10228   /*
 10157  10229   ** Determine if the argument is a power of two
 10158  10230   */
 10159  10231   #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
 10160  10232   
 10161  10233   /*
 10162  10234   ** The following value as a destructor means to use sqlite3DbFree().
 10163         -** The sqlite3DbFree() routine requires two parameters instead of the 
 10164         -** one parameter that destructors normally want.  So we have to introduce 
 10165         -** this magic value that the code knows to handle differently.  Any 
        10235  +** The sqlite3DbFree() routine requires two parameters instead of the
        10236  +** one parameter that destructors normally want.  So we have to introduce
        10237  +** this magic value that the code knows to handle differently.  Any
 10166  10238   ** pointer will work here as long as it is distinct from SQLITE_STATIC
 10167  10239   ** and SQLITE_TRANSIENT.
 10168  10240   */
 10169  10241   #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
 10170  10242   
 10171  10243   /*
 10172  10244   ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
................................................................................
 10185  10257   #ifdef SQLITE_OMIT_WSD
 10186  10258     #define SQLITE_WSD const
 10187  10259     #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
 10188  10260     #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
 10189  10261   SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
 10190  10262   SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
 10191  10263   #else
 10192         -  #define SQLITE_WSD 
        10264  +  #define SQLITE_WSD
 10193  10265     #define GLOBAL(t,v) v
 10194  10266     #define sqlite3GlobalConfig sqlite3Config
 10195  10267   #endif
 10196  10268   
 10197  10269   /*
 10198  10270   ** The following macros are used to suppress compiler warnings and to
 10199         -** make it clear to human readers when a function parameter is deliberately 
        10271  +** make it clear to human readers when a function parameter is deliberately
 10200  10272   ** left unused within the body of a function. This usually happens when
 10201         -** a function is called via a function pointer. For example the 
        10273  +** a function is called via a function pointer. For example the
 10202  10274   ** implementation of an SQL aggregate step callback may not use the
 10203  10275   ** parameter indicating the number of arguments passed to the aggregate,
 10204  10276   ** if it knows that this is enforced elsewhere.
 10205  10277   **
 10206  10278   ** When a function parameter is not used at all within the body of a function,
 10207  10279   ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
 10208  10280   ** However, these macros may also be used to suppress warnings related to
................................................................................
 10260  10332   typedef struct VTable VTable;
 10261  10333   typedef struct VtabCtx VtabCtx;
 10262  10334   typedef struct Walker Walker;
 10263  10335   typedef struct WhereInfo WhereInfo;
 10264  10336   typedef struct With With;
 10265  10337   
 10266  10338   /*
 10267         -** Defer sourcing vdbe.h and btree.h until after the "u8" and 
        10339  +** Defer sourcing vdbe.h and btree.h until after the "u8" and
 10268  10340   ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
 10269  10341   ** pointer types (i.e. FuncDef) defined above.
 10270  10342   */
 10271  10343   /************** Include btree.h in the middle of sqliteInt.h *****************/
 10272  10344   /************** Begin file btree.h *******************************************/
 10273  10345   /*
 10274  10346   ** 2001 September 15
................................................................................
 10336  10408   SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
 10337  10409   SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
 10338  10410   SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
 10339  10411   #if SQLITE_MAX_MMAP_SIZE>0
 10340  10412   SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
 10341  10413   #endif
 10342  10414   SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
 10343         -SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
 10344  10415   SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
 10345  10416   SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
 10346  10417   SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
 10347  10418   SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
 10348  10419   SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
 10349  10420   SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
 10350  10421   SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
................................................................................
 11012  11083   SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
 11013  11084   SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
 11014  11085   SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
 11015  11086   SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
 11016  11087   SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
 11017  11088   SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
 11018  11089   SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
        11090  +SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
 11019  11091   SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
 11020  11092   SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
 11021  11093   SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
 11022  11094   SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
 11023  11095   SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
 11024  11096   SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
 11025  11097   #ifdef SQLITE_DEBUG
................................................................................
 11315  11387   #endif
 11316  11388   SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
 11317  11389   SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
 11318  11390   SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
 11319  11391   SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
 11320  11392   SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
 11321  11393   SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
 11322         -SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
 11323  11394   SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
 11324  11395   SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
 11325  11396   SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
 11326  11397   SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
 11327  11398   SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
 11328  11399   
 11329  11400   /* Functions used to truncate the database file. */
................................................................................
 11531  11602   SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
 11532  11603   SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
 11533  11604   
 11534  11605   #endif /* _PCACHE_H_ */
 11535  11606   
 11536  11607   /************** End of pcache.h **********************************************/
 11537  11608   /************** Continuing where we left off in sqliteInt.h ******************/
 11538         -
 11539  11609   /************** Include os.h in the middle of sqliteInt.h ********************/
 11540  11610   /************** Begin file os.h **********************************************/
 11541  11611   /*
 11542  11612   ** 2001 September 16
 11543  11613   **
 11544  11614   ** The author disclaims copyright to this source code.  In place of
 11545  11615   ** a legal notice, here is a blessing:
................................................................................
 11794  11864   SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
 11795  11865   SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
 11796  11866   SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
 11797  11867   SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
 11798  11868   #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 11799  11869   SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
 11800  11870   SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
        11871  +SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
 11801  11872   SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
 11802  11873   
 11803  11874   /*
 11804  11875   ** Convenience functions for opening and closing files using 
 11805  11876   ** sqlite3_malloc() to obtain space for the file-handle structure.
 11806  11877   */
 11807  11878   SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
................................................................................
 11883  11954   #else
 11884  11955   #define MUTEX_LOGIC(X)            X
 11885  11956   #endif /* defined(SQLITE_MUTEX_OMIT) */
 11886  11957   
 11887  11958   /************** End of mutex.h ***********************************************/
 11888  11959   /************** Continuing where we left off in sqliteInt.h ******************/
 11889  11960   
        11961  +/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
        11962  +** synchronous setting to EXTRA.  It is no longer supported.
        11963  +*/
        11964  +#ifdef SQLITE_EXTRA_DURABLE
        11965  +# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
        11966  +# define SQLITE_DEFAULT_SYNCHRONOUS 3
        11967  +#endif
        11968  +
        11969  +/*
        11970  +** Default synchronous levels.
        11971  +**
        11972  +** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
        11973  +** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
        11974  +**
        11975  +**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
        11976  +**   OFF           1                         0
        11977  +**   NORMAL        2                         1
        11978  +**   FULL          3                         2
        11979  +**   EXTRA         4                         3
        11980  +**
        11981  +** The "PRAGMA synchronous" statement also uses the zero-based numbers.
        11982  +** In other words, the zero-based numbers are used for all external interfaces
        11983  +** and the one-based values are used internally.
        11984  +*/
        11985  +#ifndef SQLITE_DEFAULT_SYNCHRONOUS
        11986  +# define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
        11987  +#endif
        11988  +#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
        11989  +# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
        11990  +#endif
 11890  11991   
 11891  11992   /*
 11892  11993   ** Each database file to be accessed by the system is an instance
 11893  11994   ** of the following structure.  There are normally two of these structures
 11894  11995   ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
 11895  11996   ** aDb[1] is the database file used to hold temporary tables.  Additional
 11896  11997   ** databases may be attached.
 11897  11998   */
 11898  11999   struct Db {
 11899  12000     char *zName;         /* Name of this database */
 11900  12001     Btree *pBt;          /* The B*Tree structure for this database file */
 11901  12002     u8 safety_level;     /* How aggressive at syncing data to disk */
        12003  +  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
 11902  12004     Schema *pSchema;     /* Pointer to database schema (possibly shared) */
 11903  12005   };
 11904  12006   
 11905  12007   /*
 11906  12008   ** An instance of the following structure stores a database schema.
 11907  12009   **
 11908  12010   ** Most Schema objects are associated with a Btree.  The exception is
 11909  12011   ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
 11910  12012   ** In shared cache mode, a single Schema object can be shared by multiple
 11911  12013   ** Btrees that refer to the same underlying BtShared object.
 11912         -** 
        12014  +**
 11913  12015   ** Schema objects are automatically deallocated when the last Btree that
 11914  12016   ** references them is destroyed.   The TEMP Schema is manually freed by
 11915  12017   ** sqlite3_close().
 11916  12018   *
 11917  12019   ** A thread must be holding a mutex on the corresponding Btree in order
 11918  12020   ** to access Schema content.  This implies that the thread must also be
 11919  12021   ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
................................................................................
 11930  12032     u8 file_format;      /* Schema format version for this file */
 11931  12033     u8 enc;              /* Text encoding used by this database */
 11932  12034     u16 schemaFlags;     /* Flags associated with this schema */
 11933  12035     int cache_size;      /* Number of pages to use in the cache */
 11934  12036   };
 11935  12037   
 11936  12038   /*
 11937         -** These macros can be used to test, set, or clear bits in the 
        12039  +** These macros can be used to test, set, or clear bits in the
 11938  12040   ** Db.pSchema->flags field.
 11939  12041   */
 11940  12042   #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
 11941  12043   #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
 11942  12044   #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
 11943  12045   #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
 11944  12046   
................................................................................
 11994  12096     void *pEnd;             /* First byte past end of available space */
 11995  12097   };
 11996  12098   struct LookasideSlot {
 11997  12099     LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
 11998  12100   };
 11999  12101   
 12000  12102   /*
 12001         -** A hash table for function definitions.
        12103  +** A hash table for built-in function definitions.  (Application-defined
        12104  +** functions use a regular table table from hash.h.)
 12002  12105   **
 12003  12106   ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
 12004         -** Collisions are on the FuncDef.pHash chain.
        12107  +** Collisions are on the FuncDef.u.pHash chain.
 12005  12108   */
        12109  +#define SQLITE_FUNC_HASH_SZ 23
 12006  12110   struct FuncDefHash {
 12007         -  FuncDef *a[23];       /* Hash table for functions */
        12111  +  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
 12008  12112   };
 12009  12113   
 12010  12114   #ifdef SQLITE_USER_AUTHENTICATION
 12011  12115   /*
 12012  12116   ** Information held in the "sqlite3" database connection object and used
 12013  12117   ** to manage user authentication.
 12014  12118   */
................................................................................
 12058  12162     int nDb;                      /* Number of backends currently in use */
 12059  12163     int flags;                    /* Miscellaneous flags. See below */
 12060  12164     i64 lastRowid;                /* ROWID of most recent insert (see above) */
 12061  12165     i64 szMmap;                   /* Default mmap_size setting */
 12062  12166     unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
 12063  12167     int errCode;                  /* Most recent error code (SQLITE_*) */
 12064  12168     int errMask;                  /* & result codes with this before returning */
        12169  +  int iSysErrno;                /* Errno value from last system error */
 12065  12170     u16 dbOptFlags;               /* Flags to enable/disable optimizations */
 12066  12171     u8 enc;                       /* Text encoding */
 12067  12172     u8 autoCommit;                /* The auto-commit flag. */
 12068  12173     u8 temp_store;                /* 1: file 2: memory 0: default */
 12069  12174     u8 mallocFailed;              /* True if we have seen a malloc failure */
 12070  12175     u8 bBenignMalloc;             /* Do not require OOMs if true */
 12071  12176     u8 dfltLockMode;              /* Default locking-mode for attached dbs */
................................................................................
 12093  12198     int nVDestroy;                /* Number of active OP_VDestroy operations */
 12094  12199     int nExtension;               /* Number of loaded extensions */
 12095  12200     void **aExtension;            /* Array of shared library handles */
 12096  12201     void (*xTrace)(void*,const char*);        /* Trace function */
 12097  12202     void *pTraceArg;                          /* Argument to the trace function */
 12098  12203     void (*xProfile)(void*,const char*,u64);  /* Profiling function */
 12099  12204     void *pProfileArg;                        /* Argument to profile function */
 12100         -  void *pCommitArg;                 /* Argument to xCommitCallback() */   
        12205  +  void *pCommitArg;                 /* Argument to xCommitCallback() */
 12101  12206     int (*xCommitCallback)(void*);    /* Invoked at every commit. */
 12102         -  void *pRollbackArg;               /* Argument to xRollbackCallback() */   
        12207  +  void *pRollbackArg;               /* Argument to xRollbackCallback() */
 12103  12208     void (*xRollbackCallback)(void*); /* Invoked at every commit. */
 12104  12209     void *pUpdateArg;
 12105  12210     void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
 12106  12211   #ifndef SQLITE_OMIT_WAL
 12107  12212     int (*xWalCallback)(void *, sqlite3 *, const char *, int);
 12108  12213     void *pWalArg;
 12109  12214   #endif
................................................................................
 12128  12233   #ifndef SQLITE_OMIT_VIRTUALTABLE
 12129  12234     int nVTrans;                  /* Allocated size of aVTrans */
 12130  12235     Hash aModule;                 /* populated by sqlite3_create_module() */
 12131  12236     VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
 12132  12237     VTable **aVTrans;             /* Virtual tables with open transactions */
 12133  12238     VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
 12134  12239   #endif
 12135         -  FuncDefHash aFunc;            /* Hash table of connection functions */
        12240  +  Hash aFunc;                   /* Hash table of connection functions */
 12136  12241     Hash aCollSeq;                /* All collating sequences */
 12137  12242     BusyHandler busyHandler;      /* Busy callback */
 12138  12243     Db aDbStatic[2];              /* Static space for the 2 default backends */
 12139  12244     Savepoint *pSavepoint;        /* List of active savepoints */
 12140  12245     int busyTimeout;              /* Busy handler timeout, in msec */
 12141  12246     int nSavepoint;               /* Number of non-transaction savepoints */
 12142  12247     int nStatement;               /* Number of nested statement-transactions  */
 12143  12248     i64 nDeferredCons;            /* Net deferred constraints this transaction. */
 12144  12249     i64 nDeferredImmCons;         /* Net deferred immediate constraints */
 12145  12250     int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
 12146  12251   #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 12147         -  /* The following variables are all protected by the STATIC_MASTER 
 12148         -  ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
        12252  +  /* The following variables are all protected by the STATIC_MASTER
        12253  +  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
 12149  12254     **
 12150  12255     ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
 12151  12256     ** unlock so that it can proceed.
 12152  12257     **
 12153  12258     ** When X.pBlockingConnection==Y, that means that something that X tried
 12154  12259     ** tried to do recently failed with an SQLITE_LOCKED error due to locks
 12155  12260     ** held by Y.
................................................................................
 12202  12307   #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
 12203  12308   #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
 12204  12309   #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
 12205  12310   #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
 12206  12311   #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
 12207  12312   #define SQLITE_Vacuum         0x08000000  /* Currently in a VACUUM */
 12208  12313   #define SQLITE_CellSizeCk     0x10000000  /* Check btree cell sizes on load */
        12314  +#define SQLITE_Fts3Tokenizer  0x20000000  /* Enable fts3_tokenizer(2) */
 12209  12315   
 12210  12316   
 12211  12317   /*
 12212  12318   ** Bits of the sqlite3.dbOptFlags field that are used by the
 12213  12319   ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
 12214  12320   ** selectively disable various optimizations.
 12215  12321   */
................................................................................
 12255  12361   #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
 12256  12362   #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
 12257  12363   #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
 12258  12364   #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
 12259  12365   
 12260  12366   /*
 12261  12367   ** Each SQL function is defined by an instance of the following
 12262         -** structure.  A pointer to this structure is stored in the sqlite.aFunc
 12263         -** hash table.  When multiple functions have the same name, the hash table
 12264         -** points to a linked list of these structures.
        12368  +** structure.  For global built-in functions (ex: substr(), max(), count())
        12369  +** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
        12370  +** For per-connection application-defined functions, a pointer to this
        12371  +** structure is held in the db->aHash hash table.
        12372  +**
        12373  +** The u.pHash field is used by the global built-ins.  The u.pDestructor
        12374  +** field is used by per-connection app-def functions.
 12265  12375   */
 12266  12376   struct FuncDef {
 12267         -  i16 nArg;            /* Number of arguments.  -1 means unlimited */
        12377  +  i8 nArg;             /* Number of arguments.  -1 means unlimited */
 12268  12378     u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
 12269  12379     void *pUserData;     /* User data parameter */
 12270  12380     FuncDef *pNext;      /* Next function with same name */
 12271  12381     void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
 12272  12382     void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
 12273         -  char *zName;         /* SQL name of the function. */
 12274         -  FuncDef *pHash;      /* Next with a different name but the same hash */
 12275         -  FuncDestructor *pDestructor;   /* Reference counted destructor function */
        12383  +  const char *zName;   /* SQL name of the function. */
        12384  +  union {
        12385  +    FuncDef *pHash;      /* Next with a different name but the same hash */
        12386  +    FuncDestructor *pDestructor;   /* Reference counted destructor function */
        12387  +  } u;
 12276  12388   };
 12277  12389   
 12278  12390   /*
 12279  12391   ** This structure encapsulates a user-function destructor callback (as
 12280  12392   ** configured using create_function_v2()) and a reference counter. When
 12281  12393   ** create_function_v2() is called to create a function with a destructor,
 12282         -** a single object of this type is allocated. FuncDestructor.nRef is set to 
        12394  +** a single object of this type is allocated. FuncDestructor.nRef is set to
 12283  12395   ** the number of FuncDef objects created (either 1 or 3, depending on whether
 12284  12396   ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
 12285  12397   ** member of each of the new FuncDef objects is set to point to the allocated
 12286  12398   ** FuncDestructor.
 12287  12399   **
 12288  12400   ** Thereafter, when one of the FuncDef objects is deleted, the reference
 12289  12401   ** count on this object is decremented. When it reaches 0, the destructor
................................................................................
 12317  12429                                       ** single query - might change over time */
 12318  12430   
 12319  12431   /*
 12320  12432   ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
 12321  12433   ** used to create the initializers for the FuncDef structures.
 12322  12434   **
 12323  12435   **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
 12324         -**     Used to create a scalar function definition of a function zName 
        12436  +**     Used to create a scalar function definition of a function zName
 12325  12437   **     implemented by C function xFunc that accepts nArg arguments. The
 12326  12438   **     value passed as iArg is cast to a (void*) and made available
 12327         -**     as the user-data (sqlite3_user_data()) for the function. If 
        12439  +**     as the user-data (sqlite3_user_data()) for the function. If
 12328  12440   **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
 12329  12441   **
 12330  12442   **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
 12331  12443   **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
 12332  12444   **
 12333  12445   **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
 12334  12446   **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
................................................................................
 12339  12451   **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
 12340  12452   **     Used to create an aggregate function definition implemented by
 12341  12453   **     the C functions xStep and xFinal. The first four parameters
 12342  12454   **     are interpreted in the same way as the first 4 parameters to
 12343  12455   **     FUNCTION().
 12344  12456   **
 12345  12457   **   LIKEFUNC(zName, nArg, pArg, flags)
 12346         -**     Used to create a scalar function definition of a function zName 
 12347         -**     that accepts nArg arguments and is implemented by a call to C 
        12458  +**     Used to create a scalar function definition of a function zName
        12459  +**     that accepts nArg arguments and is implemented by a call to C
 12348  12460   **     function likeFunc. Argument pArg is cast to a (void *) and made
 12349  12461   **     available as the function user-data (sqlite3_user_data()). The
 12350  12462   **     FuncDef.flags variable is set to the value passed as the flags
 12351  12463   **     parameter.
 12352  12464   */
 12353  12465   #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
 12354  12466     {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 12355         -   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, 0, 0}
        12467  +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 12356  12468   #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 12357  12469     {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 12358         -   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, 0, 0}
        12470  +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 12359  12471   #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 12360  12472     {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 12361         -   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, 0, 0}
        12473  +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 12362  12474   #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
 12363  12475     {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
 12364         -   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, 0, 0}
        12476  +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 12365  12477   #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
 12366  12478     {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 12367         -   pArg, 0, xFunc, 0, #zName, 0, 0}
        12479  +   pArg, 0, xFunc, 0, #zName, }
 12368  12480   #define LIKEFUNC(zName, nArg, arg, flags) \
 12369  12481     {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
 12370         -   (void *)arg, 0, likeFunc, 0, #zName, 0, 0}
        12482  +   (void *)arg, 0, likeFunc, 0, #zName, {0} }
 12371  12483   #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
 12372  12484     {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
 12373         -   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName,0,0}
        12485  +   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
 12374  12486   #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
 12375  12487     {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
 12376         -   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName,0,0}
        12488  +   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
 12377  12489   
 12378  12490   /*
 12379  12491   ** All current savepoints are stored in a linked list starting at
 12380  12492   ** sqlite3.pSavepoint. The first element in the list is the most recently
 12381  12493   ** opened savepoint. Savepoints are added to the list by the vdbe
 12382  12494   ** OP_Savepoint instruction.
 12383  12495   */
................................................................................
 12411  12523   };
 12412  12524   
 12413  12525   /*
 12414  12526   ** information about each column of an SQL table is held in an instance
 12415  12527   ** of this structure.
 12416  12528   */
 12417  12529   struct Column {
 12418         -  char *zName;     /* Name of this column */
        12530  +  char *zName;     /* Name of this column, \000, then the type */
 12419  12531     Expr *pDflt;     /* Default value of this column */
 12420         -  char *zDflt;     /* Original text of the default value */
 12421         -  char *zType;     /* Data type for this column */
 12422  12532     char *zColl;     /* Collating sequence.  If NULL, use the default */
 12423  12533     u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
 12424  12534     char affinity;   /* One of the SQLITE_AFF_... values */
 12425  12535     u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
 12426  12536     u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
 12427  12537   };
 12428  12538   
................................................................................
 12456  12566   #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
 12457  12567   
 12458  12568   /*
 12459  12569   ** Column affinity types.
 12460  12570   **
 12461  12571   ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
 12462  12572   ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
 12463         -** the speed a little by numbering the values consecutively.  
        12573  +** the speed a little by numbering the values consecutively.
 12464  12574   **
 12465  12575   ** But rather than start with 0 or 1, we begin with 'A'.  That way,
 12466  12576   ** when multiple affinity types are concatenated into a string and
 12467  12577   ** used as the P4 operand, they will be more readable.
 12468  12578   **
 12469  12579   ** Note also that the numeric types are grouped together so that testing
 12470  12580   ** for a numeric type is a single comparison.  And the BLOB type is first.
................................................................................
 12475  12585   #define SQLITE_AFF_INTEGER  'D'
 12476  12586   #define SQLITE_AFF_REAL     'E'
 12477  12587   
 12478  12588   #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
 12479  12589   
 12480  12590   /*
 12481  12591   ** The SQLITE_AFF_MASK values masks off the significant bits of an
 12482         -** affinity value. 
        12592  +** affinity value.
 12483  12593   */
 12484  12594   #define SQLITE_AFF_MASK     0x47
 12485  12595   
 12486  12596   /*
 12487  12597   ** Additional bit values that can be ORed with an affinity without
 12488  12598   ** changing the affinity.
 12489  12599   **
................................................................................
 12495  12605   #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
 12496  12606   #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
 12497  12607   #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
 12498  12608   #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
 12499  12609   
 12500  12610   /*
 12501  12611   ** An object of this type is created for each virtual table present in
 12502         -** the database schema. 
        12612  +** the database schema.
 12503  12613   **
 12504  12614   ** If the database schema is shared, then there is one instance of this
 12505  12615   ** structure for each database connection (sqlite3*) that uses the shared
 12506  12616   ** schema. This is because each database connection requires its own unique
 12507         -** instance of the sqlite3_vtab* handle used to access the virtual table 
 12508         -** implementation. sqlite3_vtab* handles can not be shared between 
 12509         -** database connections, even when the rest of the in-memory database 
        12617  +** instance of the sqlite3_vtab* handle used to access the virtual table
        12618  +** implementation. sqlite3_vtab* handles can not be shared between
        12619  +** database connections, even when the rest of the in-memory database
 12510  12620   ** schema is shared, as the implementation often stores the database
 12511  12621   ** connection handle passed to it via the xConnect() or xCreate() method
 12512  12622   ** during initialization internally. This database connection handle may
 12513         -** then be used by the virtual table implementation to access real tables 
 12514         -** within the database. So that they appear as part of the callers 
 12515         -** transaction, these accesses need to be made via the same database 
        12623  +** then be used by the virtual table implementation to access real tables
        12624  +** within the database. So that they appear as part of the callers
        12625  +** transaction, these accesses need to be made via the same database
 12516  12626   ** connection as that used to execute SQL operations on the virtual table.
 12517  12627   **
 12518  12628   ** All VTable objects that correspond to a single table in a shared
 12519  12629   ** database schema are initially stored in a linked-list pointed to by
 12520  12630   ** the Table.pVTable member variable of the corresponding Table object.
 12521  12631   ** When an sqlite3_prepare() operation is required to access the virtual
 12522  12632   ** table, it searches the list for the VTable that corresponds to the
 12523  12633   ** database connection doing the preparing so as to use the correct
 12524  12634   ** sqlite3_vtab* handle in the compiled query.
 12525  12635   **
 12526  12636   ** When an in-memory Table object is deleted (for example when the
 12527         -** schema is being reloaded for some reason), the VTable objects are not 
 12528         -** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
        12637  +** schema is being reloaded for some reason), the VTable objects are not
        12638  +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
 12529  12639   ** immediately. Instead, they are moved from the Table.pVTable list to
 12530  12640   ** another linked list headed by the sqlite3.pDisconnect member of the
 12531         -** corresponding sqlite3 structure. They are then deleted/xDisconnected 
        12641  +** corresponding sqlite3 structure. They are then deleted/xDisconnected
 12532  12642   ** next time a statement is prepared using said sqlite3*. This is done
 12533  12643   ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
 12534  12644   ** Refer to comments above function sqlite3VtabUnlockList() for an
 12535  12645   ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
 12536  12646   ** list without holding the corresponding sqlite3.mutex mutex.
 12537  12647   **
 12538         -** The memory for objects of this type is always allocated by 
 12539         -** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
        12648  +** The memory for objects of this type is always allocated by
        12649  +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
 12540  12650   ** the first argument.
 12541  12651   */
 12542  12652   struct VTable {
 12543  12653     sqlite3 *db;              /* Database connection associated with this table */
 12544  12654     Module *pMod;             /* Pointer to module implementation */
 12545  12655     sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
 12546  12656     int nRef;                 /* Number of pointers to this structure */
................................................................................
 12700  12810   **
 12701  12811   ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
 12702  12812   ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
 12703  12813   ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
 12704  12814   ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
 12705  12815   ** referenced table row is propagated into the row that holds the
 12706  12816   ** foreign key.
 12707         -** 
        12817  +**
 12708  12818   ** The following symbolic values are used to record which type
 12709  12819   ** of action to take.
 12710  12820   */
 12711  12821   #define OE_None     0   /* There is no constraint to check */
 12712  12822   #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
 12713  12823   #define OE_Abort    2   /* Back out changes but do no rollback transaction */
 12714  12824   #define OE_Fail     3   /* Stop the operation but leave all prior changes */
................................................................................
 12721  12831   #define OE_Cascade  9   /* Cascade the changes */
 12722  12832   
 12723  12833   #define OE_Default  10  /* Do whatever the default action is */
 12724  12834   
 12725  12835   
 12726  12836   /*
 12727  12837   ** An instance of the following structure is passed as the first
 12728         -** argument to sqlite3VdbeKeyCompare and is used to control the 
        12838  +** argument to sqlite3VdbeKeyCompare and is used to control the
 12729  12839   ** comparison of the two index keys.
 12730  12840   **
 12731  12841   ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
 12732  12842   ** are nField slots for the columns of an index then one extra slot
 12733  12843   ** for the rowid at the end.
 12734  12844   */
 12735  12845   struct KeyInfo {
................................................................................
 12762  12872   ** or greater than a key in the btree, respectively.  These are normally
 12763  12873   ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
 12764  12874   ** is in DESC order.
 12765  12875   **
 12766  12876   ** The key comparison functions actually return default_rc when they find
 12767  12877   ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
 12768  12878   ** multiple entries in the b-tree with the same key (when only looking
 12769         -** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to 
        12879  +** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
 12770  12880   ** cause the search to find the last match, or +1 to cause the search to
 12771  12881   ** find the first match.
 12772  12882   **
 12773  12883   ** The key comparison functions will set eqSeen to true if they ever
 12774  12884   ** get and equal results when comparing this structure to a b-tree record.
 12775  12885   ** When default_rc!=0, the search might end up on the record immediately
 12776  12886   ** before the first match or immediately after the last match.  The
................................................................................
 12799  12909   **
 12800  12910   **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
 12801  12911   **     CREATE INDEX Ex2 ON Ex1(c3,c1);
 12802  12912   **
 12803  12913   ** In the Table structure describing Ex1, nCol==3 because there are
 12804  12914   ** three columns in the table.  In the Index structure describing
 12805  12915   ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
 12806         -** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
        12916  +** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
 12807  12917   ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
 12808  12918   ** The second column to be indexed (c1) has an index of 0 in
 12809  12919   ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
 12810  12920   **
 12811  12921   ** The Index.onError field determines whether or not the indexed columns
 12812  12922   ** must be unique and what to do if they are not.  When Index.onError=OE_None,
 12813  12923   ** it means this is not a unique index.  Otherwise it is a unique index
 12814         -** and the value of Index.onError indicate the which conflict resolution 
        12924  +** and the value of Index.onError indicate the which conflict resolution
 12815  12925   ** algorithm to employ whenever an attempt is made to insert a non-unique
 12816  12926   ** element.
 12817  12927   **
 12818  12928   ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
 12819  12929   ** generate VDBE code (as opposed to parsing one read from an sqlite_master
 12820  12930   ** table as part of parsing an existing database schema), transient instances
 12821  12931   ** of this structure may be created. In this case the Index.tnum variable is
................................................................................
 12872  12982   /* The Index.aiColumn[] values are normally positive integer.  But
 12873  12983   ** there are some negative values that have special meaning:
 12874  12984   */
 12875  12985   #define XN_ROWID     (-1)     /* Indexed column is the rowid */
 12876  12986   #define XN_EXPR      (-2)     /* Indexed column is an expression */
 12877  12987   
 12878  12988   /*
 12879         -** Each sample stored in the sqlite_stat3 table is represented in memory 
        12989  +** Each sample stored in the sqlite_stat3 table is represented in memory
 12880  12990   ** using a structure of this type.  See documentation at the top of the
 12881  12991   ** analyze.c source file for additional information.
 12882  12992   */
 12883  12993   struct IndexSample {
 12884  12994     void *p;          /* Pointer to sampled record */
 12885  12995     int n;            /* Size of record in bytes */
 12886  12996     tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
................................................................................
 12967  13077   **
 12968  13078   ** Expr.op is the opcode. The integer parser token codes are reused
 12969  13079   ** as opcodes here. For example, the parser defines TK_GE to be an integer
 12970  13080   ** code representing the ">=" operator. This same integer code is reused
 12971  13081   ** to represent the greater-than-or-equal-to operator in the expression
 12972  13082   ** tree.
 12973  13083   **
 12974         -** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
        13084  +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
 12975  13085   ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
 12976         -** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
        13086  +** the expression is a variable (TK_VARIABLE), then Expr.token contains the
 12977  13087   ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
 12978  13088   ** then Expr.token contains the name of the function.
 12979  13089   **
 12980  13090   ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
 12981  13091   ** binary operator. Either or both may be NULL.
 12982  13092   **
 12983  13093   ** Expr.x.pList is a list of arguments if the expression is an SQL function,
 12984  13094   ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
 12985  13095   ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
 12986  13096   ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
 12987         -** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
        13097  +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
 12988  13098   ** valid.
 12989  13099   **
 12990  13100   ** An expression of the form ID or ID.ID refers to a column in a table.
 12991  13101   ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
 12992  13102   ** the integer cursor number of a VDBE cursor pointing to that table and
 12993  13103   ** Expr.iColumn is the column number for the specific column.  If the
 12994  13104   ** expression is used as a result in an aggregate SELECT, then the
 12995  13105   ** value is also stored in the Expr.iAgg column in the aggregate so that
 12996  13106   ** it can be accessed after all aggregates are computed.
 12997  13107   **
 12998         -** If the expression is an unbound variable marker (a question mark 
 12999         -** character '?' in the original SQL) then the Expr.iTable holds the index 
        13108  +** If the expression is an unbound variable marker (a question mark
        13109  +** character '?' in the original SQL) then the Expr.iTable holds the index
 13000  13110   ** number for that variable.
 13001  13111   **
 13002  13112   ** If the expression is a subquery then Expr.iColumn holds an integer
 13003  13113   ** register number containing the result of the subquery.  If the
 13004  13114   ** subquery gives a constant result, then iTable is -1.  If the subquery
 13005  13115   ** gives a different answer at different times during statement processing
 13006  13116   ** then iTable is the address of a subroutine that computes the subquery.
................................................................................
 13031  13141     union {
 13032  13142       char *zToken;          /* Token value. Zero terminated and dequoted */
 13033  13143       int iValue;            /* Non-negative integer value if EP_IntValue */
 13034  13144     } u;
 13035  13145   
 13036  13146     /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
 13037  13147     ** space is allocated for the fields below this point. An attempt to
 13038         -  ** access them will result in a segfault or malfunction. 
        13148  +  ** access them will result in a segfault or malfunction.
 13039  13149     *********************************************************************/
 13040  13150   
 13041  13151     Expr *pLeft;           /* Left subnode */
 13042  13152     Expr *pRight;          /* Right subnode */
 13043  13153     union {
 13044  13154       ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
 13045  13155       Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
................................................................................
 13097  13207   
 13098  13208   /*
 13099  13209   ** Combinations of two or more EP_* flags
 13100  13210   */
 13101  13211   #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
 13102  13212   
 13103  13213   /*
 13104         -** These macros can be used to test, set, or clear bits in the 
        13214  +** These macros can be used to test, set, or clear bits in the
 13105  13215   ** Expr.flags field.
 13106  13216   */
 13107  13217   #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
 13108  13218   #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
 13109  13219   #define ExprSetProperty(E,P)     (E)->flags|=(P)
 13110  13220   #define ExprClearProperty(E,P)   (E)->flags&=~(P)
 13111  13221   
................................................................................
 13116  13226   #ifdef SQLITE_DEBUG
 13117  13227   # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
 13118  13228   #else
 13119  13229   # define ExprSetVVAProperty(E,P)
 13120  13230   #endif
 13121  13231   
 13122  13232   /*
 13123         -** Macros to determine the number of bytes required by a normal Expr 
 13124         -** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
        13233  +** Macros to determine the number of bytes required by a normal Expr
        13234  +** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
 13125  13235   ** and an Expr struct with the EP_TokenOnly flag set.
 13126  13236   */
 13127  13237   #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
 13128  13238   #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
 13129  13239   #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
 13130  13240   
 13131  13241   /*
 13132         -** Flags passed to the sqlite3ExprDup() function. See the header comment 
        13242  +** Flags passed to the sqlite3ExprDup() function. See the header comment
 13133  13243   ** above sqlite3ExprDup() for details.
 13134  13244   */
 13135  13245   #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
 13136  13246   
 13137  13247   /*
 13138  13248   ** A list of expressions.  Each expression may optionally have a
 13139  13249   ** name.  An expr/name combination can be used in several ways, such
................................................................................
 13207  13317   /*
 13208  13318   ** The bitmask datatype defined below is used for various optimizations.
 13209  13319   **
 13210  13320   ** Changing this from a 64-bit to a 32-bit type limits the number of
 13211  13321   ** tables in a join to 32 instead of 64.  But it also reduces the size
 13212  13322   ** of the library by 738 bytes on ix86.
 13213  13323   */
 13214         -typedef u64 Bitmask;
        13324  +#ifdef SQLITE_BITMASK_TYPE
        13325  +  typedef SQLITE_BITMASK_TYPE Bitmask;
        13326  +#else
        13327  +  typedef u64 Bitmask;
        13328  +#endif
 13215  13329   
 13216  13330   /*
 13217  13331   ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
 13218  13332   */
 13219  13333   #define BMS  ((int)(sizeof(Bitmask)*8))
 13220  13334   
 13221  13335   /*
 13222  13336   ** A bit in a Bitmask
 13223  13337   */
 13224  13338   #define MASKBIT(n)   (((Bitmask)1)<<(n))
 13225  13339   #define MASKBIT32(n) (((unsigned int)1)<<(n))
        13340  +#define ALLBITS      ((Bitmask)-1)
 13226  13341   
 13227  13342   /*
 13228  13343   ** The following structure describes the FROM clause of a SELECT statement.
 13229  13344   ** Each table or subquery in the FROM clause is a separate element of
 13230  13345   ** the SrcList.a[] array.
 13231  13346   **
 13232  13347   ** With the addition of multiple database support, the following structure
................................................................................
 13307  13422   #define WHERE_NO_AUTOINDEX     0x0080 /* Disallow automatic indexes */
 13308  13423   #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
 13309  13424   #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
 13310  13425   #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
 13311  13426   #define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
 13312  13427   #define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
 13313  13428   #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
        13429  +#define WHERE_USE_LIMIT        0x4000 /* There is a constant LIMIT clause */
 13314  13430   
 13315  13431   /* Allowed return values from sqlite3WhereIsDistinct()
 13316  13432   */
 13317  13433   #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
 13318  13434   #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
 13319  13435   #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
 13320  13436   #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
................................................................................
 13324  13440   ** names.  The context consists of a list of tables (the pSrcList) field and
 13325  13441   ** a list of named expression (pEList).  The named expression list may
 13326  13442   ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
 13327  13443   ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
 13328  13444   ** pEList corresponds to the result set of a SELECT and is NULL for
 13329  13445   ** other statements.
 13330  13446   **
 13331         -** NameContexts can be nested.  When resolving names, the inner-most 
        13447  +** NameContexts can be nested.  When resolving names, the inner-most
 13332  13448   ** context is searched first.  If no match is found, the next outer
 13333  13449   ** context is checked.  If there is still no match, the next context
 13334  13450   ** is checked.  This process continues until either a match is found
 13335  13451   ** or all contexts are check.  When a match is found, the nRef member of
 13336         -** the context containing the match is incremented. 
        13452  +** the context containing the match is incremented.
 13337  13453   **
 13338  13454   ** Each subquery gets a new NameContext.  The pNext field points to the
 13339  13455   ** NameContext in the parent query.  Thus the process of scanning the
 13340  13456   ** NameContext list corresponds to searching through successively outer
 13341  13457   ** subqueries looking for a match.
 13342  13458   */
 13343  13459   struct NameContext {
................................................................................
 13352  13468   };
 13353  13469   
 13354  13470   /*
 13355  13471   ** Allowed values for the NameContext, ncFlags field.
 13356  13472   **
 13357  13473   ** Note:  NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
 13358  13474   ** SQLITE_FUNC_MINMAX.
 13359         -** 
        13475  +**
 13360  13476   */
 13361  13477   #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
 13362  13478   #define NC_HasAgg    0x0002  /* One or more aggregate functions seen */
 13363  13479   #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
 13364  13480   #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
 13365  13481   #define NC_PartIdx   0x0010  /* True if resolving a partial index WHERE */
 13366  13482   #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
................................................................................
 13385  13501   ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
 13386  13502   ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
 13387  13503   ** sequences for the ORDER BY clause.
 13388  13504   */
 13389  13505   struct Select {
 13390  13506     ExprList *pEList;      /* The fields of the result */
 13391  13507     u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
 13392         -  u16 selFlags;          /* Various SF_* values */
        13508  +  LogEst nSelectRow;     /* Estimated number of result rows */
        13509  +  u32 selFlags;          /* Various SF_* values */
 13393  13510     int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
 13394  13511   #if SELECTTRACE_ENABLED
 13395  13512     char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
 13396  13513   #endif
 13397  13514     int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
 13398         -  u64 nSelectRow;        /* Estimated number of result rows */
 13399  13515     SrcList *pSrc;         /* The FROM clause */
 13400  13516     Expr *pWhere;          /* The WHERE clause */
 13401  13517     ExprList *pGroupBy;    /* The GROUP BY clause */
 13402  13518     Expr *pHaving;         /* The HAVING clause */
 13403  13519     ExprList *pOrderBy;    /* The ORDER BY clause */
 13404  13520     Select *pPrior;        /* Prior select in a compound select statement */
 13405  13521     Select *pNext;         /* Next select to the left in a compound */
................................................................................
 13408  13524     With *pWith;           /* WITH clause attached to this select. Or NULL. */
 13409  13525   };
 13410  13526   
 13411  13527   /*
 13412  13528   ** Allowed values for Select.selFlags.  The "SF" prefix stands for
 13413  13529   ** "Select Flag".
 13414  13530   */
 13415         -#define SF_Distinct        0x0001  /* Output should be DISTINCT */
 13416         -#define SF_All             0x0002  /* Includes the ALL keyword */
 13417         -#define SF_Resolved        0x0004  /* Identifiers have been resolved */
 13418         -#define SF_Aggregate       0x0008  /* Contains aggregate functions */
 13419         -#define SF_UsesEphemeral   0x0010  /* Uses the OpenEphemeral opcode */
 13420         -#define SF_Expanded        0x0020  /* sqlite3SelectExpand() called on this */
 13421         -#define SF_HasTypeInfo     0x0040  /* FROM subqueries have Table metadata */
 13422         -#define SF_Compound        0x0080  /* Part of a compound query */
 13423         -#define SF_Values          0x0100  /* Synthesized from VALUES clause */
 13424         -#define SF_MultiValue      0x0200  /* Single VALUES term with multiple rows */
 13425         -#define SF_NestedFrom      0x0400  /* Part of a parenthesized FROM clause */
 13426         -#define SF_MaybeConvert    0x0800  /* Need convertCompoundSelectToSubquery() */
 13427         -#define SF_MinMaxAgg       0x1000  /* Aggregate containing min() or max() */
 13428         -#define SF_Recursive       0x2000  /* The recursive part of a recursive CTE */
 13429         -#define SF_Converted       0x4000  /* By convertCompoundSelectToSubquery() */
 13430         -#define SF_IncludeHidden   0x8000  /* Include hidden columns in output */
        13531  +#define SF_Distinct       0x00001  /* Output should be DISTINCT */
        13532  +#define SF_All            0x00002  /* Includes the ALL keyword */
        13533  +#define SF_Resolved       0x00004  /* Identifiers have been resolved */
        13534  +#define SF_Aggregate      0x00008  /* Contains aggregate functions */
        13535  +#define SF_UsesEphemeral  0x00010  /* Uses the OpenEphemeral opcode */
        13536  +#define SF_Expanded       0x00020  /* sqlite3SelectExpand() called on this */
        13537  +#define SF_HasTypeInfo    0x00040  /* FROM subqueries have Table metadata */
        13538  +#define SF_Compound       0x00080  /* Part of a compound query */
        13539  +#define SF_Values         0x00100  /* Synthesized from VALUES clause */
        13540  +#define SF_MultiValue     0x00200  /* Single VALUES term with multiple rows */
        13541  +#define SF_NestedFrom     0x00400  /* Part of a parenthesized FROM clause */
        13542  +#define SF_MaybeConvert   0x00800  /* Need convertCompoundSelectToSubquery() */
        13543  +#define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
        13544  +#define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
        13545  +#define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
        13546  +#define SF_Converted      0x08000  /* By convertCompoundSelectToSubquery() */
        13547  +#define SF_IncludeHidden  0x10000  /* Include hidden columns in output */
 13431  13548   
 13432  13549   
 13433  13550   /*
 13434  13551   ** The results of a SELECT can be distributed in several ways, as defined
 13435  13552   ** by one of the following macros.  The "SRT" prefix means "SELECT Result
 13436  13553   ** Type".
 13437  13554   **
 13438         -**     SRT_Union       Store results as a key in a temporary index 
        13555  +**     SRT_Union       Store results as a key in a temporary index
 13439  13556   **                     identified by pDest->iSDParm.
 13440  13557   **
 13441  13558   **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
 13442  13559   **
 13443  13560   **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
 13444  13561   **                     set is not empty.
 13445  13562   **
................................................................................
 13455  13572   **
 13456  13573   **     SRT_Mem         Only valid if the result is a single column.
 13457  13574   **                     Store the first column of the first result row
 13458  13575   **                     in register pDest->iSDParm then abandon the rest
 13459  13576   **                     of the query.  This destination implies "LIMIT 1".
 13460  13577   **
 13461  13578   **     SRT_Set         The result must be a single column.  Store each
 13462         -**                     row of result as the key in table pDest->iSDParm. 
        13579  +**                     row of result as the key in table pDest->iSDParm.
 13463  13580   **                     Apply the affinity pDest->affSdst before storing
 13464  13581   **                     results.  Used to implement "IN (SELECT ...)".
 13465  13582   **
 13466  13583   **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
 13467  13584   **                     the result there. The cursor is left open after
 13468  13585   **                     returning.  This is like SRT_Table except that
 13469  13586   **                     this destination uses OP_OpenEphemeral to create
................................................................................
 13523  13640     int iSDParm;         /* A parameter used by the eDest disposal method */
 13524  13641     int iSdst;           /* Base register where results are written */
 13525  13642     int nSdst;           /* Number of registers allocated */
 13526  13643     ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
 13527  13644   };
 13528  13645   
 13529  13646   /*
 13530         -** During code generation of statements that do inserts into AUTOINCREMENT 
        13647  +** During code generation of statements that do inserts into AUTOINCREMENT
 13531  13648   ** tables, the following information is attached to the Table.u.autoInc.p
 13532  13649   ** pointer of each autoincrement table to record some side information that
 13533  13650   ** the code generator needs.  We have to keep per-table autoincrement
 13534  13651   ** information in case inserts are done within triggers.  Triggers do not
 13535  13652   ** normally coordinate their activities, but we do need to coordinate the
 13536  13653   ** loading and saving of autoincrement information.
 13537  13654   */
................................................................................
 13546  13663   ** Size of the column cache
 13547  13664   */
 13548  13665   #ifndef SQLITE_N_COLCACHE
 13549  13666   # define SQLITE_N_COLCACHE 10
 13550  13667   #endif
 13551  13668   
 13552  13669   /*
 13553         -** At least one instance of the following structure is created for each 
        13670  +** At least one instance of the following structure is created for each
 13554  13671   ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
 13555  13672   ** statement. All such objects are stored in the linked list headed at
 13556  13673   ** Parse.pTriggerPrg and deleted once statement compilation has been
 13557  13674   ** completed.
 13558  13675   **
 13559  13676   ** A Vdbe sub-program that implements the body and WHEN clause of trigger
 13560  13677   ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
 13561  13678   ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
 13562  13679   ** The Parse.pTriggerPrg list never contains two entries with the same
 13563  13680   ** values for both pTrigger and orconf.
 13564  13681   **
 13565  13682   ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
 13566         -** accessed (or set to 0 for triggers fired as a result of INSERT 
        13683  +** accessed (or set to 0 for triggers fired as a result of INSERT
 13567  13684   ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
 13568  13685   ** a mask of new.* columns used by the program.
 13569  13686   */
 13570  13687   struct TriggerPrg {
 13571  13688     Trigger *pTrigger;      /* Trigger this program was coded from */
 13572  13689     TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
 13573  13690     SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
................................................................................
 13600  13717   ** carry around information that is global to the entire parse.
 13601  13718   **
 13602  13719   ** The structure is divided into two parts.  When the parser and code
 13603  13720   ** generate call themselves recursively, the first part of the structure
 13604  13721   ** is constant but the second part is reset at the beginning and end of
 13605  13722   ** each recursion.
 13606  13723   **
 13607         -** The nTableLock and aTableLock variables are only used if the shared-cache 
        13724  +** The nTableLock and aTableLock variables are only used if the shared-cache
 13608  13725   ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
 13609  13726   ** used to store the set of table-locks required by the statement being
 13610  13727   ** compiled. Function sqlite3TableLock() is used to add entries to the
 13611  13728   ** list.
 13612  13729   */
 13613  13730   struct Parse {
 13614  13731     sqlite3 *db;         /* The main database structure */
................................................................................
 13753  13870   #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
 13754  13871   #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
 13755  13872   #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete: keep cursor position */
 13756  13873   #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
 13757  13874   
 13758  13875   /*
 13759  13876    * Each trigger present in the database schema is stored as an instance of
 13760         - * struct Trigger. 
        13877  + * struct Trigger.
 13761  13878    *
 13762  13879    * Pointers to instances of struct Trigger are stored in two ways.
 13763         - * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
        13880  + * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
 13764  13881    *    database). This allows Trigger structures to be retrieved by name.
 13765  13882    * 2. All triggers associated with a single table form a linked list, using the
 13766  13883    *    pNext member of struct Trigger. A pointer to the first element of the
 13767  13884    *    linked list is stored as the "pTrigger" member of the associated
 13768  13885    *    struct Table.
 13769  13886    *
 13770  13887    * The "step_list" member points to the first element of a linked list
................................................................................
 13782  13899     Schema *pTabSchema;     /* Schema containing the table */
 13783  13900     TriggerStep *step_list; /* Link list of trigger program steps             */
 13784  13901     Trigger *pNext;         /* Next trigger associated with the table */
 13785  13902   };
 13786  13903   
 13787  13904   /*
 13788  13905   ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
 13789         -** determine which. 
        13906  +** determine which.
 13790  13907   **
 13791  13908   ** If there are multiple triggers, you might of some BEFORE and some AFTER.
 13792  13909   ** In that cases, the constants below can be ORed together.
 13793  13910   */
 13794  13911   #define TRIGGER_BEFORE  1
 13795  13912   #define TRIGGER_AFTER   2
 13796  13913   
 13797  13914   /*
 13798  13915    * An instance of struct TriggerStep is used to store a single SQL statement
 13799         - * that is a part of a trigger-program. 
        13916  + * that is a part of a trigger-program.
 13800  13917    *
 13801  13918    * Instances of struct TriggerStep are stored in a singly linked list (linked
 13802         - * using the "pNext" member) referenced by the "step_list" member of the 
        13919  + * using the "pNext" member) referenced by the "step_list" member of the
 13803  13920    * associated struct Trigger instance. The first element of the linked list is
 13804  13921    * the first step of the trigger-program.
 13805         - * 
        13922  + *
 13806  13923    * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 13807         - * "SELECT" statement. The meanings of the other members is determined by the 
        13924  + * "SELECT" statement. The meanings of the other members is determined by the
 13808  13925    * value of "op" as follows:
 13809  13926    *
 13810  13927    * (op == TK_INSERT)
 13811  13928    * orconf    -> stores the ON CONFLICT algorithm
 13812  13929    * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 13813  13930    *              this stores a pointer to the SELECT statement. Otherwise NULL.
 13814  13931    * zTarget   -> Dequoted name of the table to insert into.
 13815  13932    * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 13816  13933    *              this stores values to be inserted. Otherwise NULL.
 13817         - * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
        13934  + * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
 13818  13935    *              statement, then this stores the column-names to be
 13819  13936    *              inserted into.
 13820  13937    *
 13821  13938    * (op == TK_DELETE)
 13822  13939    * zTarget   -> Dequoted name of the table to delete from.
 13823  13940    * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 13824  13941    *              Otherwise NULL.
 13825         - * 
        13942  + *
 13826  13943    * (op == TK_UPDATE)
 13827  13944    * zTarget   -> Dequoted name of the table to update.
 13828  13945    * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 13829  13946    *              Otherwise NULL.
 13830  13947    * pExprList -> A list of the columns to update and the expressions to update
 13831  13948    *              them to. See sqlite3Update() documentation of "pChanges"
 13832  13949    *              argument.
 13833         - * 
        13950  + *
 13834  13951    */
 13835  13952   struct TriggerStep {
 13836  13953     u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
 13837  13954     u8 orconf;           /* OE_Rollback etc. */
 13838  13955     Trigger *pTrig;      /* The trigger that this step is a part of */
 13839  13956     Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
 13840  13957     char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
................................................................................
 13844  13961     TriggerStep *pNext;  /* Next in the link-list */
 13845  13962     TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
 13846  13963   };
 13847  13964   
 13848  13965   /*
 13849  13966   ** The following structure contains information used by the sqliteFix...
 13850  13967   ** routines as they walk the parse tree to make database references
 13851         -** explicit.  
        13968  +** explicit.
 13852  13969   */
 13853  13970   typedef struct DbFixer DbFixer;
 13854  13971   struct DbFixer {
 13855  13972     Parse *pParse;      /* The parsing context.  Error messages written here */
 13856  13973     Schema *pSchema;    /* Fix items to this schema */
 13857  13974     int bVarOnly;       /* Check for variable references only */
 13858  13975     const char *zDb;    /* Make sure all objects are contained in this database */
................................................................................
 13905  14022     int bFullMutex;                   /* True to enable full mutexing */
 13906  14023     int bOpenUri;                     /* True to interpret filenames as URIs */
 13907  14024     int bUseCis;                      /* Use covering indices for full-scans */
 13908  14025     int mxStrlen;                     /* Maximum string length */
 13909  14026     int neverCorrupt;                 /* Database is always well-formed */
 13910  14027     int szLookaside;                  /* Default lookaside buffer size */
 13911  14028     int nLookaside;                   /* Default lookaside buffer count */
        14029  +  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
 13912  14030     sqlite3_mem_methods m;            /* Low-level memory allocation interface */
 13913  14031     sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
 13914  14032     sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
 13915  14033     void *pHeap;                      /* Heap storage space */
 13916  14034     int nHeap;                        /* Size of pHeap[] */
 13917  14035     int mnReq, mxReq;                 /* Min and max heap requests sizes */
 13918  14036     sqlite3_int64 szMmap;             /* mmap() space per open file */
................................................................................
 14054  14172   */
 14055  14173   SQLITE_PRIVATE int sqlite3CorruptError(int);
 14056  14174   SQLITE_PRIVATE int sqlite3MisuseError(int);
 14057  14175   SQLITE_PRIVATE int sqlite3CantopenError(int);
 14058  14176   #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
 14059  14177   #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
 14060  14178   #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
        14179  +#ifdef SQLITE_DEBUG
        14180  +SQLITE_PRIVATE   int sqlite3NomemError(int);
        14181  +SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
        14182  +# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
        14183  +# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
        14184  +#else
        14185  +# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
        14186  +# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
        14187  +#endif
 14061  14188   
 14062  14189   /*
 14063  14190   ** FTS3 and FTS4 both require virtual table support
 14064  14191   */
 14065  14192   #if defined(SQLITE_OMIT_VIRTUALTABLE)
 14066  14193   # undef SQLITE_ENABLE_FTS3
 14067  14194   # undef SQLITE_ENABLE_FTS4
................................................................................
 14110  14237   #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 14111  14238   SQLITE_PRIVATE int sqlite3IsIdChar(u8);
 14112  14239   #endif
 14113  14240   
 14114  14241   /*
 14115  14242   ** Internal function prototypes
 14116  14243   */
 14117         -#define sqlite3StrICmp sqlite3_stricmp
        14244  +SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
 14118  14245   SQLITE_PRIVATE int sqlite3Strlen30(const char*);
        14246  +SQLITE_PRIVATE const char *sqlite3StrNext(const char*);
 14119  14247   #define sqlite3StrNICmp sqlite3_strnicmp
 14120  14248   
 14121  14249   SQLITE_PRIVATE int sqlite3MallocInit(void);
 14122  14250   SQLITE_PRIVATE void sqlite3MallocEnd(void);
 14123  14251   SQLITE_PRIVATE void *sqlite3Malloc(u64);
 14124  14252   SQLITE_PRIVATE void *sqlite3MallocZero(u64);
 14125  14253   SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
................................................................................
 14150  14278   **
 14151  14279   ** The alloca() routine never returns NULL.  This will cause code paths
 14152  14280   ** that deal with sqlite3StackAlloc() failures to be unreachable.
 14153  14281   */
 14154  14282   #ifdef SQLITE_USE_ALLOCA
 14155  14283   # define sqlite3StackAllocRaw(D,N)   alloca(N)
 14156  14284   # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
 14157         -# define sqlite3StackFree(D,P)       
        14285  +# define sqlite3StackFree(D,P)
 14158  14286   #else
 14159  14287   # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
 14160  14288   # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
 14161  14289   # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
 14162  14290   #endif
 14163  14291   
 14164  14292   #ifdef SQLITE_ENABLE_MEMSYS3
................................................................................
 14234  14362   SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
 14235  14363   SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
 14236  14364   SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
 14237  14365   SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
 14238  14366   SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
 14239  14367   SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
 14240  14368   SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
        14369  +#ifdef SQLITE_DEBUG
        14370  +SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
        14371  +#endif
 14241  14372   SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
 14242  14373   SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
 14243  14374   SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
 14244  14375   SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
 14245  14376   SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
 14246  14377   SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
 14247  14378   SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
................................................................................
 14267  14398   SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
 14268  14399   SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 14269  14400   #if SQLITE_ENABLE_HIDDEN_COLUMNS
 14270  14401   SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
 14271  14402   #else
 14272  14403   # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
 14273  14404   #endif
 14274         -SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
        14405  +SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
 14275  14406   SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 14276  14407   SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
 14277  14408   SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
 14278         -SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
 14279  14409   SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
 14280  14410   SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
 14281  14411   SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
 14282  14412   SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
 14283  14413                       sqlite3_vfs**,char**,char **);
 14284  14414   SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
 14285  14415   SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
................................................................................
 14345  14475   SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
 14346  14476   SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
 14347  14477   SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
 14348  14478                             Expr*, int, int);
 14349  14479   SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
 14350  14480   SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
 14351  14481   SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
 14352         -                         Expr*,ExprList*,u16,Expr*,Expr*);
        14482  +                         Expr*,ExprList*,u32,Expr*,Expr*);
 14353  14483   SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
 14354  14484   SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
 14355  14485   SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
 14356  14486   SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
 14357  14487   #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 14358  14488   SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
 14359  14489   #endif
 14360  14490   SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
 14361  14491   SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
 14362  14492   SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
 14363  14493   SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 14364         -SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
        14494  +SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
 14365  14495   SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
 14366  14496   SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
 14367  14497   SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
 14368  14498   SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
 14369  14499   SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
 14370  14500   SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
 14371  14501   #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
................................................................................
 14457  14587   SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
 14458  14588   SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
 14459  14589   #if SELECTTRACE_ENABLED
 14460  14590   SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
 14461  14591   #else
 14462  14592   # define sqlite3SelectSetName(A,B)
 14463  14593   #endif
 14464         -SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
 14465         -SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
 14466         -SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
        14594  +SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
        14595  +SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
        14596  +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
 14467  14597   SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
 14468         -SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
        14598  +SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
 14469  14599   SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 14470  14600   SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
 14471  14601   SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
 14472  14602   
 14473  14603   #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 14474  14604   SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
 14475  14605   #endif
................................................................................
 14540  14670   SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 14541  14671   SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
 14542  14672   SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
 14543  14673   SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
 14544  14674   #ifndef SQLITE_OMIT_VIRTUALTABLE
 14545  14675   SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
 14546  14676   #endif
        14677  +#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
        14678  +    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
        14679  +    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 14547  14680   SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
        14681  +#endif
 14548  14682   
 14549  14683   /*
 14550  14684   ** Routines to read and write variable-length integers.  These used to
 14551  14685   ** be defined locally, but now we use the varint routines in the util.c
 14552  14686   ** file.
 14553  14687   */
 14554  14688   SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
................................................................................
 14575  14709   SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
 14576  14710   SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
 14577  14711   SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
 14578  14712   SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 14579  14713   SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
 14580  14714   SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
 14581  14715   SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
        14716  +SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
 14582  14717   SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
 14583  14718   SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
 14584  14719   SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
 14585  14720   
 14586  14721   #if defined(SQLITE_NEED_ERR_NAME)
 14587  14722   SQLITE_PRIVATE const char *sqlite3ErrName(int);
 14588  14723   #endif
................................................................................
 14607  14742   #else
 14608  14743   # define sqlite3FileSuffix3(X,Y)
 14609  14744   #endif
 14610  14745   SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
 14611  14746   
 14612  14747   SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
 14613  14748   SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
 14614         -SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
        14749  +SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
 14615  14750                           void(*)(void*));
 14616  14751   SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
 14617  14752   SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
 14618  14753   SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
 14619  14754   SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
 14620  14755   SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
 14621  14756   SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
................................................................................
 14622  14757   #ifndef SQLITE_AMALGAMATION
 14623  14758   SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
 14624  14759   SQLITE_PRIVATE const char sqlite3StrBINARY[];
 14625  14760   SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
 14626  14761   SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 14627  14762   SQLITE_PRIVATE const Token sqlite3IntTokens[];
 14628  14763   SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 14629         -SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
        14764  +SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 14630  14765   #ifndef SQLITE_OMIT_WSD
 14631  14766   SQLITE_PRIVATE int sqlite3PendingByte;
 14632  14767   #endif
 14633  14768   #endif
 14634  14769   SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
 14635  14770   SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 14636  14771   SQLITE_PRIVATE void sqlite3AlterFunctions(void);
................................................................................
 14667  14802   SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
 14668  14803   SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
 14669  14804   SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
 14670  14805   SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
 14671  14806   #ifdef SQLITE_DEBUG
 14672  14807   SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 14673  14808   #endif
 14674         -SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
        14809  +SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
 14675  14810     void (*)(sqlite3_context*,int,sqlite3_value **),
 14676  14811     void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
 14677  14812     FuncDestructor *pDestructor
 14678  14813   );
 14679  14814   SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
 14680  14815   SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
 14681  14816   SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
................................................................................
 14730  14865   
 14731  14866   #ifdef SQLITE_OMIT_VIRTUALTABLE
 14732  14867   #  define sqlite3VtabClear(Y)
 14733  14868   #  define sqlite3VtabSync(X,Y) SQLITE_OK
 14734  14869   #  define sqlite3VtabRollback(X)
 14735  14870   #  define sqlite3VtabCommit(X)
 14736  14871   #  define sqlite3VtabInSync(db) 0
 14737         -#  define sqlite3VtabLock(X) 
        14872  +#  define sqlite3VtabLock(X)
 14738  14873   #  define sqlite3VtabUnlock(X)
 14739  14874   #  define sqlite3VtabUnlockList(X)
 14740  14875   #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
 14741  14876   #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
 14742  14877   #else
 14743  14878   SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
 14744  14879   SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
................................................................................
 14788  14923   #define sqlite3WithDelete(x,y)
 14789  14924   #endif
 14790  14925   
 14791  14926   /* Declarations for functions in fkey.c. All of these are replaced by
 14792  14927   ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
 14793  14928   ** key functionality is available. If OMIT_TRIGGER is defined but
 14794  14929   ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
 14795         -** this case foreign keys are parsed, but no other functionality is 
        14930  +** this case foreign keys are parsed, but no other functionality is
 14796  14931   ** provided (enforcement of FK constraints requires the triggers sub-system).
 14797  14932   */
 14798  14933   #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 14799  14934   SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
 14800  14935   SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
 14801  14936   SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
 14802  14937   SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
................................................................................
 14849  14984   ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
 14850  14985   */
 14851  14986   #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
 14852  14987   #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
 14853  14988   #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
 14854  14989   SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
 14855  14990   
        14991  +SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
        14992  +SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
 14856  14993   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 14857         -SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
 14858         -SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
 14859  14994   SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
 14860         -SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
 14861         -#else
 14862         -  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
 14863         -  #define sqlite3JournalExists(p) 1
 14864  14995   #endif
 14865  14996   
        14997  +SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
 14866  14998   SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
 14867         -SQLITE_PRIVATE int sqlite3MemJournalSize(void);
 14868         -SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
 14869  14999   
 14870  15000   SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
 14871  15001   #if SQLITE_MAX_EXPR_DEPTH>0
 14872  15002   SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
 14873  15003   SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
 14874  15004   #else
 14875  15005     #define sqlite3SelectExprHeight(x) 0
................................................................................
 14892  15022   #ifdef SQLITE_DEBUG
 14893  15023   SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
 14894  15024   #endif
 14895  15025   
 14896  15026   /*
 14897  15027   ** If the SQLITE_ENABLE IOTRACE exists then the global variable
 14898  15028   ** sqlite3IoTrace is a pointer to a printf-like routine used to
 14899         -** print I/O tracing messages. 
        15029  +** print I/O tracing messages.
 14900  15030   */
 14901  15031   #ifdef SQLITE_ENABLE_IOTRACE
 14902  15032   # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
 14903  15033   SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
 14904  15034   SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
 14905  15035   #else
 14906  15036   # define IOTRACE(A)
................................................................................
 14926  15056   ** Perhaps the most important point is the difference between MEMTYPE_HEAP
 14927  15057   ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
 14928  15058   ** it might have been allocated by lookaside, except the allocation was
 14929  15059   ** too large or lookaside was already full.  It is important to verify
 14930  15060   ** that allocations that might have been satisfied by lookaside are not
 14931  15061   ** passed back to non-lookaside free() routines.  Asserts such as the
 14932  15062   ** example above are placed on the non-lookaside free() routines to verify
 14933         -** this constraint. 
        15063  +** this constraint.
 14934  15064   **
 14935  15065   ** All of this is no-op for a production build.  It only comes into
 14936  15066   ** play when the SQLITE_MEMDEBUG compile-time option is used.
 14937  15067   */
 14938  15068   #ifdef SQLITE_MEMDEBUG
 14939  15069   SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
 14940  15070   SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
................................................................................
 15122  15252   /* The minimum PMA size is set to this value multiplied by the database
 15123  15253   ** page size in bytes.
 15124  15254   */
 15125  15255   #ifndef SQLITE_SORTER_PMASZ
 15126  15256   # define SQLITE_SORTER_PMASZ 250
 15127  15257   #endif
 15128  15258   
        15259  +/* Statement journals spill to disk when their size exceeds the following
        15260  +** threashold (in bytes). 0 means that statement journals are created and
        15261  +** written to disk immediately (the default behavior for SQLite versions
        15262  +** before 3.12.0).  -1 means always keep the entire statement journal in
        15263  +** memory.  (The statement journal is also always held entirely in memory
        15264  +** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
        15265  +** setting.)
        15266  +*/
        15267  +#ifndef SQLITE_STMTJRNL_SPILL 
        15268  +# define SQLITE_STMTJRNL_SPILL (64*1024)
        15269  +#endif
        15270  +
 15129  15271   /*
 15130  15272   ** The following singleton contains the global configuration for
 15131  15273   ** the SQLite library.
 15132  15274   */
 15133  15275   SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
 15134  15276      SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
 15135  15277      1,                         /* bCoreMutex */
................................................................................
 15136  15278      SQLITE_THREADSAFE==1,      /* bFullMutex */
 15137  15279      SQLITE_USE_URI,            /* bOpenUri */
 15138  15280      SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
 15139  15281      0x7ffffffe,                /* mxStrlen */
 15140  15282      0,                         /* neverCorrupt */
 15141  15283      128,                       /* szLookaside */
 15142  15284      500,                       /* nLookaside */
        15285  +   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
 15143  15286      {0,0,0,0,0,0,0,0},         /* m */
 15144  15287      {0,0,0,0,0,0,0,0,0},       /* mutex */
 15145  15288      {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
 15146  15289      (void*)0,                  /* pHeap */
 15147  15290      0,                         /* nHeap */
 15148  15291      0, 0,                      /* mnHeap, mxHeap */
 15149  15292      SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
................................................................................
 15182  15325   };
 15183  15326   
 15184  15327   /*
 15185  15328   ** Hash table for global functions - functions common to all
 15186  15329   ** database connections.  After initialization, this table is
 15187  15330   ** read-only.
 15188  15331   */
 15189         -SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
        15332  +SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 15190  15333   
 15191  15334   /*
 15192  15335   ** Constant tokens for values 0 and 1.
 15193  15336   */
 15194  15337   SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
 15195  15338      { "0", 1 },
 15196  15339      { "1", 1 }
................................................................................
 15783  15926     u8 isTable;           /* True for rowid tables.  False for indexes */
 15784  15927   #ifdef SQLITE_DEBUG
 15785  15928     u8 seekOp;            /* Most recent seek operation on this cursor */
 15786  15929     u8 wrFlag;            /* The wrFlag argument to sqlite3BtreeCursor() */
 15787  15930   #endif
 15788  15931     Bool isEphemeral:1;   /* True for an ephemeral table */
 15789  15932     Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
 15790         -  Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
        15933  +  Bool isOrdered:1;     /* True if the table is not BTREE_UNORDERED */
 15791  15934     Pgno pgnoRoot;        /* Root page of the open btree cursor */
 15792  15935     i16 nField;           /* Number of fields in the header */
 15793  15936     u16 nHdrParsed;       /* Number of header fields parsed so far */
 15794  15937     union {
 15795  15938       BtCursor *pCursor;          /* CURTYPE_BTREE.  Btree cursor */
 15796  15939       sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.   Vtab cursor */
 15797  15940       int pseudoTableReg;         /* CURTYPE_PSEUDO. Reg holding content. */
................................................................................
 15857  16000     Op *aOp;                /* Program instructions for parent frame */
 15858  16001     i64 *anExec;            /* Event counters from parent frame */
 15859  16002     Mem *aMem;              /* Array of memory cells for parent frame */
 15860  16003     u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
 15861  16004     VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
 15862  16005     void *token;            /* Copy of SubProgram.token */
 15863  16006     i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
        16007  +  AuxData *pAuxData;      /* Linked list of auxdata allocations */
 15864  16008     int nCursor;            /* Number of entries in apCsr */
 15865  16009     int pc;                 /* Program Counter in parent (calling) frame */
 15866  16010     int nOp;                /* Size of aOp array */
 15867  16011     int nMem;               /* Number of entries in aMem */
 15868  16012     int nOnceFlag;          /* Number of entries in aOnceFlag */
 15869  16013     int nChildMem;          /* Number of memory cells for child frame */
 15870  16014     int nChildCsr;          /* Number of cursors for child frame */
................................................................................
 16076  16220     int pc;                 /* The program counter */
 16077  16221     int rc;                 /* Value to return */
 16078  16222   #ifdef SQLITE_DEBUG
 16079  16223     int rcApp;              /* errcode set by sqlite3_result_error_code() */
 16080  16224   #endif
 16081  16225     u16 nResColumn;         /* Number of columns in one row of the result set */
 16082  16226     u8 errorAction;         /* Recovery action to do in case of an error */
        16227  +  bft expired:1;          /* True if the VM needs to be recompiled */
        16228  +  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
 16083  16229     u8 minWriteFileFormat;  /* Minimum file format for writable database files */
 16084  16230     bft explain:2;          /* True if EXPLAIN present on SQL command */
 16085  16231     bft changeCntOn:1;      /* True to update the change-counter */
 16086         -  bft expired:1;          /* True if the VM needs to be recompiled */
 16087  16232     bft runOnlyOnce:1;      /* Automatically expire on reset */
 16088  16233     bft usesStmtJournal:1;  /* True if uses a statement journal */
 16089  16234     bft readOnly:1;         /* True for statements that do not write */
 16090  16235     bft bIsReader:1;        /* True for statements that read */
 16091  16236     bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
 16092         -  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
 16093  16237     int nChange;            /* Number of db changes made since last reset */
 16094  16238     yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 16095  16239     yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 16096  16240     int iStatement;         /* Statement number (or 0 if has not opened stmt) */
 16097  16241     u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
 16098  16242   #ifndef SQLITE_OMIT_TRACE
 16099  16243     i64 startTime;          /* Time when query started - used for profiling */
................................................................................
 16139  16283   SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
 16140  16284   #endif
 16141  16285   SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 16142  16286   SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
 16143  16287   SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
 16144  16288   SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
 16145  16289   SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 16146         -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
        16290  +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
 16147  16291   
 16148  16292   int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 16149  16293   SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
 16150  16294   SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
 16151  16295   SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
 16152  16296   SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 16153  16297   SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
................................................................................
 17705  17849   
 17706  17850   /*
 17707  17851   ** This function registered all of the above C functions as SQL
 17708  17852   ** functions.  This should be the only routine in this file with
 17709  17853   ** external linkage.
 17710  17854   */
 17711  17855   SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
 17712         -  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
        17856  +  static FuncDef aDateTimeFuncs[] = {
 17713  17857   #ifndef SQLITE_OMIT_DATETIME_FUNCS
 17714  17858       DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
 17715  17859       DFUNCTION(date,             -1, 0, 0, dateFunc      ),
 17716  17860       DFUNCTION(time,             -1, 0, 0, timeFunc      ),
 17717  17861       DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
 17718  17862       DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
 17719  17863       DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
................................................................................
 17721  17865       DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
 17722  17866   #else
 17723  17867       STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
 17724  17868       STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
 17725  17869       STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
 17726  17870   #endif
 17727  17871     };
 17728         -  int i;
 17729         -  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 17730         -  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
 17731         -
 17732         -  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
 17733         -    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 17734         -  }
        17872  +  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
 17735  17873   }
 17736  17874   
 17737  17875   /************** End of date.c ************************************************/
 17738  17876   /************** Begin file os.c **********************************************/
 17739  17877   /*
 17740  17878   ** 2005 November 29
 17741  17879   **
................................................................................
 17800  17938   **     sqlite3OsAccess()
 17801  17939   **     sqlite3OsFullPathname()
 17802  17940   **
 17803  17941   */
 17804  17942   #if defined(SQLITE_TEST)
 17805  17943   SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
 17806  17944     #define DO_OS_MALLOC_TEST(x)                                       \
 17807         -  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
        17945  +  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
 17808  17946       void *pTstAlloc = sqlite3Malloc(10);                             \
 17809         -    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
        17947  +    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
 17810  17948       sqlite3_free(pTstAlloc);                                         \
 17811  17949     }
 17812  17950   #else
 17813  17951     #define DO_OS_MALLOC_TEST(x)
 17814  17952   #endif
 17815  17953   
 17816  17954   /*
................................................................................
 17996  18134   #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 17997  18135   SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 17998  18136     return pVfs->xRandomness(pVfs, nByte, zBufOut);
 17999  18137   }
 18000  18138   SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
 18001  18139     return pVfs->xSleep(pVfs, nMicro);
 18002  18140   }
        18141  +SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
        18142  +  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
        18143  +}
 18003  18144   SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
 18004  18145     int rc;
 18005  18146     /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
 18006  18147     ** method to get the current date and time if that method is available
 18007  18148     ** (if iVersion is 2 or greater and the function pointer is not NULL) and
 18008  18149     ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
 18009  18150     ** unavailable.
................................................................................
 18021  18162   SQLITE_PRIVATE int sqlite3OsOpenMalloc(
 18022  18163     sqlite3_vfs *pVfs,
 18023  18164     const char *zFile,
 18024  18165     sqlite3_file **ppFile,
 18025  18166     int flags,
 18026  18167     int *pOutFlags
 18027  18168   ){
 18028         -  int rc = SQLITE_NOMEM;
        18169  +  int rc;
 18029  18170     sqlite3_file *pFile;
 18030  18171     pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
 18031  18172     if( pFile ){
 18032  18173       rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
 18033  18174       if( rc!=SQLITE_OK ){
 18034  18175         sqlite3_free(pFile);
 18035  18176       }else{
 18036  18177         *ppFile = pFile;
 18037  18178       }
        18179  +  }else{
        18180  +    rc = SQLITE_NOMEM_BKPT;
 18038  18181     }
 18039  18182     return rc;
 18040  18183   }
 18041  18184   SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
 18042  18185     int rc = SQLITE_OK;
 18043  18186     assert( pFile );
 18044  18187     rc = sqlite3OsClose(pFile);
................................................................................
 18050  18193   ** This function is a wrapper around the OS specific implementation of
 18051  18194   ** sqlite3_os_init(). The purpose of the wrapper is to provide the
 18052  18195   ** ability to simulate a malloc failure, so that the handling of an
 18053  18196   ** error in sqlite3_os_init() by the upper layers can be tested.
 18054  18197   */
 18055  18198   SQLITE_PRIVATE int sqlite3OsInit(void){
 18056  18199     void *p = sqlite3_malloc(10);
 18057         -  if( p==0 ) return SQLITE_NOMEM;
        18200  +  if( p==0 ) return SQLITE_NOMEM_BKPT;
 18058  18201     sqlite3_free(p);
 18059  18202     return sqlite3_os_init();
 18060  18203   }
 18061  18204   
 18062  18205   /*
 18063  18206   ** The list of all registered VFS implementations.
 18064  18207   */
................................................................................
 22672  22815   
 22673  22816   /*
 22674  22817   ** Take actions at the end of an API call to indicate an OOM error
 22675  22818   */
 22676  22819   static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
 22677  22820     sqlite3OomClear(db);
 22678  22821     sqlite3Error(db, SQLITE_NOMEM);
 22679         -  return SQLITE_NOMEM;
        22822  +  return SQLITE_NOMEM_BKPT;
 22680  22823   }
 22681  22824   
 22682  22825   /*
 22683  22826   ** This function must be called before exiting any API function (i.e. 
 22684  22827   ** returning control to the user) that has called sqlite3_malloc or
 22685  22828   ** sqlite3_realloc.
 22686  22829   **
................................................................................
 23931  24074     pView = sqlite3TreeViewPush(pView, moreToFollow);
 23932  24075     if( p->pWith ){
 23933  24076       sqlite3TreeViewWith(pView, p->pWith, 1);
 23934  24077       cnt = 1;
 23935  24078       sqlite3TreeViewPush(pView, 1);
 23936  24079     }
 23937  24080     do{
 23938         -    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x",
        24081  +    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
 23939  24082         ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
 23940         -      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags
        24083  +      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
        24084  +      (int)p->nSelectRow
 23941  24085       );
 23942  24086       if( cnt++ ) sqlite3TreeViewPop(pView);
 23943  24087       if( p->pPrior ){
 23944  24088         n = 1000;
 23945  24089       }else{
 23946  24090         n = 0;
 23947  24091         if( p->pSrc && p->pSrc->nSrc ) n++;
................................................................................
 24136  24280   
 24137  24281       case TK_UMINUS:  zUniOp = "UMINUS"; break;
 24138  24282       case TK_UPLUS:   zUniOp = "UPLUS";  break;
 24139  24283       case TK_BITNOT:  zUniOp = "BITNOT"; break;
 24140  24284       case TK_NOT:     zUniOp = "NOT";    break;
 24141  24285       case TK_ISNULL:  zUniOp = "ISNULL"; break;
 24142  24286       case TK_NOTNULL: zUniOp = "NOTNULL"; break;
        24287  +
        24288  +    case TK_SPAN: {
        24289  +      sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
        24290  +      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
        24291  +      break;
        24292  +    }
 24143  24293   
 24144  24294       case TK_COLLATE: {
 24145  24295         sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
 24146  24296         sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 24147  24297         break;
 24148  24298       }
 24149  24299   
................................................................................
 24488  24638     assert( ppThread!=0 );
 24489  24639     assert( xTask!=0 );
 24490  24640     /* This routine is never used in single-threaded mode */
 24491  24641     assert( sqlite3GlobalConfig.bCoreMutex!=0 );
 24492  24642   
 24493  24643     *ppThread = 0;
 24494  24644     p = sqlite3Malloc(sizeof(*p));
 24495         -  if( p==0 ) return SQLITE_NOMEM;
        24645  +  if( p==0 ) return SQLITE_NOMEM_BKPT;
 24496  24646     memset(p, 0, sizeof(*p));
 24497  24647     p->xTask = xTask;
 24498  24648     p->pIn = pIn;
 24499  24649     /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 24500  24650     ** function that returns SQLITE_ERROR when passed the argument 200, that
 24501  24651     ** forces worker threads to run sequentially and deterministically 
 24502  24652     ** for testing purposes. */
................................................................................
 24514  24664   }
 24515  24665   
 24516  24666   /* Get the results of the thread */
 24517  24667   SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 24518  24668     int rc;
 24519  24669   
 24520  24670     assert( ppOut!=0 );
 24521         -  if( NEVER(p==0) ) return SQLITE_NOMEM;
        24671  +  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 24522  24672     if( p->done ){
 24523  24673       *ppOut = p->pOut;
 24524  24674       rc = SQLITE_OK;
 24525  24675     }else{
 24526  24676       rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
 24527  24677     }
 24528  24678     sqlite3_free(p);
................................................................................
 24579  24729   ){
 24580  24730     SQLiteThread *p;
 24581  24731   
 24582  24732     assert( ppThread!=0 );
 24583  24733     assert( xTask!=0 );
 24584  24734     *ppThread = 0;
 24585  24735     p = sqlite3Malloc(sizeof(*p));
 24586         -  if( p==0 ) return SQLITE_NOMEM;
        24736  +  if( p==0 ) return SQLITE_NOMEM_BKPT;
 24587  24737     /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 24588  24738     ** function that returns SQLITE_ERROR when passed the argument 200, that
 24589  24739     ** forces worker threads to run sequentially and deterministically 
 24590  24740     ** (via the sqlite3FaultSim() term of the conditional) for testing
 24591  24741     ** purposes. */
 24592  24742     if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
 24593  24743       memset(p, 0, sizeof(*p));
................................................................................
 24611  24761   
 24612  24762   /* Get the results of the thread */
 24613  24763   SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 24614  24764     DWORD rc;
 24615  24765     BOOL bRc;
 24616  24766   
 24617  24767     assert( ppOut!=0 );
 24618         -  if( NEVER(p==0) ) return SQLITE_NOMEM;
        24768  +  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 24619  24769     if( p->xTask==0 ){
 24620  24770       /* assert( p->id==GetCurrentThreadId() ); */
 24621  24771       rc = WAIT_OBJECT_0;
 24622  24772       assert( p->tid==0 );
 24623  24773     }else{
 24624  24774       assert( p->id!=0 && p->id!=GetCurrentThreadId() );
 24625  24775       rc = sqlite3Win32Wait((HANDLE)p->tid);
................................................................................
 24659  24809   ){
 24660  24810     SQLiteThread *p;
 24661  24811   
 24662  24812     assert( ppThread!=0 );
 24663  24813     assert( xTask!=0 );
 24664  24814     *ppThread = 0;
 24665  24815     p = sqlite3Malloc(sizeof(*p));
 24666         -  if( p==0 ) return SQLITE_NOMEM;
        24816  +  if( p==0 ) return SQLITE_NOMEM_BKPT;
 24667  24817     if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
 24668  24818       p->xTask = xTask;
 24669  24819       p->pIn = pIn;
 24670  24820     }else{
 24671  24821       p->xTask = 0;
 24672  24822       p->pResult = xTask(pIn);
 24673  24823     }
................................................................................
 24675  24825     return SQLITE_OK;
 24676  24826   }
 24677  24827   
 24678  24828   /* Get the results of the thread */
 24679  24829   SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 24680  24830   
 24681  24831     assert( ppOut!=0 );
 24682         -  if( NEVER(p==0) ) return SQLITE_NOMEM;
        24832  +  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 24683  24833     if( p->xTask ){
 24684  24834       *ppOut = p->xTask(p->pIn);
 24685  24835     }else{
 24686  24836       *ppOut = p->pResult;
 24687  24837     }
 24688  24838     sqlite3_free(p);
 24689  24839   
 24690  24840   #if defined(SQLITE_TEST)
 24691  24841     {
 24692  24842       void *pTstAlloc = sqlite3Malloc(10);
 24693         -    if (!pTstAlloc) return SQLITE_NOMEM;
        24843  +    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
 24694  24844       sqlite3_free(pTstAlloc);
 24695  24845     }
 24696  24846   #endif
 24697  24847   
 24698  24848     return SQLITE_OK;
 24699  24849   }
 24700  24850   
................................................................................
 24933  25083     */
 24934  25084     if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
 24935  25085       u8 temp;
 24936  25086       int rc;
 24937  25087       rc = sqlite3VdbeMemMakeWriteable(pMem);
 24938  25088       if( rc!=SQLITE_OK ){
 24939  25089         assert( rc==SQLITE_NOMEM );
 24940         -      return SQLITE_NOMEM;
        25090  +      return SQLITE_NOMEM_BKPT;
 24941  25091       }
 24942  25092       zIn = (u8*)pMem->z;
 24943  25093       zTerm = &zIn[pMem->n&~1];
 24944  25094       while( zIn<zTerm ){
 24945  25095         temp = *zIn;
 24946  25096         *zIn = *(zIn+1);
 24947  25097         zIn++;
................................................................................
 24975  25125     ** Variable zOut is set to point at the output buffer, space obtained
 24976  25126     ** from sqlite3_malloc().
 24977  25127     */
 24978  25128     zIn = (u8*)pMem->z;
 24979  25129     zTerm = &zIn[pMem->n];
 24980  25130     zOut = sqlite3DbMallocRaw(pMem->db, len);
 24981  25131     if( !zOut ){
 24982         -    return SQLITE_NOMEM;
        25132  +    return SQLITE_NOMEM_BKPT;
 24983  25133     }
 24984  25134     z = zOut;
 24985  25135   
 24986  25136     if( pMem->enc==SQLITE_UTF8 ){
 24987  25137       if( desiredEnc==SQLITE_UTF16LE ){
 24988  25138         /* UTF-8 -> UTF-16 Little-endian */
 24989  25139         while( zIn<zTerm ){
................................................................................
 25343  25493   ** than the actual length of the string.  For very long strings (greater
 25344  25494   ** than 1GiB) the value returned might be less than the true string length.
 25345  25495   */
 25346  25496   SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 25347  25497     if( z==0 ) return 0;
 25348  25498     return 0x3fffffff & (int)strlen(z);
 25349  25499   }
        25500  +
        25501  +/*
        25502  +** The string z[] is followed immediately by another string.  Return
        25503  +** a poiner to that other string.
        25504  +*/
        25505  +SQLITE_PRIVATE const char *sqlite3StrNext(const char *z){
        25506  +  return z + strlen(z) + 1;
        25507  +}
        25508  +
        25509  +/*
        25510  +** Helper function for sqlite3Error() - called rarely.  Broken out into
        25511  +** a separate routine to avoid unnecessary register saves on entry to
        25512  +** sqlite3Error().
        25513  +*/
        25514  +static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
        25515  +  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
        25516  +  sqlite3SystemError(db, err_code);
        25517  +}
 25350  25518   
 25351  25519   /*
 25352  25520   ** Set the current error code to err_code and clear any prior error message.
        25521  +** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
        25522  +** that would be appropriate.
 25353  25523   */
 25354  25524   SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
 25355  25525     assert( db!=0 );
 25356  25526     db->errCode = err_code;
 25357         -  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
        25527  +  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
        25528  +}
        25529  +
        25530  +/*
        25531  +** Load the sqlite3.iSysErrno field if that is an appropriate thing
        25532  +** to do based on the SQLite error code in rc.
        25533  +*/
        25534  +SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
        25535  +  if( rc==SQLITE_IOERR_NOMEM ) return;
        25536  +  rc &= 0xff;
        25537  +  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
        25538  +    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
        25539  +  }
 25358  25540   }
 25359  25541   
 25360  25542   /*
 25361  25543   ** Set the most recent error code and error string for the sqlite
 25362  25544   ** handle "db". The error code is set to "err_code".
 25363  25545   **
 25364  25546   ** If it is not NULL, string zFormat specifies the format of the
................................................................................
 25377  25559   ** To clear the most recent error for sqlite handle "db", sqlite3Error
 25378  25560   ** should be called with err_code set to SQLITE_OK and zFormat set
 25379  25561   ** to NULL.
 25380  25562   */
 25381  25563   SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
 25382  25564     assert( db!=0 );
 25383  25565     db->errCode = err_code;
        25566  +  sqlite3SystemError(db, err_code);
 25384  25567     if( zFormat==0 ){
 25385  25568       sqlite3Error(db, err_code);
 25386  25569     }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
 25387  25570       char *z;
 25388  25571       va_list ap;
 25389  25572       va_start(ap, zFormat);
 25390  25573       z = sqlite3VMPrintf(db, zFormat, ap);
................................................................................
 25491  25674   ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
 25492  25675   ** sqlite3_strnicmp() APIs allow applications and extensions to compare
 25493  25676   ** the contents of two buffers containing UTF-8 strings in a
 25494  25677   ** case-independent fashion, using the same definition of "case
 25495  25678   ** independence" that SQLite uses internally when comparing identifiers.
 25496  25679   */
 25497  25680   SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
 25498         -  register unsigned char *a, *b;
 25499  25681     if( zLeft==0 ){
 25500  25682       return zRight ? -1 : 0;
 25501  25683     }else if( zRight==0 ){
 25502  25684       return 1;
 25503  25685     }
        25686  +  return sqlite3StrICmp(zLeft, zRight);
        25687  +}
        25688  +SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
        25689  +  unsigned char *a, *b;
        25690  +  int c;
 25504  25691     a = (unsigned char *)zLeft;
 25505  25692     b = (unsigned char *)zRight;
 25506         -  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
 25507         -  return UpperToLower[*a] - UpperToLower[*b];
        25693  +  for(;;){
        25694  +    c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
        25695  +    if( c || *a==0 ) break;
        25696  +    a++;
        25697  +    b++;
        25698  +  }
        25699  +  return c;
 25508  25700   }
 25509  25701   SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
 25510  25702     register unsigned char *a, *b;
 25511  25703     if( zLeft==0 ){
 25512  25704       return zRight ? -1 : 0;
 25513  25705     }else if( zRight==0 ){
 25514  25706       return 1;
................................................................................
 26311  26503   
 26312  26504   /*
 26313  26505   ** Return the number of bytes that will be needed to store the given
 26314  26506   ** 64-bit integer.
 26315  26507   */
 26316  26508   SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
 26317  26509     int i;
 26318         -  for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
        26510  +  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
 26319  26511     return i;
 26320  26512   }
 26321  26513   
 26322  26514   
 26323  26515   /*
 26324  26516   ** Read or write a four-byte big-endian integer value.
 26325  26517   */
................................................................................
 26342  26534     testcase( p[0]&0x80 );
 26343  26535     return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
 26344  26536   #endif
 26345  26537   }
 26346  26538   SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
 26347  26539   #if SQLITE_BYTEORDER==4321
 26348  26540     memcpy(p,&v,4);
 26349         -#elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
        26541  +#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
        26542  +    && defined(__GNUC__) && GCC_VERSION>=4003000
 26350  26543     u32 x = __builtin_bswap32(v);
 26351  26544     memcpy(p,&x,4);
 26352         -#elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
        26545  +#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
        26546  +    && defined(_MSC_VER) && _MSC_VER>=1300
 26353  26547     u32 x = _byteswap_ulong(v);
 26354  26548     memcpy(p,&x,4);
 26355  26549   #else
 26356  26550     p[0] = (u8)(v>>24);
 26357  26551     p[1] = (u8)(v>>16);
 26358  26552     p[2] = (u8)(v>>8);
 26359  26553     p[3] = (u8)v;
................................................................................
 26624  26818     if( x<=2000000000 ) return sqlite3LogEst((u64)x);
 26625  26819     memcpy(&a, &x, 8);
 26626  26820     e = (a>>52) - 1022;
 26627  26821     return e*10;
 26628  26822   }
 26629  26823   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 26630  26824   
        26825  +#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
        26826  +    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
        26827  +    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 26631  26828   /*
 26632  26829   ** Convert a LogEst into an integer.
        26830  +**
        26831  +** Note that this routine is only used when one or more of various
        26832  +** non-standard compile-time options is enabled.
 26633  26833   */
 26634  26834   SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 26635  26835     u64 n;
 26636  26836     if( x<10 ) return 1;
 26637  26837     n = x%10;
 26638  26838     x /= 10;
 26639  26839     if( n>=5 ) n -= 2;
 26640  26840     else if( n>=1 ) n -= 1;
 26641         -  if( x>=3 ){
 26642         -    return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
 26643         -  }
 26644         -  return (n+8)>>(3-x);
        26841  +#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
        26842  +    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
        26843  +  if( x>60 ) return (u64)LARGEST_INT64;
        26844  +#else
        26845  +  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
        26846  +  ** possible to this routine is 310, resulting in a maximum x of 31 */
        26847  +  assert( x<=60 );
        26848  +#endif
        26849  +  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
 26645  26850   }
        26851  +#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
 26646  26852   
 26647  26853   /************** End of util.c ************************************************/
 26648  26854   /************** Begin file hash.c ********************************************/
 26649  26855   /*
 26650  26856   ** 2001 September 22
 26651  26857   **
 26652  26858   ** The author disclaims copyright to this source code.  In place of
................................................................................
 27165  27371   #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 27166  27372   #  if defined(__APPLE__)
 27167  27373   #    define SQLITE_ENABLE_LOCKING_STYLE 1
 27168  27374   #  else
 27169  27375   #    define SQLITE_ENABLE_LOCKING_STYLE 0
 27170  27376   #  endif
 27171  27377   #endif
        27378  +
        27379  +/* Use pread() and pwrite() if they are available */
        27380  +#if defined(__APPLE__)
        27381  +# define HAVE_PREAD 1
        27382  +# define HAVE_PWRITE 1
        27383  +#endif
        27384  +#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
        27385  +# undef USE_PREAD
        27386  +# define USE_PREAD64 1
        27387  +#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
        27388  +# undef USE_PREAD64
        27389  +# define USE_PREAD 1
        27390  +#endif
 27172  27391   
 27173  27392   /*
 27174  27393   ** standard include files.
 27175  27394   */
 27176  27395   #include <sys/types.h>
 27177  27396   #include <sys/stat.h>
 27178  27397   #include <fcntl.h>
................................................................................
 28595  28814     pInode = inodeList;
 28596  28815     while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
 28597  28816       pInode = pInode->pNext;
 28598  28817     }
 28599  28818     if( pInode==0 ){
 28600  28819       pInode = sqlite3_malloc64( sizeof(*pInode) );
 28601  28820       if( pInode==0 ){
 28602         -      return SQLITE_NOMEM;
        28821  +      return SQLITE_NOMEM_BKPT;
 28603  28822       }
 28604  28823       memset(pInode, 0, sizeof(*pInode));
 28605  28824       memcpy(&pInode->fileId, &fileId, sizeof(fileId));
 28606  28825       pInode->nRef = 1;
 28607  28826       pInode->pNext = inodeList;
 28608  28827       pInode->pPrev = 0;
 28609  28828       if( inodeList ) inodeList->pPrev = pInode;
................................................................................
 28637  28856   ** (3) The file has not been renamed or unlinked
 28638  28857   **
 28639  28858   ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
 28640  28859   */
 28641  28860   static void verifyDbFile(unixFile *pFile){
 28642  28861     struct stat buf;
 28643  28862     int rc;
        28863  +
        28864  +  /* These verifications occurs for the main database only */
        28865  +  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
        28866  +
 28644  28867     rc = osFstat(pFile->h, &buf);
 28645  28868     if( rc!=0 ){
 28646  28869       sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
 28647  28870       return;
 28648  28871     }
 28649         -  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
        28872  +  if( buf.st_nlink==0 ){
 28650  28873       sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
 28651  28874       return;
 28652  28875     }
 28653  28876     if( buf.st_nlink>1 ){
 28654  28877       sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
 28655  28878       return;
 28656  28879     }
................................................................................
 31515  31738     int rc;                         /* Result code */
 31516  31739     unixInodeInfo *pInode;          /* The inode of fd */
 31517  31740     char *zShmFilename;             /* Name of the file used for SHM */
 31518  31741     int nShmFilename;               /* Size of the SHM filename in bytes */
 31519  31742   
 31520  31743     /* Allocate space for the new unixShm object. */
 31521  31744     p = sqlite3_malloc64( sizeof(*p) );
 31522         -  if( p==0 ) return SQLITE_NOMEM;
        31745  +  if( p==0 ) return SQLITE_NOMEM_BKPT;
 31523  31746     memset(p, 0, sizeof(*p));
 31524  31747     assert( pDbFd->pShm==0 );
 31525  31748   
 31526  31749     /* Check to see if a unixShmNode object already exists. Reuse an existing
 31527  31750     ** one if present. Create a new one if necessary.
 31528  31751     */
 31529  31752     unixEnterMutex();
................................................................................
 31547  31770   #ifdef SQLITE_SHM_DIRECTORY
 31548  31771       nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
 31549  31772   #else
 31550  31773       nShmFilename = 6 + (int)strlen(zBasePath);
 31551  31774   #endif
 31552  31775       pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
 31553  31776       if( pShmNode==0 ){
 31554         -      rc = SQLITE_NOMEM;
        31777  +      rc = SQLITE_NOMEM_BKPT;
 31555  31778         goto shm_open_err;
 31556  31779       }
 31557  31780       memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
 31558  31781       zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
 31559  31782   #ifdef SQLITE_SHM_DIRECTORY
 31560  31783       sqlite3_snprintf(nShmFilename, zShmFilename, 
 31561  31784                        SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
................................................................................
 31565  31788       sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
 31566  31789   #endif
 31567  31790       pShmNode->h = -1;
 31568  31791       pDbFd->pInode->pShmNode = pShmNode;
 31569  31792       pShmNode->pInode = pDbFd->pInode;
 31570  31793       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 31571  31794       if( pShmNode->mutex==0 ){
 31572         -      rc = SQLITE_NOMEM;
        31795  +      rc = SQLITE_NOMEM_BKPT;
 31573  31796         goto shm_open_err;
 31574  31797       }
 31575  31798   
 31576  31799       if( pInode->bProcessLock==0 ){
 31577  31800         int openFlags = O_RDWR | O_CREAT;
 31578  31801         if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 31579  31802           openFlags = O_RDONLY;
................................................................................
 31738  31961       }
 31739  31962   
 31740  31963       /* Map the requested memory region into this processes address space. */
 31741  31964       apNew = (char **)sqlite3_realloc(
 31742  31965           pShmNode->apRegion, nReqRegion*sizeof(char *)
 31743  31966       );
 31744  31967       if( !apNew ){
 31745         -      rc = SQLITE_IOERR_NOMEM;
        31968  +      rc = SQLITE_IOERR_NOMEM_BKPT;
 31746  31969         goto shmpage_out;
 31747  31970       }
 31748  31971       pShmNode->apRegion = apNew;
 31749  31972       while( pShmNode->nRegion<nReqRegion ){
 31750  31973         int nMap = szRegion*nShmPerMap;
 31751  31974         int i;
 31752  31975         void *pMem;
................................................................................
 31758  31981           if( pMem==MAP_FAILED ){
 31759  31982             rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
 31760  31983             goto shmpage_out;
 31761  31984           }
 31762  31985         }else{
 31763  31986           pMem = sqlite3_malloc64(szRegion);
 31764  31987           if( pMem==0 ){
 31765         -          rc = SQLITE_NOMEM;
        31988  +          rc = SQLITE_NOMEM_BKPT;
 31766  31989             goto shmpage_out;
 31767  31990           }
 31768  31991           memset(pMem, 0, szRegion);
 31769  31992         }
 31770  31993   
 31771  31994         for(i=0; i<nShmPerMap; i++){
 31772  31995           pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
................................................................................
 32536  32759       pNew->ctrlFlags |= UNIXFILE_EXCL;
 32537  32760     }
 32538  32761   
 32539  32762   #if OS_VXWORKS
 32540  32763     pNew->pId = vxworksFindFileId(zFilename);
 32541  32764     if( pNew->pId==0 ){
 32542  32765       ctrlFlags |= UNIXFILE_NOLOCK;
 32543         -    rc = SQLITE_NOMEM;
        32766  +    rc = SQLITE_NOMEM_BKPT;
 32544  32767     }
 32545  32768   #endif
 32546  32769   
 32547  32770     if( ctrlFlags & UNIXFILE_NOLOCK ){
 32548  32771       pLockingStyle = &nolockIoMethods;
 32549  32772     }else{
 32550  32773       pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
................................................................................
 32592  32815     else if( pLockingStyle == &afpIoMethods ){
 32593  32816       /* AFP locking uses the file path so it needs to be included in
 32594  32817       ** the afpLockingContext.
 32595  32818       */
 32596  32819       afpLockingContext *pCtx;
 32597  32820       pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 32598  32821       if( pCtx==0 ){
 32599         -      rc = SQLITE_NOMEM;
        32822  +      rc = SQLITE_NOMEM_BKPT;
 32600  32823       }else{
 32601  32824         /* NB: zFilename exists and remains valid until the file is closed
 32602  32825         ** according to requirement F11141.  So we do not need to make a
 32603  32826         ** copy of the filename. */
 32604  32827         pCtx->dbPath = zFilename;
 32605  32828         pCtx->reserved = 0;
 32606  32829         srandomdev();
................................................................................
 32622  32845       */
 32623  32846       char *zLockFile;
 32624  32847       int nFilename;
 32625  32848       assert( zFilename!=0 );
 32626  32849       nFilename = (int)strlen(zFilename) + 6;
 32627  32850       zLockFile = (char *)sqlite3_malloc64(nFilename);
 32628  32851       if( zLockFile==0 ){
 32629         -      rc = SQLITE_NOMEM;
        32852  +      rc = SQLITE_NOMEM_BKPT;
 32630  32853       }else{
 32631  32854         sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
 32632  32855       }
 32633  32856       pNew->lockingContext = zLockFile;
 32634  32857     }
 32635  32858   
 32636  32859   #if OS_VXWORKS
................................................................................
 32645  32868         int n;
 32646  32869         sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
 32647  32870                          pNew->pId->zCanonicalName);
 32648  32871         for( n=1; zSemName[n]; n++ )
 32649  32872           if( zSemName[n]=='/' ) zSemName[n] = '_';
 32650  32873         pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
 32651  32874         if( pNew->pInode->pSem == SEM_FAILED ){
 32652         -        rc = SQLITE_NOMEM;
        32875  +        rc = SQLITE_NOMEM_BKPT;
 32653  32876           pNew->pInode->aSemName[0] = '\0';
 32654  32877         }
 32655  32878       }
 32656  32879       unixLeaveMutex();
 32657  32880     }
 32658  32881   #endif
 32659  32882     
................................................................................
 32986  33209       UnixUnusedFd *pUnused;
 32987  33210       pUnused = findReusableFd(zName, flags);
 32988  33211       if( pUnused ){
 32989  33212         fd = pUnused->fd;
 32990  33213       }else{
 32991  33214         pUnused = sqlite3_malloc64(sizeof(*pUnused));
 32992  33215         if( !pUnused ){
 32993         -        return SQLITE_NOMEM;
        33216  +        return SQLITE_NOMEM_BKPT;
 32994  33217         }
 32995  33218       }
 32996  33219       p->pUnused = pUnused;
 32997  33220   
 32998  33221       /* Database filenames are double-zero terminated if they are not
 32999  33222       ** URIs with parameters.  Hence, they can always be passed into
 33000  33223       ** sqlite3_uri_parameter(). */
................................................................................
 33072  33295     if( isDelete ){
 33073  33296   #if OS_VXWORKS
 33074  33297       zPath = zName;
 33075  33298   #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
 33076  33299       zPath = sqlite3_mprintf("%s", zName);
 33077  33300       if( zPath==0 ){
 33078  33301         robust_close(p, fd, __LINE__);
 33079         -      return SQLITE_NOMEM;
        33302  +      return SQLITE_NOMEM_BKPT;
 33080  33303       }
 33081  33304   #else
 33082  33305       osUnlink(zName);
 33083  33306   #endif
 33084  33307     }
 33085  33308   #if SQLITE_ENABLE_LOCKING_STYLE
 33086  33309     else{
 33087  33310       p->openFlags = openFlags;
 33088  33311     }
 33089  33312   #endif
 33090         -
 33091         -  noLock = eType!=SQLITE_OPEN_MAIN_DB;
 33092         -
 33093  33313     
 33094  33314   #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 33095  33315     if( fstatfs(fd, &fsInfo) == -1 ){
 33096  33316       storeLastErrno(p, errno);
 33097  33317       robust_close(p, fd, __LINE__);
 33098  33318       return SQLITE_IOERR_ACCESS;
 33099  33319     }
................................................................................
 33104  33324       ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 33105  33325     }
 33106  33326   #endif
 33107  33327   
 33108  33328     /* Set up appropriate ctrlFlags */
 33109  33329     if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
 33110  33330     if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
        33331  +  noLock = eType!=SQLITE_OPEN_MAIN_DB;
 33111  33332     if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
 33112  33333     if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
 33113  33334     if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
 33114  33335   
 33115  33336   #if SQLITE_ENABLE_LOCKING_STYLE
 33116  33337   #if SQLITE_PREFER_PROXY_LOCKING
 33117  33338     isAutoProxy = 1;
................................................................................
 33304  33525       }else{
 33305  33526         bLink = S_ISLNK(buf.st_mode);
 33306  33527       }
 33307  33528   
 33308  33529       if( bLink ){
 33309  33530         if( zDel==0 ){
 33310  33531           zDel = sqlite3_malloc(nOut);
 33311         -        if( zDel==0 ) rc = SQLITE_NOMEM;
        33532  +        if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
 33312  33533         }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
 33313  33534           rc = SQLITE_CANTOPEN_BKPT;
 33314  33535         }
 33315  33536   
 33316  33537         if( rc==SQLITE_OK ){
 33317  33538           nByte = osReadlink(zIn, zDel, nOut-1);
 33318  33539           if( nByte<0 ){
................................................................................
 33542  33763     *prNow = i/86400000.0;
 33543  33764     return rc;
 33544  33765   }
 33545  33766   #else
 33546  33767   # define unixCurrentTime 0
 33547  33768   #endif
 33548  33769   
 33549         -#ifndef SQLITE_OMIT_DEPRECATED
 33550  33770   /*
 33551         -** We added the xGetLastError() method with the intention of providing
 33552         -** better low-level error messages when operating-system problems come up
 33553         -** during SQLite operation.  But so far, none of that has been implemented
 33554         -** in the core.  So this routine is never called.  For now, it is merely
 33555         -** a place-holder.
        33771  +** The xGetLastError() method is designed to return a better
        33772  +** low-level error message when operating-system problems come up
        33773  +** during SQLite operation.  Only the integer return code is currently
        33774  +** used.
 33556  33775   */
 33557  33776   static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 33558  33777     UNUSED_PARAMETER(NotUsed);
 33559  33778     UNUSED_PARAMETER(NotUsed2);
 33560  33779     UNUSED_PARAMETER(NotUsed3);
 33561         -  return 0;
        33780  +  return errno;
 33562  33781   }
 33563         -#else
 33564         -# define unixGetLastError 0
 33565         -#endif
 33566  33782   
 33567  33783   
 33568  33784   /*
 33569  33785   ************************ End of sqlite3_vfs methods ***************************
 33570  33786   ******************************************************************************/
 33571  33787   
 33572  33788   /******************************************************************************
................................................................................
 33848  34064     */
 33849  34065     pUnused = findReusableFd(path, openFlags);
 33850  34066     if( pUnused ){
 33851  34067       fd = pUnused->fd;
 33852  34068     }else{
 33853  34069       pUnused = sqlite3_malloc64(sizeof(*pUnused));
 33854  34070       if( !pUnused ){
 33855         -      return SQLITE_NOMEM;
        34071  +      return SQLITE_NOMEM_BKPT;
 33856  34072       }
 33857  34073     }
 33858  34074     if( fd<0 ){
 33859  34075       fd = robust_open(path, openFlags, 0);
 33860  34076       terrno = errno;
 33861  34077       if( fd<0 && errno==ENOENT && islockfile ){
 33862  34078         if( proxyCreateLockPath(path) == SQLITE_OK ){
................................................................................
 33881  34097         default:
 33882  34098           return SQLITE_CANTOPEN_BKPT;
 33883  34099       }
 33884  34100     }
 33885  34101     
 33886  34102     pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
 33887  34103     if( pNew==NULL ){
 33888         -    rc = SQLITE_NOMEM;
        34104  +    rc = SQLITE_NOMEM_BKPT;
 33889  34105       goto end_create_proxy;
 33890  34106     }
 33891  34107     memset(pNew, 0, sizeof(unixFile));
 33892  34108     pNew->openFlags = openFlags;
 33893  34109     memset(&dummyVfs, 0, sizeof(dummyVfs));
 33894  34110     dummyVfs.pAppData = (void*)&autolockIoFinder;
 33895  34111     dummyVfs.zName = "dummy";
................................................................................
 34294  34510         if( rc==SQLITE_OK ){
 34295  34511           /* Need to make a copy of path if we extracted the value
 34296  34512            ** from the conch file or the path was allocated on the stack
 34297  34513            */
 34298  34514           if( tempLockPath ){
 34299  34515             pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
 34300  34516             if( !pCtx->lockProxyPath ){
 34301         -            rc = SQLITE_NOMEM;
        34517  +            rc = SQLITE_NOMEM_BKPT;
 34302  34518             }
 34303  34519           }
 34304  34520         }
 34305  34521         if( rc==SQLITE_OK ){
 34306  34522           pCtx->conchHeld = 1;
 34307  34523           
 34308  34524           if( pCtx->lockProxy->pMethod == &afpIoMethods ){
................................................................................
 34359  34575     int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
 34360  34576     char *conchPath;              /* buffer in which to construct conch name */
 34361  34577   
 34362  34578     /* Allocate space for the conch filename and initialize the name to
 34363  34579     ** the name of the original database file. */  
 34364  34580     *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
 34365  34581     if( conchPath==0 ){
 34366         -    return SQLITE_NOMEM;
        34582  +    return SQLITE_NOMEM_BKPT;
 34367  34583     }
 34368  34584     memcpy(conchPath, dbPath, len+1);
 34369  34585     
 34370  34586     /* now insert a "." before the last / character */
 34371  34587     for( i=(len-1); i>=0; i-- ){
 34372  34588       if( conchPath[i]=='/' ){
 34373  34589         i++;
................................................................................
 34475  34691     }
 34476  34692     
 34477  34693     OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
 34478  34694              (lockPath ? lockPath : ":auto:"), osGetpid(0)));
 34479  34695   
 34480  34696     pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 34481  34697     if( pCtx==0 ){
 34482         -    return SQLITE_NOMEM;
        34698  +    return SQLITE_NOMEM_BKPT;
 34483  34699     }
 34484  34700     memset(pCtx, 0, sizeof(*pCtx));
 34485  34701   
 34486  34702     rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
 34487  34703     if( rc==SQLITE_OK ){
 34488  34704       rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
 34489  34705       if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
................................................................................
 34511  34727     if( rc==SQLITE_OK && lockPath ){
 34512  34728       pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
 34513  34729     }
 34514  34730   
 34515  34731     if( rc==SQLITE_OK ){
 34516  34732       pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
 34517  34733       if( pCtx->dbPath==NULL ){
 34518         -      rc = SQLITE_NOMEM;
        34734  +      rc = SQLITE_NOMEM_BKPT;
 34519  34735       }
 34520  34736     }
 34521  34737     if( rc==SQLITE_OK ){
 34522  34738       /* all memory is allocated, proxys are created and assigned, 
 34523  34739       ** switch the locking context and pMethod then return.
 34524  34740       */
 34525  34741       pCtx->oldLockingContext = pFile->lockingContext;
................................................................................
 36287  36503   #endif
 36288  36504   #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 36289  36505     if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
 36290  36506       DWORD lastErrno = osGetLastError();
 36291  36507       if( lastErrno==NO_ERROR ){
 36292  36508         sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
 36293  36509                     (void*)hHeap);
 36294         -      rc = SQLITE_NOMEM;
        36510  +      rc = SQLITE_NOMEM_BKPT;
 36295  36511       }else{
 36296  36512         sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
 36297  36513                     osGetLastError(), (void*)hHeap);
 36298  36514         rc = SQLITE_ERROR;
 36299  36515       }
 36300  36516     }
 36301  36517   #else
................................................................................
 36607  36823       pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
 36608  36824                                         dwInitialSize, dwMaximumSize);
 36609  36825       if( !pWinMemData->hHeap ){
 36610  36826         sqlite3_log(SQLITE_NOMEM,
 36611  36827             "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
 36612  36828             osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
 36613  36829             dwMaximumSize);
 36614         -      return SQLITE_NOMEM;
        36830  +      return SQLITE_NOMEM_BKPT;
 36615  36831       }
 36616  36832       pWinMemData->bOwned = TRUE;
 36617  36833       assert( pWinMemData->bOwned );
 36618  36834     }
 36619  36835   #else
 36620  36836     pWinMemData->hHeap = osGetProcessHeap();
 36621  36837     if( !pWinMemData->hHeap ){
 36622  36838       sqlite3_log(SQLITE_NOMEM,
 36623  36839           "failed to GetProcessHeap (%lu)", osGetLastError());
 36624         -    return SQLITE_NOMEM;
        36840  +    return SQLITE_NOMEM_BKPT;
 36625  36841     }
 36626  36842     pWinMemData->bOwned = FALSE;
 36627  36843     assert( !pWinMemData->bOwned );
 36628  36844   #endif
 36629  36845     assert( pWinMemData->hHeap!=0 );
 36630  36846     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 36631  36847   #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
................................................................................
 36854  37070     );
 36855  37071     assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
 36856  37072     if( ppDirectory ){
 36857  37073       char *zValueUtf8 = 0;
 36858  37074       if( zValue && zValue[0] ){
 36859  37075         zValueUtf8 = winUnicodeToUtf8(zValue);
 36860  37076         if ( zValueUtf8==0 ){
 36861         -        return SQLITE_NOMEM;
        37077  +        return SQLITE_NOMEM_BKPT;
 36862  37078         }
 36863  37079       }
 36864  37080       sqlite3_free(*ppDirectory);
 36865  37081       *ppDirectory = zValueUtf8;
 36866  37082       return SQLITE_OK;
 36867  37083     }
 36868  37084     return SQLITE_ERROR;
................................................................................
 37131  37347     DWORD lastErrno;
 37132  37348     BOOL bLogged = FALSE;
 37133  37349     BOOL bInit = TRUE;
 37134  37350   
 37135  37351     zName = winUtf8ToUnicode(zFilename);
 37136  37352     if( zName==0 ){
 37137  37353       /* out of memory */
 37138         -    return SQLITE_IOERR_NOMEM;
        37354  +    return SQLITE_IOERR_NOMEM_BKPT;
 37139  37355     }
 37140  37356   
 37141  37357     /* Initialize the local lockdata */
 37142  37358     memset(&pFile->local, 0, sizeof(pFile->local));
 37143  37359   
 37144  37360     /* Replace the backslashes from the filename and lowercase it
 37145  37361     ** to derive a mutex name. */
................................................................................
 38322  38538     OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
 38323  38539     switch( op ){
 38324  38540       case SQLITE_FCNTL_LOCKSTATE: {
 38325  38541         *(int*)pArg = pFile->locktype;
 38326  38542         OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 38327  38543         return SQLITE_OK;
 38328  38544       }
 38329         -    case SQLITE_LAST_ERRNO: {
        38545  +    case SQLITE_FCNTL_LAST_ERRNO: {
 38330  38546         *(int*)pArg = (int)pFile->lastErrno;
 38331  38547         OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 38332  38548         return SQLITE_OK;
 38333  38549       }
 38334  38550       case SQLITE_FCNTL_CHUNK_SIZE: {
 38335  38551         pFile->szChunk = *(int *)pArg;
 38336  38552         OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
................................................................................
 38680  38896   
 38681  38897     assert( pDbFd->pShm==0 );    /* Not previously opened */
 38682  38898   
 38683  38899     /* Allocate space for the new sqlite3_shm object.  Also speculatively
 38684  38900     ** allocate space for a new winShmNode and filename.
 38685  38901     */
 38686  38902     p = sqlite3MallocZero( sizeof(*p) );
 38687         -  if( p==0 ) return SQLITE_IOERR_NOMEM;
        38903  +  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
 38688  38904     nName = sqlite3Strlen30(pDbFd->zPath);
 38689  38905     pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
 38690  38906     if( pNew==0 ){
 38691  38907       sqlite3_free(p);
 38692         -    return SQLITE_IOERR_NOMEM;
        38908  +    return SQLITE_IOERR_NOMEM_BKPT;
 38693  38909     }
 38694  38910     pNew->zFilename = (char*)&pNew[1];
 38695  38911     sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
 38696  38912     sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
 38697  38913   
 38698  38914     /* Look to see if there is an existing winShmNode that can be used.
 38699  38915     ** If no matching winShmNode currently exists, create a new one.
................................................................................
 38712  38928       pNew = 0;
 38713  38929       ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
 38714  38930       pShmNode->pNext = winShmNodeList;
 38715  38931       winShmNodeList = pShmNode;
 38716  38932   
 38717  38933       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 38718  38934       if( pShmNode->mutex==0 ){
 38719         -      rc = SQLITE_IOERR_NOMEM;
        38935  +      rc = SQLITE_IOERR_NOMEM_BKPT;
 38720  38936         goto shm_open_err;
 38721  38937       }
 38722  38938   
 38723  38939       rc = winOpen(pDbFd->pVfs,
 38724  38940                    pShmNode->zFilename,             /* Name of the file (UTF-8) */
 38725  38941                    (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
 38726  38942                    SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
................................................................................
 39017  39233       }
 39018  39234   
 39019  39235       /* Map the requested memory region into this processes address space. */
 39020  39236       apNew = (struct ShmRegion *)sqlite3_realloc64(
 39021  39237           pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
 39022  39238       );
 39023  39239       if( !apNew ){
 39024         -      rc = SQLITE_IOERR_NOMEM;
        39240  +      rc = SQLITE_IOERR_NOMEM_BKPT;
 39025  39241         goto shmpage_out;
 39026  39242       }
 39027  39243       pShmNode->aRegion = apNew;
 39028  39244   
 39029  39245       while( pShmNode->nRegion<=iRegion ){
 39030  39246         HANDLE hMap = NULL;         /* file-mapping handle */
 39031  39247         void *pMap = 0;             /* Mapped memory region */
................................................................................
 39447  39663     /* Allocate a temporary buffer to store the fully qualified file
 39448  39664     ** name for the temporary file.  If this fails, we cannot continue.
 39449  39665     */
 39450  39666     nMax = pVfs->mxPathname; nBuf = nMax + 2;
 39451  39667     zBuf = sqlite3MallocZero( nBuf );
 39452  39668     if( !zBuf ){
 39453  39669       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39454         -    return SQLITE_IOERR_NOMEM;
        39670  +    return SQLITE_IOERR_NOMEM_BKPT;
 39455  39671     }
 39456  39672   
 39457  39673     /* Figure out the effective temporary directory.  First, check if one
 39458  39674     ** has been explicitly set by the application; otherwise, use the one
 39459  39675     ** configured by the operating system.
 39460  39676     */
 39461  39677     nDir = nMax - (nPre + 15);
................................................................................
 39505  39721         ** prior to using it.
 39506  39722         */
 39507  39723         if( winIsDriveLetterAndColon(zDir) ){
 39508  39724           zConverted = winConvertFromUtf8Filename(zDir);
 39509  39725           if( !zConverted ){
 39510  39726             sqlite3_free(zBuf);
 39511  39727             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39512         -          return SQLITE_IOERR_NOMEM;
        39728  +          return SQLITE_IOERR_NOMEM_BKPT;
 39513  39729           }
 39514  39730           if( winIsDir(zConverted) ){
 39515  39731             sqlite3_snprintf(nMax, zBuf, "%s", zDir);
 39516  39732             sqlite3_free(zConverted);
 39517  39733             break;
 39518  39734           }
 39519  39735           sqlite3_free(zConverted);
 39520  39736         }else{
 39521  39737           zConverted = sqlite3MallocZero( nMax+1 );
 39522  39738           if( !zConverted ){
 39523  39739             sqlite3_free(zBuf);
 39524  39740             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39525         -          return SQLITE_IOERR_NOMEM;
        39741  +          return SQLITE_IOERR_NOMEM_BKPT;
 39526  39742           }
 39527  39743           if( cygwin_conv_path(
 39528  39744                   osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
 39529  39745                   zConverted, nMax+1)<0 ){
 39530  39746             sqlite3_free(zConverted);
 39531  39747             sqlite3_free(zBuf);
 39532  39748             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
................................................................................
 39539  39755             ** its name into UTF-8 (i.e. if it is UTF-16 right now).
 39540  39756             */
 39541  39757             char *zUtf8 = winConvertToUtf8Filename(zConverted);
 39542  39758             if( !zUtf8 ){
 39543  39759               sqlite3_free(zConverted);
 39544  39760               sqlite3_free(zBuf);
 39545  39761               OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39546         -            return SQLITE_IOERR_NOMEM;
        39762  +            return SQLITE_IOERR_NOMEM_BKPT;
 39547  39763             }
 39548  39764             sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 39549  39765             sqlite3_free(zUtf8);
 39550  39766             sqlite3_free(zConverted);
 39551  39767             break;
 39552  39768           }
 39553  39769           sqlite3_free(zConverted);
................................................................................
 39557  39773   #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 39558  39774     else if( osIsNT() ){
 39559  39775       char *zMulti;
 39560  39776       LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
 39561  39777       if( !zWidePath ){
 39562  39778         sqlite3_free(zBuf);
 39563  39779         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39564         -      return SQLITE_IOERR_NOMEM;
        39780  +      return SQLITE_IOERR_NOMEM_BKPT;
 39565  39781       }
 39566  39782       if( osGetTempPathW(nMax, zWidePath)==0 ){
 39567  39783         sqlite3_free(zWidePath);
 39568  39784         sqlite3_free(zBuf);
 39569  39785         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 39570  39786         return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 39571  39787                            "winGetTempname2", 0);
................................................................................
 39575  39791         sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
 39576  39792         sqlite3_free(zMulti);
 39577  39793         sqlite3_free(zWidePath);
 39578  39794       }else{
 39579  39795         sqlite3_free(zWidePath);
 39580  39796         sqlite3_free(zBuf);
 39581  39797         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39582         -      return SQLITE_IOERR_NOMEM;
        39798  +      return SQLITE_IOERR_NOMEM_BKPT;
 39583  39799       }
 39584  39800     }
 39585  39801   #ifdef SQLITE_WIN32_HAS_ANSI
 39586  39802     else{
 39587  39803       char *zUtf8;
 39588  39804       char *zMbcsPath = sqlite3MallocZero( nMax );
 39589  39805       if( !zMbcsPath ){
 39590  39806         sqlite3_free(zBuf);
 39591  39807         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39592         -      return SQLITE_IOERR_NOMEM;
        39808  +      return SQLITE_IOERR_NOMEM_BKPT;
 39593  39809       }
 39594  39810       if( osGetTempPathA(nMax, zMbcsPath)==0 ){
 39595  39811         sqlite3_free(zBuf);
 39596  39812         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 39597  39813         return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 39598  39814                            "winGetTempname3", 0);
 39599  39815       }
................................................................................
 39600  39816       zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
 39601  39817       if( zUtf8 ){
 39602  39818         sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 39603  39819         sqlite3_free(zUtf8);
 39604  39820       }else{
 39605  39821         sqlite3_free(zBuf);
 39606  39822         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 39607         -      return SQLITE_IOERR_NOMEM;
        39823  +      return SQLITE_IOERR_NOMEM_BKPT;
 39608  39824       }
 39609  39825     }
 39610  39826   #endif /* SQLITE_WIN32_HAS_ANSI */
 39611  39827   #endif /* !SQLITE_OS_WINRT */
 39612  39828   
 39613  39829     /*
 39614  39830     ** Check to make sure the temporary directory ends with an appropriate
................................................................................
 39792  40008          zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
 39793  40009   
 39794  40010     /* Convert the filename to the system encoding. */
 39795  40011     zConverted = winConvertFromUtf8Filename(zUtf8Name);
 39796  40012     if( zConverted==0 ){
 39797  40013       sqlite3_free(zTmpname);
 39798  40014       OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
 39799         -    return SQLITE_IOERR_NOMEM;
        40015  +    return SQLITE_IOERR_NOMEM_BKPT;
 39800  40016     }
 39801  40017   
 39802  40018     if( winIsDir(zConverted) ){
 39803  40019       sqlite3_free(zConverted);
 39804  40020       sqlite3_free(zTmpname);
 39805  40021       OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
 39806  40022       return SQLITE_CANTOPEN_ISDIR;
................................................................................
 39992  40208   
 39993  40209     SimulateIOError(return SQLITE_IOERR_DELETE);
 39994  40210     OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
 39995  40211   
 39996  40212     zConverted = winConvertFromUtf8Filename(zFilename);
 39997  40213     if( zConverted==0 ){
 39998  40214       OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 39999         -    return SQLITE_IOERR_NOMEM;
        40215  +    return SQLITE_IOERR_NOMEM_BKPT;
 40000  40216     }
 40001  40217     if( osIsNT() ){
 40002  40218       do {
 40003  40219   #if SQLITE_OS_WINRT
 40004  40220         WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 40005  40221         memset(&sAttrData, 0, sizeof(sAttrData));
 40006  40222         if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
................................................................................
 40100  40316     SimulateIOError( return SQLITE_IOERR_ACCESS; );
 40101  40317     OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
 40102  40318              zFilename, flags, pResOut));
 40103  40319   
 40104  40320     zConverted = winConvertFromUtf8Filename(zFilename);
 40105  40321     if( zConverted==0 ){
 40106  40322       OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 40107         -    return SQLITE_IOERR_NOMEM;
        40323  +    return SQLITE_IOERR_NOMEM_BKPT;
 40108  40324     }
 40109  40325     if( osIsNT() ){
 40110  40326       int cnt = 0;
 40111  40327       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 40112  40328       memset(&sAttrData, 0, sizeof(sAttrData));
 40113  40329       while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 40114  40330                                GetFileExInfoStandard,
................................................................................
 40227  40443       ** NOTE: We are dealing with a relative path name and the data
 40228  40444       **       directory has been set.  Therefore, use it as the basis
 40229  40445       **       for converting the relative path name to an absolute
 40230  40446       **       one by prepending the data directory and a slash.
 40231  40447       */
 40232  40448       char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 40233  40449       if( !zOut ){
 40234         -      return SQLITE_IOERR_NOMEM;
        40450  +      return SQLITE_IOERR_NOMEM_BKPT;
 40235  40451       }
 40236  40452       if( cygwin_conv_path(
 40237  40453               (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
 40238  40454               CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
 40239  40455         sqlite3_free(zOut);
 40240  40456         return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 40241  40457                            "winFullPathname1", zRelative);
 40242  40458       }else{
 40243  40459         char *zUtf8 = winConvertToUtf8Filename(zOut);
 40244  40460         if( !zUtf8 ){
 40245  40461           sqlite3_free(zOut);
 40246         -        return SQLITE_IOERR_NOMEM;
        40462  +        return SQLITE_IOERR_NOMEM_BKPT;
 40247  40463         }
 40248  40464         sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 40249  40465                          sqlite3_data_directory, winGetDirSep(), zUtf8);
 40250  40466         sqlite3_free(zUtf8);
 40251  40467         sqlite3_free(zOut);
 40252  40468       }
 40253  40469     }else{
 40254  40470       char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 40255  40471       if( !zOut ){
 40256         -      return SQLITE_IOERR_NOMEM;
        40472  +      return SQLITE_IOERR_NOMEM_BKPT;
 40257  40473       }
 40258  40474       if( cygwin_conv_path(
 40259  40475               (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
 40260  40476               zRelative, zOut, pVfs->mxPathname+1)<0 ){
 40261  40477         sqlite3_free(zOut);
 40262  40478         return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 40263  40479                            "winFullPathname2", zRelative);
 40264  40480       }else{
 40265  40481         char *zUtf8 = winConvertToUtf8Filename(zOut);
 40266  40482         if( !zUtf8 ){
 40267  40483           sqlite3_free(zOut);
 40268         -        return SQLITE_IOERR_NOMEM;
        40484  +        return SQLITE_IOERR_NOMEM_BKPT;
 40269  40485         }
 40270  40486         sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
 40271  40487         sqlite3_free(zUtf8);
 40272  40488         sqlite3_free(zOut);
 40273  40489       }
 40274  40490     }
 40275  40491     return SQLITE_OK;
................................................................................
 40321  40537       */
 40322  40538       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 40323  40539                        sqlite3_data_directory, winGetDirSep(), zRelative);
 40324  40540       return SQLITE_OK;
 40325  40541     }
 40326  40542     zConverted = winConvertFromUtf8Filename(zRelative);
 40327  40543     if( zConverted==0 ){
 40328         -    return SQLITE_IOERR_NOMEM;
        40544  +    return SQLITE_IOERR_NOMEM_BKPT;
 40329  40545     }
 40330  40546     if( osIsNT() ){
 40331  40547       LPWSTR zTemp;
 40332  40548       nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
 40333  40549       if( nByte==0 ){
 40334  40550         sqlite3_free(zConverted);
 40335  40551         return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 40336  40552                            "winFullPathname1", zRelative);
 40337  40553       }
 40338  40554       nByte += 3;
 40339  40555       zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 40340  40556       if( zTemp==0 ){
 40341  40557         sqlite3_free(zConverted);
 40342         -      return SQLITE_IOERR_NOMEM;
        40558  +      return SQLITE_IOERR_NOMEM_BKPT;
 40343  40559       }
 40344  40560       nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
 40345  40561       if( nByte==0 ){
 40346  40562         sqlite3_free(zConverted);
 40347  40563         sqlite3_free(zTemp);
 40348  40564         return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 40349  40565                            "winFullPathname2", zRelative);
................................................................................
 40361  40577         return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 40362  40578                            "winFullPathname3", zRelative);
 40363  40579       }
 40364  40580       nByte += 3;
 40365  40581       zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 40366  40582       if( zTemp==0 ){
 40367  40583         sqlite3_free(zConverted);
 40368         -      return SQLITE_IOERR_NOMEM;
        40584  +      return SQLITE_IOERR_NOMEM_BKPT;
 40369  40585       }
 40370  40586       nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
 40371  40587       if( nByte==0 ){
 40372  40588         sqlite3_free(zConverted);
 40373  40589         sqlite3_free(zTemp);
 40374  40590         return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 40375  40591                            "winFullPathname4", zRelative);
................................................................................
 40380  40596     }
 40381  40597   #endif
 40382  40598     if( zOut ){
 40383  40599       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
 40384  40600       sqlite3_free(zOut);
 40385  40601       return SQLITE_OK;
 40386  40602     }else{
 40387         -    return SQLITE_IOERR_NOMEM;
        40603  +    return SQLITE_IOERR_NOMEM_BKPT;
 40388  40604     }
 40389  40605   #endif
 40390  40606   }
 40391  40607   
 40392  40608   #ifndef SQLITE_OMIT_LOAD_EXTENSION
 40393  40609   /*
 40394  40610   ** Interfaces for opening a shared library, finding entry points
................................................................................
 40455  40671   #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 40456  40672     #define winDlOpen  0
 40457  40673     #define winDlError 0
 40458  40674     #define winDlSym   0
 40459  40675     #define winDlClose 0
 40460  40676   #endif
 40461  40677   
        40678  +/* State information for the randomness gatherer. */
        40679  +typedef struct EntropyGatherer EntropyGatherer;
        40680  +struct EntropyGatherer {
        40681  +  unsigned char *a;   /* Gather entropy into this buffer */
        40682  +  int na;             /* Size of a[] in bytes */
        40683  +  int i;              /* XOR next input into a[i] */
        40684  +  int nXor;           /* Number of XOR operations done */
        40685  +};
        40686  +
        40687  +#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
        40688  +/* Mix sz bytes of entropy into p. */
        40689  +static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
        40690  +  int j, k;
        40691  +  for(j=0, k=p->i; j<sz; j++){
        40692  +    p->a[k++] ^= x[j];
        40693  +    if( k>=p->na ) k = 0;
        40694  +  }
        40695  +  p->i = k;
        40696  +  p->nXor += sz;
        40697  +}
        40698  +#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
 40462  40699   
 40463  40700   /*
 40464  40701   ** Write up to nBuf bytes of randomness into zBuf.
 40465  40702   */
 40466  40703   static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 40467         -  int n = 0;
 40468         -  UNUSED_PARAMETER(pVfs);
 40469  40704   #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
 40470         -  n = nBuf;
        40705  +  UNUSED_PARAMETER(pVfs);
        40706  +  memset(zBuf, 0, nBuf);
        40707  +  return nBuf;
        40708  +#else
        40709  +  EntropyGatherer e;
        40710  +  UNUSED_PARAMETER(pVfs);
 40471  40711     memset(zBuf, 0, nBuf);
 40472         -#else
 40473         -  if( sizeof(SYSTEMTIME)<=nBuf-n ){
        40712  +#if defined(_MSC_VER) && _MSC_VER>=1400
        40713  +  rand_s((int*)zBuf); /* rand_s() is not available with MinGW */
        40714  +#endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
        40715  +  e.a = (unsigned char*)zBuf;
        40716  +  e.na = nBuf;
        40717  +  e.nXor = 0;
        40718  +  e.i = 0;
        40719  +  {
 40474  40720       SYSTEMTIME x;
 40475  40721       osGetSystemTime(&x);
 40476         -    memcpy(&zBuf[n], &x, sizeof(x));
 40477         -    n += sizeof(x);
        40722  +    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
 40478  40723     }
 40479         -  if( sizeof(DWORD)<=nBuf-n ){
        40724  +  {
 40480  40725       DWORD pid = osGetCurrentProcessId();
 40481         -    memcpy(&zBuf[n], &pid, sizeof(pid));
 40482         -    n += sizeof(pid);
        40726  +    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
 40483  40727     }
 40484  40728   #if SQLITE_OS_WINRT
 40485         -  if( sizeof(ULONGLONG)<=nBuf-n ){
        40729  +  {
 40486  40730       ULONGLONG cnt = osGetTickCount64();
 40487         -    memcpy(&zBuf[n], &cnt, sizeof(cnt));
 40488         -    n += sizeof(cnt);
        40731  +    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
 40489  40732     }
 40490  40733   #else
 40491         -  if( sizeof(DWORD)<=nBuf-n ){
        40734  +  {
 40492  40735       DWORD cnt = osGetTickCount();
 40493         -    memcpy(&zBuf[n], &cnt, sizeof(cnt));
 40494         -    n += sizeof(cnt);
        40736  +    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
 40495  40737     }
 40496         -#endif
 40497         -  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
        40738  +#endif /* SQLITE_OS_WINRT */
        40739  +  {
 40498  40740       LARGE_INTEGER i;
 40499  40741       osQueryPerformanceCounter(&i);
 40500         -    memcpy(&zBuf[n], &i, sizeof(i));
 40501         -    n += sizeof(i);
        40742  +    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
 40502  40743     }
 40503  40744   #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 40504         -  if( sizeof(UUID)<=nBuf-n ){
        40745  +  {
 40505  40746       UUID id;
 40506  40747       memset(&id, 0, sizeof(UUID));
 40507  40748       osUuidCreate(&id);
 40508         -    memcpy(&zBuf[n], &id, sizeof(UUID));
 40509         -    n += sizeof(UUID);
 40510         -  }
 40511         -  if( sizeof(UUID)<=nBuf-n ){
 40512         -    UUID id;
        40749  +    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 40513  40750       memset(&id, 0, sizeof(UUID));
 40514  40751       osUuidCreateSequential(&id);
 40515         -    memcpy(&zBuf[n], &id, sizeof(UUID));
 40516         -    n += sizeof(UUID);
        40752  +    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 40517  40753     }
 40518         -#endif
 40519         -#endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
 40520         -  return n;
        40754  +#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
        40755  +  return e.nXor>nBuf ? nBuf : e.nXor;
        40756  +#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
 40521  40757   }
 40522  40758   
 40523  40759   
 40524  40760   /*
 40525  40761   ** Sleep for a little while.  Return the amount of time slept.
 40526  40762   */
 40527  40763   static int winSleep(sqlite3_vfs *pVfs, int microsec){
................................................................................
 40629  40865   **   }
 40630  40866   **
 40631  40867   ** However if an error message is supplied, it will be incorporated
 40632  40868   ** by sqlite into the error message available to the user using
 40633  40869   ** sqlite3_errmsg(), possibly making IO errors easier to debug.
 40634  40870   */
 40635  40871   static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
        40872  +  DWORD e = osGetLastError();
 40636  40873     UNUSED_PARAMETER(pVfs);
 40637         -  return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
        40874  +  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
        40875  +  return e;
 40638  40876   }
 40639  40877   
 40640  40878   /*
 40641  40879   ** Initialize and deinitialize the operating system interface.
 40642  40880   */
 40643  40881   SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
 40644  40882     static sqlite3_vfs winVfs = {
................................................................................
 40904  41142     assert( i<=p->iSize );
 40905  41143     i--;
 40906  41144     while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
 40907  41145       u32 bin = i/p->iDivisor;
 40908  41146       i = i%p->iDivisor;
 40909  41147       if( p->u.apSub[bin]==0 ){
 40910  41148         p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
 40911         -      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
        41149  +      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
 40912  41150       }
 40913  41151       p = p->u.apSub[bin];
 40914  41152     }
 40915  41153     if( p->iSize<=BITVEC_NBIT ){
 40916  41154       p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
 40917  41155       return SQLITE_OK;
 40918  41156     }
................................................................................
 40939  41177     /* make our hash too "full".  */
 40940  41178   bitvec_set_rehash:
 40941  41179     if( p->nSet>=BITVEC_MXHASH ){
 40942  41180       unsigned int j;
 40943  41181       int rc;
 40944  41182       u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
 40945  41183       if( aiValues==0 ){
 40946         -      return SQLITE_NOMEM;
        41184  +      return SQLITE_NOMEM_BKPT;
 40947  41185       }else{
 40948  41186         memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 40949  41187         memset(p->u.apSub, 0, sizeof(p->u.apSub));
 40950  41188         p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
 40951  41189         rc = sqlite3BitvecSet(p, i);
 40952  41190         for(j=0; j<BITVEC_NINT; j++){
 40953  41191           if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
................................................................................
 41332  41570     assert( pCache->nRefSum==0 && pCache->pDirty==0 );
 41333  41571     if( pCache->szPage ){
 41334  41572       sqlite3_pcache *pNew;
 41335  41573       pNew = sqlite3GlobalConfig.pcache2.xCreate(
 41336  41574                   szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
 41337  41575                   pCache->bPurgeable
 41338  41576       );
 41339         -    if( pNew==0 ) return SQLITE_NOMEM;
        41577  +    if( pNew==0 ) return SQLITE_NOMEM_BKPT;
 41340  41578       sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
 41341  41579       if( pCache->pCache ){
 41342  41580         sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 41343  41581       }
 41344  41582       pCache->pCache = pNew;
 41345  41583       pCache->szPage = szPage;
 41346  41584     }
................................................................................
 41442  41680         rc = pCache->xStress(pCache->pStress, pPg);
 41443  41681         if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
 41444  41682           return rc;
 41445  41683         }
 41446  41684       }
 41447  41685     }
 41448  41686     *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
 41449         -  return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
        41687  +  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
 41450  41688   }
 41451  41689   
 41452  41690   /*
 41453  41691   ** This is a helper routine for sqlite3PcacheFetchFinish()
 41454  41692   **
 41455  41693   ** In the uncommon case where the page being fetched has not been
 41456  41694   ** initialized, this routine is invoked to do the initialization.
................................................................................
 42183  42421     return p;
 42184  42422   }
 42185  42423   
 42186  42424   /*
 42187  42425   ** Free an allocated buffer obtained from pcache1Alloc().
 42188  42426   */
 42189  42427   static void pcache1Free(void *p){
 42190         -  int nFreed = 0;
 42191  42428     if( p==0 ) return;
 42192  42429     if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
 42193  42430       PgFreeslot *pSlot;
 42194  42431       sqlite3_mutex_enter(pcache1.mutex);
 42195  42432       sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
 42196  42433       pSlot = (PgFreeslot*)p;
 42197  42434       pSlot->pNext = pcache1.pFree;
................................................................................
 42200  42437       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 42201  42438       assert( pcache1.nFreeSlot<=pcache1.nSlot );
 42202  42439       sqlite3_mutex_leave(pcache1.mutex);
 42203  42440     }else{
 42204  42441       assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 42205  42442       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 42206  42443   #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 42207         -    nFreed = sqlite3MallocSize(p);
 42208         -    sqlite3_mutex_enter(pcache1.mutex);
 42209         -    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
 42210         -    sqlite3_mutex_leave(pcache1.mutex);
        42444  +    {
        42445  +      int nFreed = 0;
        42446  +      nFreed = sqlite3MallocSize(p);
        42447  +      sqlite3_mutex_enter(pcache1.mutex);
        42448  +      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
        42449  +      sqlite3_mutex_leave(pcache1.mutex);
        42450  +    }
 42211  42451   #endif
 42212  42452       sqlite3_free(p);
 42213  42453     }
 42214  42454   }
 42215  42455   
 42216  42456   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 42217  42457   /*
................................................................................
 44162  44402   ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
 44163  44403   ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 44164  44404   ** This could conceivably cause corruption following a power failure on
 44165  44405   ** such a system. This is currently an undocumented limit.
 44166  44406   */
 44167  44407   #define MAX_SECTOR_SIZE 0x10000
 44168  44408   
 44169         -/*
 44170         -** If the option SQLITE_EXTRA_DURABLE option is set at compile-time, then
 44171         -** SQLite will do extra fsync() operations when synchronous==FULL to help
 44172         -** ensure that transactions are durable across a power failure.  Most
 44173         -** applications are happy as long as transactions are consistent across
 44174         -** a power failure, and are perfectly willing to lose the last transaction
 44175         -** in exchange for the extra performance of avoiding directory syncs.
 44176         -** And so the default SQLITE_EXTRA_DURABLE setting is off.
 44177         -*/
 44178         -#ifndef SQLITE_EXTRA_DURABLE
 44179         -# define SQLITE_EXTRA_DURABLE 0
 44180         -#endif
 44181         -
 44182  44409   
 44183  44410   /*
 44184  44411   ** An instance of the following structure is allocated for each active
 44185  44412   ** savepoint and statement transaction in the system. All such structures
 44186  44413   ** are stored in the Pager.aSavepoint[] array, which is allocated and
 44187  44414   ** resized using sqlite3Realloc().
 44188  44415   **
................................................................................
 45077  45304   **
 45078  45305   ** If an IO error occurs, abandon processing and return the IO error code.
 45079  45306   ** Otherwise, return SQLITE_OK.
 45080  45307   */
 45081  45308   static int zeroJournalHdr(Pager *pPager, int doTruncate){
 45082  45309     int rc = SQLITE_OK;                               /* Return code */
 45083  45310     assert( isOpen(pPager->jfd) );
        45311  +  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
 45084  45312     if( pPager->journalOff ){
 45085  45313       const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
 45086  45314   
 45087  45315       IOTRACE(("JZEROHDR %p\n", pPager))
 45088  45316       if( doTruncate || iLimit==0 ){
 45089  45317         rc = sqlite3OsTruncate(pPager->jfd, 0);
 45090  45318       }else{
................................................................................
 45458  45686   ** if it is open and the pager is not in exclusive mode.
 45459  45687   */
 45460  45688   static void releaseAllSavepoints(Pager *pPager){
 45461  45689     int ii;               /* Iterator for looping through Pager.aSavepoint */
 45462  45690     for(ii=0; ii<pPager->nSavepoint; ii++){
 45463  45691       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 45464  45692     }
 45465         -  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
        45693  +  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
 45466  45694       sqlite3OsClose(pPager->sjfd);
 45467  45695     }
 45468  45696     sqlite3_free(pPager->aSavepoint);
 45469  45697     pPager->aSavepoint = 0;
 45470  45698     pPager->nSavepoint = 0;
 45471  45699     pPager->nSubRec = 0;
 45472  45700   }
................................................................................
 45696  45924   
 45697  45925     releaseAllSavepoints(pPager);
 45698  45926     assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
 45699  45927     if( isOpen(pPager->jfd) ){
 45700  45928       assert( !pagerUseWal(pPager) );
 45701  45929   
 45702  45930       /* Finalize the journal file. */
 45703         -    if( sqlite3IsMemJournal(pPager->jfd) ){
 45704         -      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
        45931  +    if( sqlite3JournalIsInMemory(pPager->jfd) ){
        45932  +      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
 45705  45933         sqlite3OsClose(pPager->jfd);
 45706  45934       }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
 45707  45935         if( pPager->journalOff==0 ){
 45708  45936           rc = SQLITE_OK;
 45709  45937         }else{
 45710  45938           rc = sqlite3OsTruncate(pPager->jfd, 0);
 45711  45939           if( rc==SQLITE_OK && pPager->fullSync ){
................................................................................
 45723  45951       ){
 45724  45952         rc = zeroJournalHdr(pPager, hasMaster);
 45725  45953         pPager->journalOff = 0;
 45726  45954       }else{
 45727  45955         /* This branch may be executed with Pager.journalMode==MEMORY if
 45728  45956         ** a hot-journal was just rolled back. In this case the journal
 45729  45957         ** file should be closed and deleted. If this connection writes to
 45730         -      ** the database file, it will do so using an in-memory journal. 
        45958  +      ** the database file, it will do so using an in-memory journal.
 45731  45959         */
 45732         -      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
        45960  +      int bDelete = !pPager->tempFile;
        45961  +      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
 45733  45962         assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
 45734  45963              || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 45735  45964              || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 45736  45965         );
 45737  45966         sqlite3OsClose(pPager->jfd);
 45738  45967         if( bDelete ){
 45739  45968           rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
................................................................................
 46058  46287       testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
 46059  46288       assert( !pagerUseWal(pPager) );
 46060  46289       rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 46061  46290       if( pgno>pPager->dbFileSize ){
 46062  46291         pPager->dbFileSize = pgno;
 46063  46292       }
 46064  46293       if( pPager->pBackup ){
 46065         -      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
        46294  +      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
 46066  46295         sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 46067         -      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
        46296  +      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
 46068  46297       }
 46069  46298     }else if( !isMainJrnl && pPg==0 ){
 46070  46299       /* If this is a rollback of a savepoint and data was not written to
 46071  46300       ** the database and the page is not in-memory, there is a potential
 46072  46301       ** problem. When the page is next fetched by the b-tree layer, it 
 46073  46302       ** will be read from the database file, which may or may not be 
 46074  46303       ** current. 
................................................................................
 46132  46361       /* If this was page 1, then restore the value of Pager.dbFileVers.
 46133  46362       ** Do this before any decoding. */
 46134  46363       if( pgno==1 ){
 46135  46364         memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
 46136  46365       }
 46137  46366   
 46138  46367       /* Decode the page just read from disk */
 46139         -    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
        46368  +    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
 46140  46369       sqlite3PcacheRelease(pPg);
 46141  46370     }
 46142  46371     return rc;
 46143  46372   }
 46144  46373   
 46145  46374   /*
 46146  46375   ** Parameter zMaster is the name of a master journal file. A single journal
................................................................................
 46198  46427   
 46199  46428     /* Allocate space for both the pJournal and pMaster file descriptors.
 46200  46429     ** If successful, open the master journal file for reading.
 46201  46430     */
 46202  46431     pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
 46203  46432     pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
 46204  46433     if( !pMaster ){
 46205         -    rc = SQLITE_NOMEM;
        46434  +    rc = SQLITE_NOMEM_BKPT;
 46206  46435     }else{
 46207  46436       const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
 46208  46437       rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
 46209  46438     }
 46210  46439     if( rc!=SQLITE_OK ) goto delmaster_out;
 46211  46440   
 46212  46441     /* Load the entire master journal file into space obtained from
................................................................................
 46215  46444     ** journal files extracted from regular rollback-journals.
 46216  46445     */
 46217  46446     rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
 46218  46447     if( rc!=SQLITE_OK ) goto delmaster_out;
 46219  46448     nMasterPtr = pVfs->mxPathname+1;
 46220  46449     zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
 46221  46450     if( !zMasterJournal ){
 46222         -    rc = SQLITE_NOMEM;
        46451  +    rc = SQLITE_NOMEM_BKPT;
 46223  46452       goto delmaster_out;
 46224  46453     }
 46225  46454     zMasterPtr = &zMasterJournal[nMasterJournal+1];
 46226  46455     rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
 46227  46456     if( rc!=SQLITE_OK ) goto delmaster_out;
 46228  46457     zMasterJournal[nMasterJournal] = 0;
 46229  46458   
................................................................................
 46463  46692     ** If a master journal file name is specified, but the file is not
 46464  46693     ** present on disk, then the journal is not hot and does not need to be
 46465  46694     ** played back.
 46466  46695     **
 46467  46696     ** TODO: Technically the following is an error because it assumes that
 46468  46697     ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
 46469  46698     ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
 46470         -  **  mxPathname is 512, which is the same as the minimum allowable value
        46699  +  ** mxPathname is 512, which is the same as the minimum allowable value
 46471  46700     ** for pageSize.
 46472  46701     */
 46473  46702     zMaster = pPager->pTmpSpace;
 46474  46703     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 46475  46704     if( rc==SQLITE_OK && zMaster[0] ){
 46476  46705       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 46477  46706     }
................................................................................
 46685  46914         */
 46686  46915         memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
 46687  46916       }else{
 46688  46917         u8 *dbFileVers = &((u8*)pPg->pData)[24];
 46689  46918         memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
 46690  46919       }
 46691  46920     }
 46692         -  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
        46921  +  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
 46693  46922   
 46694  46923     PAGER_INCR(sqlite3_pager_readdb_count);
 46695  46924     PAGER_INCR(pPager->nRead);
 46696  46925     IOTRACE(("PGIN %p %d\n", pPager, pgno));
 46697  46926     PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
 46698  46927                  PAGERID(pPager), pgno, pager_pagehash(pPg)));
 46699  46928   
................................................................................
 47045  47274     assert( pPager->eState!=PAGER_ERROR );
 47046  47275     assert( pPager->eState>=PAGER_WRITER_LOCKED );
 47047  47276   
 47048  47277     /* Allocate a bitvec to use to store the set of pages rolled back */
 47049  47278     if( pSavepoint ){
 47050  47279       pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
 47051  47280       if( !pDone ){
 47052         -      return SQLITE_NOMEM;
        47281  +      return SQLITE_NOMEM_BKPT;
 47053  47282       }
 47054  47283     }
 47055  47284   
 47056  47285     /* Set the database size back to the value it was before the savepoint 
 47057  47286     ** being reverted was opened.
 47058  47287     */
 47059  47288     pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
................................................................................
 47192  47421   
 47193  47422   /*
 47194  47423   ** Adjust settings of the pager to those specified in the pgFlags parameter.
 47195  47424   **
 47196  47425   ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
 47197  47426   ** of the database to damage due to OS crashes or power failures by
 47198  47427   ** changing the number of syncs()s when writing the journals.
 47199         -** There are three levels:
        47428  +** There are four levels:
 47200  47429   **
 47201  47430   **    OFF       sqlite3OsSync() is never called.  This is the default
 47202  47431   **              for temporary and transient files.
 47203  47432   **
 47204  47433   **    NORMAL    The journal is synced once before writes begin on the
 47205  47434   **              database.  This is normally adequate protection, but
 47206  47435   **              it is theoretically possible, though very unlikely,
................................................................................
 47211  47440   **    FULL      The journal is synced twice before writes begin on the
 47212  47441   **              database (with some additional information - the nRec field
 47213  47442   **              of the journal header - being written in between the two
 47214  47443   **              syncs).  If we assume that writing a
 47215  47444   **              single disk sector is atomic, then this mode provides
 47216  47445   **              assurance that the journal will not be corrupted to the
 47217  47446   **              point of causing damage to the database during rollback.
        47447  +**
        47448  +**    EXTRA     This is like FULL except that is also syncs the directory
        47449  +**              that contains the rollback journal after the rollback
        47450  +**              journal is unlinked.
 47218  47451   **
 47219  47452   ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
 47220  47453   ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
 47221  47454   ** prior to the start of checkpoint and that the database file is synced
 47222  47455   ** at the conclusion of the checkpoint if the entire content of the WAL
 47223  47456   ** was written back into the database.  But no sync operations occur for
 47224  47457   ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
 47225  47458   ** file is synced following each commit operation, in addition to the
 47226         -** syncs associated with NORMAL.
        47459  +** syncs associated with NORMAL.  There is no difference between FULL
        47460  +** and EXTRA for WAL mode.
 47227  47461   **
 47228  47462   ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
 47229  47463   ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
 47230  47464   ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
 47231  47465   ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
 47232  47466   ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
 47233  47467   ** synchronous=FULL versus synchronous=NORMAL setting determines when
................................................................................
 47408  47642       i64 nByte = 0;
 47409  47643   
 47410  47644       if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
 47411  47645         rc = sqlite3OsFileSize(pPager->fd, &nByte);
 47412  47646       }
 47413  47647       if( rc==SQLITE_OK ){
 47414  47648         pNew = (char *)sqlite3PageMalloc(pageSize);
 47415         -      if( !pNew ) rc = SQLITE_NOMEM;
        47649  +      if( !pNew ) rc = SQLITE_NOMEM_BKPT;
 47416  47650       }
 47417  47651   
 47418  47652       if( rc==SQLITE_OK ){
 47419  47653         pager_reset(pPager);
 47420  47654         rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
 47421  47655       }
 47422  47656       if( rc==SQLITE_OK ){
................................................................................
 47684  47918       pPager->pMmapFreelist = p->pDirty;
 47685  47919       p->pDirty = 0;
 47686  47920       memset(p->pExtra, 0, pPager->nExtra);
 47687  47921     }else{
 47688  47922       *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
 47689  47923       if( p==0 ){
 47690  47924         sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
 47691         -      return SQLITE_NOMEM;
        47925  +      return SQLITE_NOMEM_BKPT;
 47692  47926       }
 47693  47927       p->pExtra = (void *)&p[1];
 47694  47928       p->flags = PGHDR_MMAP;
 47695  47929       p->nRef = 1;
 47696  47930       p->pPager = pPager;
 47697  47931     }
 47698  47932   
................................................................................
 48042  48276         i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
 48043  48277         char *pData;                                   /* Data to write */    
 48044  48278   
 48045  48279         assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
 48046  48280         if( pList->pgno==1 ) pager_write_changecounter(pList);
 48047  48281   
 48048  48282         /* Encode the database */
 48049         -      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
        48283  +      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
 48050  48284   
 48051  48285         /* Write out the page data. */
 48052  48286         rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
 48053  48287   
 48054  48288         /* If page 1 was just written, update Pager.dbFileVers to match
 48055  48289         ** the value now stored in the database file. If writing this 
 48056  48290         ** page caused the database file to grow, update dbFileSize. 
................................................................................
 48087  48321   ** SQLITE_OK is returned if everything goes according to plan. An 
 48088  48322   ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
 48089  48323   ** fails.
 48090  48324   */
 48091  48325   static int openSubJournal(Pager *pPager){
 48092  48326     int rc = SQLITE_OK;
 48093  48327     if( !isOpen(pPager->sjfd) ){
        48328  +    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE 
        48329  +      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE 
        48330  +      | SQLITE_OPEN_DELETEONCLOSE;
        48331  +    int nStmtSpill = sqlite3Config.nStmtSpill;
 48094  48332       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
 48095         -      sqlite3MemJournalOpen(pPager->sjfd);
 48096         -    }else{
 48097         -      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
        48333  +      nStmtSpill = -1;
 48098  48334       }
        48335  +    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
 48099  48336     }
 48100  48337     return rc;
 48101  48338   }
 48102  48339   
 48103  48340   /*
 48104  48341   ** Append a record of the current state of page pPg to the sub-journal. 
 48105  48342   **
................................................................................
 48129  48366       /* If the sub-journal was opened successfully (or was already open),
 48130  48367       ** write the journal record into the file.  */
 48131  48368       if( rc==SQLITE_OK ){
 48132  48369         void *pData = pPg->pData;
 48133  48370         i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
 48134  48371         char *pData2;
 48135  48372     
 48136         -      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
        48373  +      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 48137  48374         PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
 48138  48375         rc = write32bits(pPager->sjfd, offset, pPg->pgno);
 48139  48376         if( rc==SQLITE_OK ){
 48140  48377           rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
 48141  48378         }
 48142  48379       }
 48143  48380     }
................................................................................
 48312  48549     int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
 48313  48550     int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
 48314  48551     u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
 48315  48552     const char *zUri = 0;    /* URI args to copy */
 48316  48553     int nUri = 0;            /* Number of bytes of URI args at *zUri */
 48317  48554   
 48318  48555     /* Figure out how much space is required for each journal file-handle
 48319         -  ** (there are two of them, the main journal and the sub-journal). This
 48320         -  ** is the maximum space required for an in-memory journal file handle 
 48321         -  ** and a regular journal file-handle. Note that a "regular journal-handle"
 48322         -  ** may be a wrapper capable of caching the first portion of the journal
 48323         -  ** file in memory to implement the atomic-write optimization (see 
 48324         -  ** source file journal.c).
 48325         -  */
 48326         -  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
 48327         -    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
 48328         -  }else{
 48329         -    journalFileSize = ROUND8(sqlite3MemJournalSize());
 48330         -  }
        48556  +  ** (there are two of them, the main journal and the sub-journal).  */
        48557  +  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
 48331  48558   
 48332  48559     /* Set the output variable to NULL in case an error occurs. */
 48333  48560     *ppPager = 0;
 48334  48561   
 48335  48562   #ifndef SQLITE_OMIT_MEMORYDB
 48336  48563     if( flags & PAGER_MEMORY ){
 48337  48564       memDb = 1;
 48338  48565       if( zFilename && zFilename[0] ){
 48339  48566         zPathname = sqlite3DbStrDup(0, zFilename);
 48340         -      if( zPathname==0  ) return SQLITE_NOMEM;
        48567  +      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
 48341  48568         nPathname = sqlite3Strlen30(zPathname);
 48342  48569         zFilename = 0;
 48343  48570       }
 48344  48571     }
 48345  48572   #endif
 48346  48573   
 48347  48574     /* Compute and store the full pathname in an allocated buffer pointed
................................................................................
 48349  48576     ** leave both nPathname and zPathname set to 0.
 48350  48577     */
 48351  48578     if( zFilename && zFilename[0] ){
 48352  48579       const char *z;
 48353  48580       nPathname = pVfs->mxPathname+1;
 48354  48581       zPathname = sqlite3DbMallocRaw(0, nPathname*2);
 48355  48582       if( zPathname==0 ){
 48356         -      return SQLITE_NOMEM;
        48583  +      return SQLITE_NOMEM_BKPT;
 48357  48584       }
 48358  48585       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
 48359  48586       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
 48360  48587       nPathname = sqlite3Strlen30(zPathname);
 48361  48588       z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
 48362  48589       while( *z ){
 48363  48590         z += sqlite3Strlen30(z)+1;
................................................................................
 48402  48629   #ifndef SQLITE_OMIT_WAL
 48403  48630       + nPathname + 4 + 2            /* zWal */
 48404  48631   #endif
 48405  48632     );
 48406  48633     assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
 48407  48634     if( !pPtr ){
 48408  48635       sqlite3DbFree(0, zPathname);
 48409         -    return SQLITE_NOMEM;
        48636  +    return SQLITE_NOMEM_BKPT;
 48410  48637     }
 48411  48638     pPager =              (Pager*)(pPtr);
 48412  48639     pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
 48413  48640     pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
 48414  48641     pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
 48415  48642     pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
 48416  48643     pPager->zFilename =    (char*)(pPtr += journalFileSize);
................................................................................
 48557  48784       assert( pPager->fullSync==0 );
 48558  48785       assert( pPager->extraSync==0 );
 48559  48786       assert( pPager->syncFlags==0 );
 48560  48787       assert( pPager->walSyncFlags==0 );
 48561  48788       assert( pPager->ckptSyncFlags==0 );
 48562  48789     }else{
 48563  48790       pPager->fullSync = 1;
 48564         -#if SQLITE_EXTRA_DURABLE
 48565         -    pPager->extraSync = 1;
 48566         -#else
 48567  48791       pPager->extraSync = 0;
 48568         -#endif
 48569  48792       pPager->syncFlags = SQLITE_SYNC_NORMAL;
 48570  48793       pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
 48571  48794       pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
 48572  48795     }
 48573  48796     /* pPager->pFirst = 0; */
 48574  48797     /* pPager->pFirstSynced = 0; */
 48575  48798     /* pPager->pLast = 0; */
................................................................................
 49122  49345         sqlite3_pcache_page *pBase;
 49123  49346         pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
 49124  49347         if( pBase==0 ){
 49125  49348           rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
 49126  49349           if( rc!=SQLITE_OK ) goto pager_acquire_err;
 49127  49350           if( pBase==0 ){
 49128  49351             pPg = *ppPage = 0;
 49129         -          rc = SQLITE_NOMEM;
        49352  +          rc = SQLITE_NOMEM_BKPT;
 49130  49353             goto pager_acquire_err;
 49131  49354           }
 49132  49355         }
 49133  49356         pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
 49134  49357         assert( pPg!=0 );
 49135  49358       }
 49136  49359     }
................................................................................
 49296  49519     ** the other hand, this routine is never called if we are already in
 49297  49520     ** an error state. */
 49298  49521     if( NEVER(pPager->errCode) ) return pPager->errCode;
 49299  49522   
 49300  49523     if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 49301  49524       pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
 49302  49525       if( pPager->pInJournal==0 ){
 49303         -      return SQLITE_NOMEM;
        49526  +      return SQLITE_NOMEM_BKPT;
 49304  49527       }
 49305  49528     
 49306  49529       /* Open the journal file if it is not already open. */
 49307  49530       if( !isOpen(pPager->jfd) ){
 49308  49531         if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
 49309  49532           sqlite3MemJournalOpen(pPager->jfd);
 49310  49533         }else{
................................................................................
 49451  49674   
 49452  49675     /* We should never write to the journal file the page that
 49453  49676     ** contains the database locks.  The following assert verifies
 49454  49677     ** that we do not. */
 49455  49678     assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
 49456  49679   
 49457  49680     assert( pPager->journalHdr<=pPager->journalOff );
 49458         -  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
        49681  +  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 49459  49682     cksum = pager_cksum(pPager, (u8*)pData2);
 49460  49683   
 49461  49684     /* Even if an IO or diskfull error occurs while journalling the
 49462  49685     ** page in the block above, set the need-sync flag for the page.
 49463  49686     ** Otherwise, when the transaction is rolled back, the logic in
 49464  49687     ** playback_one_page() will think that the page needs to be restored
 49465  49688     ** in the database file. And if an IO error occurs while doing so,
................................................................................
 49808  50031         /* Actually do the update of the change counter */
 49809  50032         pager_write_changecounter(pPgHdr);
 49810  50033   
 49811  50034         /* If running in direct mode, write the contents of page 1 to the file. */
 49812  50035         if( DIRECT_MODE ){
 49813  50036           const void *zBuf;
 49814  50037           assert( pPager->dbFileSize>0 );
 49815         -        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
        50038  +        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
 49816  50039           if( rc==SQLITE_OK ){
 49817  50040             rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
 49818  50041             pPager->aStat[PAGER_STAT_WRITE]++;
 49819  50042           }
 49820  50043           if( rc==SQLITE_OK ){
 49821  50044             /* Update the pager's copy of the change-counter. Otherwise, the
 49822  50045             ** next time a read transaction is opened the cache will be
................................................................................
 50307  50530     ** if the allocation fails. Otherwise, zero the new portion in case a 
 50308  50531     ** malloc failure occurs while populating it in the for(...) loop below.
 50309  50532     */
 50310  50533     aNew = (PagerSavepoint *)sqlite3Realloc(
 50311  50534         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
 50312  50535     );
 50313  50536     if( !aNew ){
 50314         -    return SQLITE_NOMEM;
        50537  +    return SQLITE_NOMEM_BKPT;
 50315  50538     }
 50316  50539     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
 50317  50540     pPager->aSavepoint = aNew;
 50318  50541   
 50319  50542     /* Populate the PagerSavepoint structures just allocated. */
 50320  50543     for(ii=nCurrent; ii<nSavepoint; ii++){
 50321  50544       aNew[ii].nOrig = pPager->dbSize;
................................................................................
 50323  50546         aNew[ii].iOffset = pPager->journalOff;
 50324  50547       }else{
 50325  50548         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
 50326  50549       }
 50327  50550       aNew[ii].iSubRec = pPager->nSubRec;
 50328  50551       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
 50329  50552       if( !aNew[ii].pInSavepoint ){
 50330         -      return SQLITE_NOMEM;
        50553  +      return SQLITE_NOMEM_BKPT;
 50331  50554       }
 50332  50555       if( pagerUseWal(pPager) ){
 50333  50556         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
 50334  50557       }
 50335  50558       pPager->nSavepoint = ii+1;
 50336  50559     }
 50337  50560     assert( pPager->nSavepoint==nSavepoint );
................................................................................
 50401  50624       pPager->nSavepoint = nNew;
 50402  50625   
 50403  50626       /* If this is a release of the outermost savepoint, truncate 
 50404  50627       ** the sub-journal to zero bytes in size. */
 50405  50628       if( op==SAVEPOINT_RELEASE ){
 50406  50629         if( nNew==0 && isOpen(pPager->sjfd) ){
 50407  50630           /* Only truncate if it is an in-memory sub-journal. */
 50408         -        if( sqlite3IsMemJournal(pPager->sjfd) ){
        50631  +        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
 50409  50632             rc = sqlite3OsTruncate(pPager->sjfd, 0);
 50410  50633             assert( rc==SQLITE_OK );
 50411  50634           }
 50412  50635           pPager->nSubRec = 0;
 50413  50636         }
 50414  50637       }
 50415  50638       /* Else this is a rollback operation, playback the specified savepoint.
................................................................................
 50472  50695   /*
 50473  50696   ** Return the full pathname of the journal file.
 50474  50697   */
 50475  50698   SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
 50476  50699     return pPager->zJournal;
 50477  50700   }
 50478  50701   
 50479         -/*
 50480         -** Return true if fsync() calls are disabled for this pager.  Return FALSE
 50481         -** if fsync()s are executed normally.
 50482         -*/
 50483         -SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
 50484         -  return pPager->noSync;
 50485         -}
 50486         -
 50487  50702   #ifdef SQLITE_HAS_CODEC
 50488  50703   /*
 50489  50704   ** Set or retrieve the codec for this pager
 50490  50705   */
 50491  50706   SQLITE_PRIVATE void sqlite3PagerSetCodec(
 50492  50707     Pager *pPager,
 50493  50708     void *(*xCodec)(void*,void*,Pgno,int),
................................................................................
 50926  51141   
 50927  51142   /*
 50928  51143   ** Return true if the underlying VFS for the given pager supports the
 50929  51144   ** primitives necessary for write-ahead logging.
 50930  51145   */
 50931  51146   SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
 50932  51147     const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
        51148  +  if( pPager->noLock ) return 0;
 50933  51149     return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
 50934  51150   }
 50935  51151   
 50936  51152   /*
 50937  51153   ** Attempt to take an exclusive lock on the database file. If a PENDING lock
 50938  51154   ** is obtained instead, immediately release it.
 50939  51155   */
................................................................................
 51671  51887     /* Enlarge the pWal->apWiData[] array if required */
 51672  51888     if( pWal->nWiData<=iPage ){
 51673  51889       int nByte = sizeof(u32*)*(iPage+1);
 51674  51890       volatile u32 **apNew;
 51675  51891       apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
 51676  51892       if( !apNew ){
 51677  51893         *ppPage = 0;
 51678         -      return SQLITE_NOMEM;
        51894  +      return SQLITE_NOMEM_BKPT;
 51679  51895       }
 51680  51896       memset((void*)&apNew[pWal->nWiData], 0,
 51681  51897              sizeof(u32*)*(iPage+1-pWal->nWiData));
 51682  51898       pWal->apWiData = apNew;
 51683  51899       pWal->nWiData = iPage+1;
 51684  51900     }
 51685  51901   
 51686  51902     /* Request a pointer to the required page from the VFS */
 51687  51903     if( pWal->apWiData[iPage]==0 ){
 51688  51904       if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 51689  51905         pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
 51690         -      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
        51906  +      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
 51691  51907       }else{
 51692  51908         rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
 51693  51909             pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
 51694  51910         );
 51695  51911         if( rc==SQLITE_READONLY ){
 51696  51912           pWal->readOnly |= WAL_SHM_RDONLY;
 51697  51913           rc = SQLITE_OK;
................................................................................
 52298  52514         goto finished;
 52299  52515       }
 52300  52516   
 52301  52517       /* Malloc a buffer to read frames into. */
 52302  52518       szFrame = szPage + WAL_FRAME_HDRSIZE;
 52303  52519       aFrame = (u8 *)sqlite3_malloc64(szFrame);
 52304  52520       if( !aFrame ){
 52305         -      rc = SQLITE_NOMEM;
        52521  +      rc = SQLITE_NOMEM_BKPT;
 52306  52522         goto recovery_error;
 52307  52523       }
 52308  52524       aData = &aFrame[WAL_FRAME_HDRSIZE];
 52309  52525   
 52310  52526       /* Read all frames from the log file. */
 52311  52527       iFrame = 0;
 52312  52528       for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
................................................................................
 52436  52652   #endif
 52437  52653   
 52438  52654   
 52439  52655     /* Allocate an instance of struct Wal to return. */
 52440  52656     *ppWal = 0;
 52441  52657     pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
 52442  52658     if( !pRet ){
 52443         -    return SQLITE_NOMEM;
        52659  +    return SQLITE_NOMEM_BKPT;
 52444  52660     }
 52445  52661   
 52446  52662     pRet->pVfs = pVfs;
 52447  52663     pRet->pWalFd = (sqlite3_file *)&pRet[1];
 52448  52664     pRet->pDbFd = pDbFd;
 52449  52665     pRet->readLock = -1;
 52450  52666     pRet->mxWalSize = mxWalSize;
................................................................................
 52700  52916     /* Allocate space for the WalIterator object. */
 52701  52917     nSegment = walFramePage(iLast) + 1;
 52702  52918     nByte = sizeof(WalIterator) 
 52703  52919           + (nSegment-1)*sizeof(struct WalSegment)
 52704  52920           + iLast*sizeof(ht_slot);
 52705  52921     p = (WalIterator *)sqlite3_malloc64(nByte);
 52706  52922     if( !p ){
 52707         -    return SQLITE_NOMEM;
        52923  +    return SQLITE_NOMEM_BKPT;
 52708  52924     }
 52709  52925     memset(p, 0, nByte);
 52710  52926     p->nSegment = nSegment;
 52711  52927   
 52712  52928     /* Allocate temporary space used by the merge-sort routine. This block
 52713  52929     ** of memory will be freed before this function returns.
 52714  52930     */
 52715  52931     aTmp = (ht_slot *)sqlite3_malloc64(
 52716  52932         sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
 52717  52933     );
 52718  52934     if( !aTmp ){
 52719         -    rc = SQLITE_NOMEM;
        52935  +    rc = SQLITE_NOMEM_BKPT;
 52720  52936     }
 52721  52937   
 52722  52938     for(i=0; rc==SQLITE_OK && i<nSegment; i++){
 52723  52939       volatile ht_slot *aHash;
 52724  52940       u32 iZero;
 52725  52941       volatile u32 *aPgno;
 52726  52942   
................................................................................
 54005  54221     int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
 54006  54222     sqlite3_int64 iOffset       /* Byte offset at which to write */
 54007  54223   ){
 54008  54224     int rc;                         /* Result code from subfunctions */
 54009  54225     void *pData;                    /* Data actually written */
 54010  54226     u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
 54011  54227   #if defined(SQLITE_HAS_CODEC)
 54012         -  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
        54228  +  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
 54013  54229   #else
 54014  54230     pData = pPage->pData;
 54015  54231   #endif
 54016  54232     walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
 54017  54233     rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
 54018  54234     if( rc ) return rc;
 54019  54235     /* Write the page data */
................................................................................
 54034  54250     int rc = SQLITE_OK;             /* Return code */
 54035  54251     u8 *aBuf;                       /* Buffer to load data from wal file into */
 54036  54252     u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
 54037  54253     u32 iRead;                      /* Next frame to read from wal file */
 54038  54254     i64 iCksumOff;
 54039  54255   
 54040  54256     aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
 54041         -  if( aBuf==0 ) return SQLITE_NOMEM;
        54257  +  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
 54042  54258   
 54043  54259     /* Find the checksum values to use as input for the recalculating the
 54044  54260     ** first checksum. If the first frame is frame 1 (implying that the current
 54045  54261     ** transaction restarted the wal file), these values must be read from the
 54046  54262     ** wal-file header. Otherwise, read them from the frame header of the
 54047  54263     ** previous frame.  */
 54048  54264     assert( pWal->iReCksum>0 );
................................................................................
 54510  54726     int rc = SQLITE_OK;
 54511  54727     WalIndexHdr *pRet;
 54512  54728   
 54513  54729     assert( pWal->readLock>=0 && pWal->writeLock==0 );
 54514  54730   
 54515  54731     pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
 54516  54732     if( pRet==0 ){
 54517         -    rc = SQLITE_NOMEM;
        54733  +    rc = SQLITE_NOMEM_BKPT;
 54518  54734     }else{
 54519  54735       memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
 54520  54736       *ppSnapshot = (sqlite3_snapshot*)pRet;
 54521  54737     }
 54522  54738   
 54523  54739     return rc;
 54524  54740   }
................................................................................
 55913  56129   
 55914  56130     /* If the above search did not find a BtLock struct associating Btree p
 55915  56131     ** with table iTable, allocate one and link it into the list.
 55916  56132     */
 55917  56133     if( !pLock ){
 55918  56134       pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
 55919  56135       if( !pLock ){
 55920         -      return SQLITE_NOMEM;
        56136  +      return SQLITE_NOMEM_BKPT;
 55921  56137       }
 55922  56138       pLock->iTable = iTable;
 55923  56139       pLock->pBtree = p;
 55924  56140       pLock->pNext = pBt->pLock;
 55925  56141       pBt->pLock = pLock;
 55926  56142     }
 55927  56143   
................................................................................
 56116  56332   */
 56117  56333   static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
 56118  56334     int rc = SQLITE_OK;
 56119  56335     if( !pBt->pHasContent ){
 56120  56336       assert( pgno<=pBt->nPage );
 56121  56337       pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
 56122  56338       if( !pBt->pHasContent ){
 56123         -      rc = SQLITE_NOMEM;
        56339  +      rc = SQLITE_NOMEM_BKPT;
 56124  56340       }
 56125  56341     }
 56126  56342     if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
 56127  56343       rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
 56128  56344     }
 56129  56345     return rc;
 56130  56346   }
................................................................................
 56195  56411         rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
 56196  56412         if( rc==SQLITE_OK ){
 56197  56413           pCur->pKey = pKey;
 56198  56414         }else{
 56199  56415           sqlite3_free(pKey);
 56200  56416         }
 56201  56417       }else{
 56202         -      rc = SQLITE_NOMEM;
        56418  +      rc = SQLITE_NOMEM_BKPT;
 56203  56419       }
 56204  56420     }
 56205  56421     assert( !pCur->curIntKey || !pCur->pKey );
 56206  56422     return rc;
 56207  56423   }
 56208  56424   
 56209  56425   /*
................................................................................
 56327  56543     char *pFree = 0;
 56328  56544   
 56329  56545     if( pKey ){
 56330  56546       assert( nKey==(i64)(int)nKey );
 56331  56547       pIdxKey = sqlite3VdbeAllocUnpackedRecord(
 56332  56548           pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
 56333  56549       );
 56334         -    if( pIdxKey==0 ) return SQLITE_NOMEM;
        56550  +    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
 56335  56551       sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
 56336  56552       if( pIdxKey->nField==0 ){
 56337  56553         sqlite3DbFree(pCur->pKeyInfo->db, pFree);
 56338  56554         return SQLITE_CORRUPT_BKPT;
 56339  56555       }
 56340  56556     }else{
 56341  56557       pIdxKey = 0;
................................................................................
 57739  57955       flags |= BTREE_MEMORY;
 57740  57956     }
 57741  57957     if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
 57742  57958       vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
 57743  57959     }
 57744  57960     p = sqlite3MallocZero(sizeof(Btree));
 57745  57961     if( !p ){
 57746         -    return SQLITE_NOMEM;
        57962  +    return SQLITE_NOMEM_BKPT;
 57747  57963     }
 57748  57964     p->inTrans = TRANS_NONE;
 57749  57965     p->db = db;
 57750  57966   #ifndef SQLITE_OMIT_SHARED_CACHE
 57751  57967     p->lock.pBtree = p;
 57752  57968     p->lock.iTable = 1;
 57753  57969   #endif
................................................................................
 57763  57979         int nFullPathname = pVfs->mxPathname+1;
 57764  57980         char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
 57765  57981         MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 57766  57982   
 57767  57983         p->sharable = 1;
 57768  57984         if( !zFullPathname ){
 57769  57985           sqlite3_free(p);
 57770         -        return SQLITE_NOMEM;
        57986  +        return SQLITE_NOMEM_BKPT;
 57771  57987         }
 57772  57988         if( isMemdb ){
 57773  57989           memcpy(zFullPathname, zFilename, nFilename);
 57774  57990         }else{
 57775  57991           rc = sqlite3OsFullPathname(pVfs, zFilename,
 57776  57992                                      nFullPathname, zFullPathname);
 57777  57993           if( rc ){
................................................................................
 57831  58047       assert( sizeof(u64)==8 );
 57832  58048       assert( sizeof(u32)==4 );
 57833  58049       assert( sizeof(u16)==2 );
 57834  58050       assert( sizeof(Pgno)==4 );
 57835  58051     
 57836  58052       pBt = sqlite3MallocZero( sizeof(*pBt) );
 57837  58053       if( pBt==0 ){
 57838         -      rc = SQLITE_NOMEM;
        58054  +      rc = SQLITE_NOMEM_BKPT;
 57839  58055         goto btree_open_out;
 57840  58056       }
 57841  58057       rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
 57842  58058                             EXTRA_SIZE, flags, vfsFlags, pageReinit);
 57843  58059       if( rc==SQLITE_OK ){
 57844  58060         sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
 57845  58061         rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
................................................................................
 57900  58116       if( p->sharable ){
 57901  58117         MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 57902  58118         pBt->nRef = 1;
 57903  58119         MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
 57904  58120         if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
 57905  58121           pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
 57906  58122           if( pBt->mutex==0 ){
 57907         -          rc = SQLITE_NOMEM;
        58123  +          rc = SQLITE_NOMEM_BKPT;
 57908  58124             goto btree_open_out;
 57909  58125           }
 57910  58126         }
 57911  58127         sqlite3_mutex_enter(mutexShared);
 57912  58128         pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
 57913  58129         GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
 57914  58130         sqlite3_mutex_leave(mutexShared);
................................................................................
 57923  58139     */
 57924  58140     if( p->sharable ){
 57925  58141       int i;
 57926  58142       Btree *pSib;
 57927  58143       for(i=0; i<db->nDb; i++){
 57928  58144         if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
 57929  58145           while( pSib->pPrev ){ pSib = pSib->pPrev; }
 57930         -        if( p->pBt<pSib->pBt ){
        58146  +        if( (uptr)p->pBt<(uptr)pSib->pBt ){
 57931  58147             p->pNext = pSib;
 57932  58148             p->pPrev = 0;
 57933  58149             pSib->pPrev = p;
 57934  58150           }else{
 57935         -          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
        58151  +          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
 57936  58152               pSib = pSib->pNext;
 57937  58153             }
 57938  58154             p->pNext = pSib->pNext;
 57939  58155             p->pPrev = pSib;
 57940  58156             if( p->pNext ){
 57941  58157               p->pNext->pPrev = p;
 57942  58158             }
................................................................................
 58182  58398     sqlite3BtreeEnter(p);
 58183  58399     sqlite3PagerSetFlags(pBt->pPager, pgFlags);
 58184  58400     sqlite3BtreeLeave(p);
 58185  58401     return SQLITE_OK;
 58186  58402   }
 58187  58403   #endif
 58188  58404   
 58189         -/*
 58190         -** Return TRUE if the given btree is set to safety level 1.  In other
 58191         -** words, return TRUE if no sync() occurs on the disk files.
 58192         -*/
 58193         -SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
 58194         -  BtShared *pBt = p->pBt;
 58195         -  int rc;
 58196         -  assert( sqlite3_mutex_held(p->db->mutex) );  
 58197         -  sqlite3BtreeEnter(p);
 58198         -  assert( pBt && pBt->pPager );
 58199         -  rc = sqlite3PagerNosync(pBt->pPager);
 58200         -  sqlite3BtreeLeave(p);
 58201         -  return rc;
 58202         -}
 58203         -
 58204  58405   /*
 58205  58406   ** Change the default pages size and the number of reserved bytes per page.
 58206  58407   ** Or, if the page size has already been fixed, return SQLITE_READONLY 
 58207  58408   ** without changing anything.
 58208  58409   **
 58209  58410   ** The page size must be a power of 2 between 512 and 65536.  If the page
 58210  58411   ** size supplied does not meet this constraint then the page size is not
................................................................................
 58442  58643       ** file.
 58443  58644       */
 58444  58645       if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
 58445  58646         int isOpen = 0;
 58446  58647         rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
 58447  58648         if( rc!=SQLITE_OK ){
 58448  58649           goto page1_init_failed;
 58449         -      }else if( isOpen==0 ){
 58450         -        releasePage(pPage1);
 58451         -        return SQLITE_OK;
        58650  +      }else{
        58651  +#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
        58652  +        sqlite3 *db;
        58653  +        Db *pDb;
        58654  +        if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
        58655  +          while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
        58656  +          if( pDb->bSyncSet==0
        58657  +           && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
        58658  +          ){
        58659  +            pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
        58660  +            sqlite3PagerSetFlags(pBt->pPager,
        58661  +               pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
        58662  +          }
        58663  +        }
        58664  +#endif
        58665  +        if( isOpen==0 ){
        58666  +          releasePage(pPage1);
        58667  +          return SQLITE_OK;
        58668  +        }
 58452  58669         }
 58453  58670         rc = SQLITE_NOTADB;
 58454  58671       }
 58455  58672   #endif
 58456  58673   
 58457  58674       /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
 58458  58675       ** fractions and the leaf payload fraction values must be 64, 32, and 32.
................................................................................
 59677  59894     assert( p->inTrans>TRANS_NONE );
 59678  59895     assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
 59679  59896     assert( pBt->pPage1 && pBt->pPage1->aData );
 59680  59897     assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
 59681  59898   
 59682  59899     if( wrFlag ){
 59683  59900       allocateTempSpace(pBt);
 59684         -    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
        59901  +    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
 59685  59902     }
 59686  59903     if( iTable==1 && btreePagecount(pBt)==0 ){
 59687  59904       assert( wrFlag==0 );
 59688  59905       iTable = 0;
 59689  59906     }
 59690  59907   
 59691  59908     /* Now that no other errors can occur, finish filling in the BtCursor
................................................................................
 60034  60251     getCellInfo(pCur);
 60035  60252     aPayload = pCur->info.pPayload;
 60036  60253   #ifdef SQLITE_DIRECT_OVERFLOW_READ
 60037  60254     bEnd = offset+amt==pCur->info.nPayload;
 60038  60255   #endif
 60039  60256     assert( offset+amt <= pCur->info.nPayload );
 60040  60257   
 60041         -  if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
 60042         -    /* Trying to read or write past the end of the data is an error */
        60258  +  assert( aPayload > pPage->aData );
        60259  +  if( (aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
        60260  +    /* Trying to read or write past the end of the data is an error.  The
        60261  +    ** conditional above is really:
        60262  +    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
        60263  +    ** but is recast into its current form to avoid integer overflow problems
        60264  +    */
 60043  60265       return SQLITE_CORRUPT_BKPT;
 60044  60266     }
 60045  60267   
 60046  60268     /* Check if data must be read/written to/from the btree page itself. */
 60047  60269     if( offset<pCur->info.nLocal ){
 60048  60270       int a = amt;
 60049  60271       if( a+offset>pCur->info.nLocal ){
................................................................................
 60075  60297       if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
 60076  60298         int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
 60077  60299         if( nOvfl>pCur->nOvflAlloc ){
 60078  60300           Pgno *aNew = (Pgno*)sqlite3Realloc(
 60079  60301               pCur->aOverflow, nOvfl*2*sizeof(Pgno)
 60080  60302           );
 60081  60303           if( aNew==0 ){
 60082         -          rc = SQLITE_NOMEM;
        60304  +          rc = SQLITE_NOMEM_BKPT;
 60083  60305           }else{
 60084  60306             pCur->nOvflAlloc = nOvfl*2;
 60085  60307             pCur->aOverflow = aNew;
 60086  60308           }
 60087  60309         }
 60088  60310         if( rc==SQLITE_OK ){
 60089  60311           memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
................................................................................
 60780  61002             testcase( nCell==2 );  /* Minimum legal index key size */
 60781  61003             if( nCell<2 ){
 60782  61004               rc = SQLITE_CORRUPT_BKPT;
 60783  61005               goto moveto_finish;
 60784  61006             }
 60785  61007             pCellKey = sqlite3Malloc( nCell+18 );
 60786  61008             if( pCellKey==0 ){
 60787         -            rc = SQLITE_NOMEM;
        61009  +            rc = SQLITE_NOMEM_BKPT;
 60788  61010               goto moveto_finish;
 60789  61011             }
 60790  61012             pCur->aiIdx[pCur->iPage] = (u16)idx;
 60791  61013             rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
 60792  61014             if( rc ){
 60793  61015               sqlite3_free(pCellKey);
 60794  61016               goto moveto_finish;
................................................................................
 62599  62821     ** index iParentIdx. This scenario comes about when this function
 62600  62822     ** is called (indirectly) from sqlite3BtreeDelete().
 62601  62823     */
 62602  62824     assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
 62603  62825     assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
 62604  62826   
 62605  62827     if( !aOvflSpace ){
 62606         -    return SQLITE_NOMEM;
        62828  +    return SQLITE_NOMEM_BKPT;
 62607  62829     }
 62608  62830   
 62609  62831     /* Find the sibling pages to balance. Also locate the cells in pParent 
 62610  62832     ** that divide the siblings. An attempt is made to find NN siblings on 
 62611  62833     ** either side of pPage. More siblings are taken from one side, however, 
 62612  62834     ** if there are fewer than NN siblings on the other side. If pParent
 62613  62835     ** has NB or fewer children then all children of pParent are taken.  
................................................................................
 62699  62921        + pBt->pageSize;                              /* aSpace1 */
 62700  62922   
 62701  62923     /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
 62702  62924     ** that is more than 6 times the database page size. */
 62703  62925     assert( szScratch<=6*(int)pBt->pageSize );
 62704  62926     b.apCell = sqlite3ScratchMalloc( szScratch ); 
 62705  62927     if( b.apCell==0 ){
 62706         -    rc = SQLITE_NOMEM;
        62928  +    rc = SQLITE_NOMEM_BKPT;
 62707  62929       goto balance_cleanup;
 62708  62930     }
 62709  62931     b.szCell = (u16*)&b.apCell[nMaxCells];
 62710  62932     aSpace1 = (u8*)&b.szCell[nMaxCells];
 62711  62933     assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
 62712  62934   
 62713  62935     /*
................................................................................
 63134  63356         /* Obscure case for non-leaf-data trees: If the cell at pCell was
 63135  63357         ** previously stored on a leaf node, and its reported size was 4
 63136  63358         ** bytes, then it may actually be smaller than this 
 63137  63359         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
 63138  63360         ** any cell). But it is important to pass the correct size to 
 63139  63361         ** insertCell(), so reparse the cell now.
 63140  63362         **
 63141         -      ** Note that this can never happen in an SQLite data file, as all
 63142         -      ** cells are at least 4 bytes. It only happens in b-trees used
 63143         -      ** to evaluate "IN (SELECT ...)" and similar clauses.
        63363  +      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
        63364  +      ** and WITHOUT ROWID tables with exactly one column which is the
        63365  +      ** primary key.
 63144  63366         */
 63145  63367         if( b.szCell[j]==4 ){
 63146  63368           assert(leafCorrection==4);
 63147  63369           sz = pParent->xCellSize(pParent, pCell);
 63148  63370         }
 63149  63371       }
 63150  63372       iOvflSpace += sz;
................................................................................
 65355  65577   
 65356  65578     if( i==1 ){
 65357  65579       Parse *pParse;
 65358  65580       int rc = 0;
 65359  65581       pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
 65360  65582       if( pParse==0 ){
 65361  65583         sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
 65362         -      rc = SQLITE_NOMEM;
        65584  +      rc = SQLITE_NOMEM_BKPT;
 65363  65585       }else{
 65364  65586         pParse->db = pDb;
 65365  65587         if( sqlite3OpenTempDatabase(pParse) ){
 65366  65588           sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
 65367  65589           rc = SQLITE_ERROR;
 65368  65590         }
 65369  65591         sqlite3DbFree(pErrorDb, pParse->zErrMsg);
................................................................................
 65449  65671     }else {
 65450  65672       /* Allocate space for a new sqlite3_backup object...
 65451  65673       ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 65452  65674       ** call to sqlite3_backup_init() and is destroyed by a call to
 65453  65675       ** sqlite3_backup_finish(). */
 65454  65676       p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
 65455  65677       if( !p ){
 65456         -      sqlite3Error(pDestDb, SQLITE_NOMEM);
        65678  +      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
 65457  65679       }
 65458  65680     }
 65459  65681   
 65460  65682     /* If the allocation succeeded, populate the new object. */
 65461  65683     if( p ){
 65462  65684       p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
 65463  65685       p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
................................................................................
 65848  66070         TESTONLY( int rc2 );
 65849  66071         TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
 65850  66072         TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
 65851  66073         assert( rc2==SQLITE_OK );
 65852  66074       }
 65853  66075     
 65854  66076       if( rc==SQLITE_IOERR_NOMEM ){
 65855         -      rc = SQLITE_NOMEM;
        66077  +      rc = SQLITE_NOMEM_BKPT;
 65856  66078       }
 65857  66079       p->rc = rc;
 65858  66080     }
 65859  66081     if( p->pDestDb ){
 65860  66082       sqlite3_mutex_leave(p->pDestDb->mutex);
 65861  66083     }
 65862  66084     sqlite3BtreeLeave(p->pSrc);
................................................................................
 66205  66427         if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
 66206  66428         pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
 66207  66429       }
 66208  66430       if( pMem->zMalloc==0 ){
 66209  66431         sqlite3VdbeMemSetNull(pMem);
 66210  66432         pMem->z = 0;
 66211  66433         pMem->szMalloc = 0;
 66212         -      return SQLITE_NOMEM;
        66434  +      return SQLITE_NOMEM_BKPT;
 66213  66435       }else{
 66214  66436         pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 66215  66437       }
 66216  66438     }
 66217  66439   
 66218  66440     if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
 66219  66441       memcpy(pMem->zMalloc, pMem->z, pMem->n);
................................................................................
 66263  66485     int f;
 66264  66486     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 66265  66487     assert( (pMem->flags&MEM_RowSet)==0 );
 66266  66488     ExpandBlob(pMem);
 66267  66489     f = pMem->flags;
 66268  66490     if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
 66269  66491       if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
 66270         -      return SQLITE_NOMEM;
        66492  +      return SQLITE_NOMEM_BKPT;
 66271  66493       }
 66272  66494       pMem->z[pMem->n] = 0;
 66273  66495       pMem->z[pMem->n+1] = 0;
 66274  66496       pMem->flags |= MEM_Term;
 66275  66497     }
 66276  66498     pMem->flags &= ~MEM_Ephem;
 66277  66499   #ifdef SQLITE_DEBUG
................................................................................
 66295  66517   
 66296  66518       /* Set nByte to the number of bytes required to store the expanded blob. */
 66297  66519       nByte = pMem->n + pMem->u.nZero;
 66298  66520       if( nByte<=0 ){
 66299  66521         nByte = 1;
 66300  66522       }
 66301  66523       if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
 66302         -      return SQLITE_NOMEM;
        66524  +      return SQLITE_NOMEM_BKPT;
 66303  66525       }
 66304  66526   
 66305  66527       memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
 66306  66528       pMem->n += pMem->u.nZero;
 66307  66529       pMem->flags &= ~(MEM_Zero|MEM_Term);
 66308  66530     }
 66309  66531     return SQLITE_OK;
................................................................................
 66312  66534   
 66313  66535   /*
 66314  66536   ** It is already known that pMem contains an unterminated string.
 66315  66537   ** Add the zero terminator.
 66316  66538   */
 66317  66539   static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
 66318  66540     if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
 66319         -    return SQLITE_NOMEM;
        66541  +    return SQLITE_NOMEM_BKPT;
 66320  66542     }
 66321  66543     pMem->z[pMem->n] = 0;
 66322  66544     pMem->z[pMem->n+1] = 0;
 66323  66545     pMem->flags |= MEM_Term;
 66324  66546     return SQLITE_OK;
 66325  66547   }
 66326  66548   
................................................................................
 66361  66583     assert( !(fg&(MEM_Str|MEM_Blob)) );
 66362  66584     assert( fg&(MEM_Int|MEM_Real) );
 66363  66585     assert( (pMem->flags&MEM_RowSet)==0 );
 66364  66586     assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 66365  66587   
 66366  66588   
 66367  66589     if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 66368         -    return SQLITE_NOMEM;
        66590  +    return SQLITE_NOMEM_BKPT;
 66369  66591     }
 66370  66592   
 66371  66593     /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
 66372  66594     ** string representation of the value. Then, if the required encoding
 66373  66595     ** is UTF-16le or UTF-16be do a translation.
 66374  66596     ** 
 66375  66597     ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
................................................................................
 66828  67050   **
 66829  67051   ** This is used for testing and debugging only - to make sure shallow
 66830  67052   ** copies are not misused.
 66831  67053   */
 66832  67054   SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
 66833  67055     int i;
 66834  67056     Mem *pX;
 66835         -  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
        67057  +  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
 66836  67058       if( pX->pScopyFrom==pMem ){
 66837  67059         pX->flags |= MEM_Undefined;
 66838  67060         pX->pScopyFrom = 0;
 66839  67061       }
 66840  67062     }
 66841  67063     pMem->pScopyFrom = 0;
 66842  67064   }
................................................................................
 66972  67194       if( nByte>iLimit ){
 66973  67195         return SQLITE_TOOBIG;
 66974  67196       }
 66975  67197       testcase( nAlloc==0 );
 66976  67198       testcase( nAlloc==31 );
 66977  67199       testcase( nAlloc==32 );
 66978  67200       if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
 66979         -      return SQLITE_NOMEM;
        67201  +      return SQLITE_NOMEM_BKPT;
 66980  67202       }
 66981  67203       memcpy(pMem->z, z, nAlloc);
 66982  67204     }else if( xDel==SQLITE_DYNAMIC ){
 66983  67205       sqlite3VdbeMemRelease(pMem);
 66984  67206       pMem->zMalloc = pMem->z = (char *)z;
 66985  67207       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 66986  67208     }else{
................................................................................
 66992  67214   
 66993  67215     pMem->n = nByte;
 66994  67216     pMem->flags = flags;
 66995  67217     pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
 66996  67218   
 66997  67219   #ifndef SQLITE_OMIT_UTF16
 66998  67220     if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
 66999         -    return SQLITE_NOMEM;
        67221  +    return SQLITE_NOMEM_BKPT;
 67000  67222     }
 67001  67223   #endif
 67002  67224   
 67003  67225     if( nByte>iLimit ){
 67004  67226       return SQLITE_TOOBIG;
 67005  67227     }
 67006  67228   
................................................................................
 67253  67475   ){
 67254  67476     sqlite3_context ctx;            /* Context object for function invocation */
 67255  67477     sqlite3_value **apVal = 0;      /* Function arguments */
 67256  67478     int nVal = 0;                   /* Size of apVal[] array */
 67257  67479     FuncDef *pFunc = 0;             /* Function definition */
 67258  67480     sqlite3_value *pVal = 0;        /* New value */
 67259  67481     int rc = SQLITE_OK;             /* Return code */
 67260         -  int nName;                      /* Size of function name in bytes */
 67261  67482     ExprList *pList = 0;            /* Function arguments */
 67262  67483     int i;                          /* Iterator variable */
 67263  67484   
 67264  67485     assert( pCtx!=0 );
 67265  67486     assert( (p->flags & EP_TokenOnly)==0 );
 67266  67487     pList = p->x.pList;
 67267  67488     if( pList ) nVal = pList->nExpr;
 67268         -  nName = sqlite3Strlen30(p->u.zToken);
 67269         -  pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
        67489  +  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
 67270  67490     assert( pFunc );
 67271  67491     if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 
 67272  67492      || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
 67273  67493     ){
 67274  67494       return SQLITE_OK;
 67275  67495     }
 67276  67496   
 67277  67497     if( pList ){
 67278  67498       apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
 67279  67499       if( apVal==0 ){
 67280         -      rc = SQLITE_NOMEM;
        67500  +      rc = SQLITE_NOMEM_BKPT;
 67281  67501         goto value_from_function_out;
 67282  67502       }
 67283  67503       for(i=0; i<nVal; i++){
 67284  67504         rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
 67285  67505         if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
 67286  67506       }
 67287  67507     }
 67288  67508   
 67289  67509     pVal = valueNew(db, pCtx);
 67290  67510     if( pVal==0 ){
 67291         -    rc = SQLITE_NOMEM;
        67511  +    rc = SQLITE_NOMEM_BKPT;
 67292  67512       goto value_from_function_out;
 67293  67513     }
 67294  67514   
 67295  67515     assert( pCtx->pParse->rc==SQLITE_OK );
 67296  67516     memset(&ctx, 0, sizeof(ctx));
 67297  67517     ctx.pOut = pVal;
 67298  67518     ctx.pFunc = pFunc;
................................................................................
 67354  67574     const char *zNeg = "";
 67355  67575     int rc = SQLITE_OK;
 67356  67576   
 67357  67577     if( !pExpr ){
 67358  67578       *ppVal = 0;
 67359  67579       return SQLITE_OK;
 67360  67580     }
 67361         -  while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
        67581  +  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
 67362  67582     if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
 67363  67583   
 67364  67584     /* Compressed expressions only appear when parsing the DEFAULT clause
 67365  67585     ** on a table column definition, and hence only when pCtx==0.  This
 67366  67586     ** check ensures that an EP_TokenOnly expression is never passed down
 67367  67587     ** into valueFromFunction(). */
 67368  67588     assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
................................................................................
 67457  67677     sqlite3DbFree(db, zVal);
 67458  67678     assert( *ppVal==0 );
 67459  67679   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 67460  67680     if( pCtx==0 ) sqlite3ValueFree(pVal);
 67461  67681   #else
 67462  67682     assert( pCtx==0 ); sqlite3ValueFree(pVal);
 67463  67683   #endif
 67464         -  return SQLITE_NOMEM;
        67684  +  return SQLITE_NOMEM_BKPT;
 67465  67685   }
 67466  67686   
 67467  67687   /*
 67468  67688   ** Create a new sqlite3_value object, containing the value of pExpr.
 67469  67689   **
 67470  67690   ** This only works for very simple expressions that consist of one constant
 67471  67691   ** token (i.e. "5", "5.1", "'a string'"). If the expression can
................................................................................
 67524  67744     }
 67525  67745   }
 67526  67746   
 67527  67747   /*
 67528  67748   ** Register built-in functions used to help read ANALYZE data.
 67529  67749   */
 67530  67750   SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
 67531         -  static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
        67751  +  static FuncDef aAnalyzeTableFuncs[] = {
 67532  67752       FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
 67533  67753     };
 67534         -  int i;
 67535         -  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 67536         -  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
 67537         -  for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
 67538         -    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 67539         -  }
        67754  +  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
 67540  67755   }
 67541  67756   
 67542  67757   /*
 67543  67758   ** Attempt to extract a value from pExpr and use it to construct *ppVal.
 67544  67759   **
 67545  67760   ** If pAlloc is not NULL, then an UnpackedRecord object is created for
 67546  67761   ** pAlloc if one does not exist and the new value is added to the
................................................................................
 67711  67926       iField += szField;
 67712  67927     }
 67713  67928     testcase( iField==nRec );
 67714  67929     testcase( iField==nRec+1 );
 67715  67930     if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
 67716  67931     if( pMem==0 ){
 67717  67932       pMem = *ppVal = sqlite3ValueNew(db);
 67718         -    if( pMem==0 ) return SQLITE_NOMEM;
        67933  +    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
 67719  67934     }
 67720  67935     sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
 67721  67936     pMem->enc = ENC(db);
 67722  67937     return SQLITE_OK;
 67723  67938   }
 67724  67939   
 67725  67940   /*
................................................................................
 67918  68133     assert( nNew>=(p->nOpAlloc+nOp) );
 67919  68134     pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
 67920  68135     if( pNew ){
 67921  68136       p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
 67922  68137       p->nOpAlloc = p->szOpAlloc/sizeof(Op);
 67923  68138       v->aOp = pNew;
 67924  68139     }
 67925         -  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
        68140  +  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
 67926  68141   }
 67927  68142   
 67928  68143   #ifdef SQLITE_DEBUG
 67929  68144   /* This routine is just a convenient place to set a breakpoint that will
 67930  68145   ** fire after each opcode is inserted and displayed using
 67931  68146   ** "PRAGMA vdbe_addoptrace=on".
 67932  68147   */
................................................................................
 68179  68394   
 68180  68395   /*
 68181  68396   ** Mark the VDBE as one that can only be run one time.
 68182  68397   */
 68183  68398   SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
 68184  68399     p->runOnlyOnce = 1;
 68185  68400   }
        68401  +
        68402  +/*
        68403  +** Mark the VDBE as one that can only be run multiple times.
        68404  +*/
        68405  +SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
        68406  +  p->runOnlyOnce = 0;
        68407  +}
 68186  68408   
 68187  68409   #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
 68188  68410   
 68189  68411   /*
 68190  68412   ** The following type and function are used to iterate through all opcodes
 68191  68413   ** in a Vdbe main program and each of the sub-programs (triggers) it may 
 68192  68414   ** invoke directly or indirectly. It should be used as follows:
................................................................................
 69277  69499     int i;
 69278  69500     Mem *aMem = VdbeFrameMem(p);
 69279  69501     VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
 69280  69502     for(i=0; i<p->nChildCsr; i++){
 69281  69503       sqlite3VdbeFreeCursor(p->v, apCsr[i]);
 69282  69504     }
 69283  69505     releaseMemArray(aMem, p->nChildMem);
        69506  +  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
 69284  69507     sqlite3DbFree(p->v->db, p);
 69285  69508   }
 69286  69509   
 69287  69510   #ifndef SQLITE_OMIT_EXPLAIN
 69288  69511   /*
 69289  69512   ** Give a listing of the program in the virtual machine.
 69290  69513   **
................................................................................
 69319  69542     /* Even though this opcode does not use dynamic strings for
 69320  69543     ** the result, result columns may become dynamic if the user calls
 69321  69544     ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
 69322  69545     */
 69323  69546     releaseMemArray(pMem, 8);
 69324  69547     p->pResultSet = 0;
 69325  69548   
 69326         -  if( p->rc==SQLITE_NOMEM ){
        69549  +  if( p->rc==SQLITE_NOMEM_BKPT ){
 69327  69550       /* This happens if a malloc() inside a call to sqlite3_column_text() or
 69328  69551       ** sqlite3_column_text16() failed.  */
 69329  69552       sqlite3OomFault(db);
 69330  69553       return SQLITE_ERROR;
 69331  69554     }
 69332  69555   
 69333  69556     /* When the number of output rows reaches nRow, that means the
................................................................................
 69582  69805     */
 69583  69806     assert( p->nOp>0 );
 69584  69807   
 69585  69808     /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
 69586  69809     p->magic = VDBE_MAGIC_RUN;
 69587  69810   
 69588  69811   #ifdef SQLITE_DEBUG
 69589         -  for(i=1; i<p->nMem; i++){
        69812  +  for(i=0; i<p->nMem; i++){
 69590  69813       assert( p->aMem[i].db==p->db );
 69591  69814     }
 69592  69815   #endif
 69593  69816     p->pc = -1;
 69594  69817     p->rc = SQLITE_OK;
 69595  69818     p->errorAction = OE_Abort;
 69596  69819     p->nChange = 0;
................................................................................
 69647  69870     nVar = pParse->nVar;
 69648  69871     nMem = pParse->nMem;
 69649  69872     nCursor = pParse->nTab;
 69650  69873     nArg = pParse->nMaxArg;
 69651  69874     nOnce = pParse->nOnce;
 69652  69875     if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
 69653  69876     
 69654         -  /* For each cursor required, also allocate a memory cell. Memory
 69655         -  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
 69656         -  ** the vdbe program. Instead they are used to allocate memory for
 69657         -  ** VdbeCursor/BtCursor structures. The blob of memory associated with 
 69658         -  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
 69659         -  ** stores the blob of memory associated with cursor 1, etc.
 69660         -  **
        69877  +  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
        69878  +  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
        69879  +  ** space at the end of aMem[] for cursors 1 and greater.
 69661  69880     ** See also: allocateCursor().
 69662  69881     */
 69663  69882     nMem += nCursor;
        69883  +  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
 69664  69884   
 69665  69885     /* Figure out how much reusable memory is available at the end of the
 69666  69886     ** opcode array.  This extra memory will be reallocated for other elements
 69667  69887     ** of the prepared statement.
 69668  69888     */
 69669  69889     n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
 69670  69890     x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
................................................................................
 69718  69938       }
 69719  69939     }
 69720  69940     p->nzVar = pParse->nzVar;
 69721  69941     p->azVar = pParse->azVar;
 69722  69942     pParse->nzVar =  0;
 69723  69943     pParse->azVar = 0;
 69724  69944     if( p->aMem ){
 69725         -    p->aMem--;                      /* aMem[] goes from 1..nMem */
 69726         -    p->nMem = nMem;                 /*       not from 0..nMem-1 */
 69727         -    for(n=1; n<=nMem; n++){
        69945  +    p->nMem = nMem;
        69946  +    for(n=0; n<nMem; n++){
 69728  69947         p->aMem[n].flags = MEM_Undefined;
 69729  69948         p->aMem[n].db = db;
 69730  69949       }
 69731  69950     }
 69732  69951     p->explain = pParse->explain;
 69733  69952     sqlite3VdbeRewind(p);
 69734  69953   }
................................................................................
 69805  70024     v->aMem = pFrame->aMem;
 69806  70025     v->nMem = pFrame->nMem;
 69807  70026     v->apCsr = pFrame->apCsr;
 69808  70027     v->nCursor = pFrame->nCursor;
 69809  70028     v->db->lastRowid = pFrame->lastRowid;
 69810  70029     v->nChange = pFrame->nChange;
 69811  70030     v->db->nChange = pFrame->nDbChange;
        70031  +  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
        70032  +  v->pAuxData = pFrame->pAuxData;
        70033  +  pFrame->pAuxData = 0;
 69812  70034     return pFrame->pc;
 69813  70035   }
 69814  70036   
 69815  70037   /*
 69816  70038   ** Close all cursors.
 69817  70039   **
 69818  70040   ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
................................................................................
 69827  70049       sqlite3VdbeFrameRestore(pFrame);
 69828  70050       p->pFrame = 0;
 69829  70051       p->nFrame = 0;
 69830  70052     }
 69831  70053     assert( p->nFrame==0 );
 69832  70054     closeCursorsInFrame(p);
 69833  70055     if( p->aMem ){
 69834         -    releaseMemArray(&p->aMem[1], p->nMem);
        70056  +    releaseMemArray(p->aMem, p->nMem);
 69835  70057     }
 69836  70058     while( p->pDelFrame ){
 69837  70059       VdbeFrame *pDel = p->pDelFrame;
 69838  70060       p->pDelFrame = pDel->pParent;
 69839  70061       sqlite3VdbeFrameDelete(pDel);
 69840  70062     }
 69841  70063   
 69842  70064     /* Delete any auxdata allocations made by the VM */
 69843         -  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
        70065  +  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
 69844  70066     assert( p->pAuxData==0 );
 69845  70067   }
 69846  70068   
 69847  70069   /*
 69848  70070   ** Clean up the VM after a single run.
 69849  70071   */
 69850  70072   static void Cleanup(Vdbe *p){
................................................................................
 69852  70074   
 69853  70075   #ifdef SQLITE_DEBUG
 69854  70076     /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
 69855  70077     ** Vdbe.aMem[] arrays have already been cleaned up.  */
 69856  70078     int i;
 69857  70079     if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
 69858  70080     if( p->aMem ){
 69859         -    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
        70081  +    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
 69860  70082     }
 69861  70083   #endif
 69862  70084   
 69863  70085     sqlite3DbFree(db, p->zErrMsg);
 69864  70086     p->zErrMsg = 0;
 69865  70087     p->pResultSet = 0;
 69866  70088   }
................................................................................
 69908  70130   ){
 69909  70131     int rc;
 69910  70132     Mem *pColName;
 69911  70133     assert( idx<p->nResColumn );
 69912  70134     assert( var<COLNAME_N );
 69913  70135     if( p->db->mallocFailed ){
 69914  70136       assert( !zName || xDel!=SQLITE_DYNAMIC );
 69915         -    return SQLITE_NOMEM;
        70137  +    return SQLITE_NOMEM_BKPT;
 69916  70138     }
 69917  70139     assert( p->aColName!=0 );
 69918  70140     pColName = &(p->aColName[idx+var*p->nResColumn]);
 69919  70141     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
 69920  70142     assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
 69921  70143     return rc;
 69922  70144   }
................................................................................
 69925  70147   ** A read or write transaction may or may not be active on database handle
 69926  70148   ** db. If a transaction is active, commit it. If there is a
 69927  70149   ** write-transaction spanning more than one database file, this routine
 69928  70150   ** takes care of the master journal trickery.
 69929  70151   */
 69930  70152   static int vdbeCommit(sqlite3 *db, Vdbe *p){
 69931  70153     int i;
 69932         -  int nTrans = 0;  /* Number of databases with an active write-transaction */
        70154  +  int nTrans = 0;  /* Number of databases with an active write-transaction
        70155  +                   ** that are candidates for a two-phase commit using a
        70156  +                   ** master-journal */
 69933  70157     int rc = SQLITE_OK;
 69934  70158     int needXcommit = 0;
 69935  70159   
 69936  70160   #ifdef SQLITE_OMIT_VIRTUALTABLE
 69937  70161     /* With this option, sqlite3VtabSync() is defined to be simply 
 69938  70162     ** SQLITE_OK so p is not used. 
 69939  70163     */
................................................................................
 69953  70177     ** including the temp database. (b) is important because if more than 
 69954  70178     ** one database file has an open write transaction, a master journal
 69955  70179     ** file is required for an atomic commit.
 69956  70180     */ 
 69957  70181     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 69958  70182       Btree *pBt = db->aDb[i].pBt;
 69959  70183       if( sqlite3BtreeIsInTrans(pBt) ){
        70184  +      /* Whether or not a database might need a master journal depends upon
        70185  +      ** its journal mode (among other things).  This matrix determines which
        70186  +      ** journal modes use a master journal and which do not */
        70187  +      static const u8 aMJNeeded[] = {
        70188  +        /* DELETE   */  1,
        70189  +        /* PERSIST   */ 1,
        70190  +        /* OFF       */ 0,
        70191  +        /* TRUNCATE  */ 1,
        70192  +        /* MEMORY    */ 0,
        70193  +        /* WAL       */ 0
        70194  +      };
        70195  +      Pager *pPager;   /* Pager associated with pBt */
 69960  70196         needXcommit = 1;
 69961         -      if( i!=1 ) nTrans++;
 69962  70197         sqlite3BtreeEnter(pBt);
 69963         -      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
        70198  +      pPager = sqlite3BtreePager(pBt);
        70199  +      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
        70200  +       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
        70201  +      ){ 
        70202  +        assert( i!=1 );
        70203  +        nTrans++;
        70204  +      }
        70205  +      rc = sqlite3PagerExclusiveLock(pPager);
 69964  70206         sqlite3BtreeLeave(pBt);
 69965  70207       }
 69966  70208     }
 69967  70209     if( rc!=SQLITE_OK ){
 69968  70210       return rc;
 69969  70211     }
 69970  70212   
................................................................................
 70014  70256     /* The complex case - There is a multi-file write-transaction active.
 70015  70257     ** This requires a master journal file to ensure the transaction is
 70016  70258     ** committed atomically.
 70017  70259     */
 70018  70260   #ifndef SQLITE_OMIT_DISKIO
 70019  70261     else{
 70020  70262       sqlite3_vfs *pVfs = db->pVfs;
 70021         -    int needSync = 0;
 70022  70263       char *zMaster = 0;   /* File-name for the master journal */
 70023  70264       char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
 70024  70265       sqlite3_file *pMaster = 0;
 70025  70266       i64 offset = 0;
 70026  70267       int res;
 70027  70268       int retryCount = 0;
 70028  70269       int nMainFile;
 70029  70270   
 70030  70271       /* Select a master journal file name */
 70031  70272       nMainFile = sqlite3Strlen30(zMainFile);
 70032  70273       zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
 70033         -    if( zMaster==0 ) return SQLITE_NOMEM;
        70274  +    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
 70034  70275       do {
 70035  70276         u32 iRandom;
 70036  70277         if( retryCount ){
 70037  70278           if( retryCount>100 ){
 70038  70279             sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
 70039  70280             sqlite3OsDelete(pVfs, zMaster, 0);
 70040  70281             break;
................................................................................
 70074  70315         Btree *pBt = db->aDb[i].pBt;
 70075  70316         if( sqlite3BtreeIsInTrans(pBt) ){
 70076  70317           char const *zFile = sqlite3BtreeGetJournalname(pBt);
 70077  70318           if( zFile==0 ){
 70078  70319             continue;  /* Ignore TEMP and :memory: databases */
 70079  70320           }
 70080  70321           assert( zFile[0]!=0 );
 70081         -        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
 70082         -          needSync = 1;
 70083         -        }
 70084  70322           rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
 70085  70323           offset += sqlite3Strlen30(zFile)+1;
 70086  70324           if( rc!=SQLITE_OK ){
 70087  70325             sqlite3OsCloseFree(pMaster);
 70088  70326             sqlite3OsDelete(pVfs, zMaster, 0);
 70089  70327             sqlite3DbFree(db, zMaster);
 70090  70328             return rc;
................................................................................
 70091  70329           }
 70092  70330         }
 70093  70331       }
 70094  70332   
 70095  70333       /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
 70096  70334       ** flag is set this is not required.
 70097  70335       */
 70098         -    if( needSync 
 70099         -     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
        70336  +    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
 70100  70337        && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
 70101  70338       ){
 70102  70339         sqlite3OsCloseFree(pMaster);
 70103  70340         sqlite3OsDelete(pVfs, zMaster, 0);
 70104  70341         sqlite3DbFree(db, zMaster);
 70105  70342         return rc;
 70106  70343       }
................................................................................
 70128  70365         return rc;
 70129  70366       }
 70130  70367   
 70131  70368       /* Delete the master journal file. This commits the transaction. After
 70132  70369       ** doing this the directory is synced again before any individual
 70133  70370       ** transaction files are deleted.
 70134  70371       */
 70135         -    rc = sqlite3OsDelete(pVfs, zMaster, needSync);
        70372  +    rc = sqlite3OsDelete(pVfs, zMaster, 1);
 70136  70373       sqlite3DbFree(db, zMaster);
 70137  70374       zMaster = 0;
 70138  70375       if( rc ){
 70139  70376         return rc;
 70140  70377       }
 70141  70378   
 70142  70379       /* All files and directories have already been synced, so the following
................................................................................
 70316  70553     **
 70317  70554     ** Then the internal cache might have been left in an inconsistent
 70318  70555     ** state.  We need to rollback the statement transaction, if there is
 70319  70556     ** one, or the complete transaction if there is no statement transaction.
 70320  70557     */
 70321  70558   
 70322  70559     if( db->mallocFailed ){
 70323         -    p->rc = SQLITE_NOMEM;
        70560  +    p->rc = SQLITE_NOMEM_BKPT;
 70324  70561     }
 70325  70562     if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
 70326  70563     closeAllCursors(p);
 70327  70564     if( p->magic!=VDBE_MAGIC_RUN ){
 70328  70565       return SQLITE_OK;
 70329  70566     }
 70330  70567     checkActiveVdbeCnt(db);
................................................................................
 70477  70714       assert( db->nVdbeActive>=db->nVdbeRead );
 70478  70715       assert( db->nVdbeRead>=db->nVdbeWrite );
 70479  70716       assert( db->nVdbeWrite>=0 );
 70480  70717     }
 70481  70718     p->magic = VDBE_MAGIC_HALT;
 70482  70719     checkActiveVdbeCnt(db);
 70483  70720     if( db->mallocFailed ){
 70484         -    p->rc = SQLITE_NOMEM;
        70721  +    p->rc = SQLITE_NOMEM_BKPT;
 70485  70722     }
 70486  70723   
 70487  70724     /* If the auto-commit flag is set to true, then any locks that were held
 70488  70725     ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
 70489  70726     ** to invoke any required unlock-notify callbacks.
 70490  70727     */
 70491  70728     if( db->autoCommit ){
................................................................................
 70664  70901   **
 70665  70902   **    * the associated function parameter is the 32nd or later (counting
 70666  70903   **      from left to right), or
 70667  70904   **
 70668  70905   **    * the corresponding bit in argument mask is clear (where the first
 70669  70906   **      function parameter corresponds to bit 0 etc.).
 70670  70907   */
 70671         -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
 70672         -  AuxData **pp = &pVdbe->pAuxData;
        70908  +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
 70673  70909     while( *pp ){
 70674  70910       AuxData *pAux = *pp;
 70675  70911       if( (iOp<0)
 70676  70912        || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
 70677  70913       ){
 70678  70914         testcase( pAux->iArg==31 );
 70679  70915         if( pAux->xDelete ){
 70680  70916           pAux->xDelete(pAux->pAux);
 70681  70917         }
 70682  70918         *pp = pAux->pNext;
 70683         -      sqlite3DbFree(pVdbe->db, pAux);
        70919  +      sqlite3DbFree(db, pAux);
 70684  70920       }else{
 70685  70921         pp= &pAux->pNext;
 70686  70922       }
 70687  70923     }
 70688  70924   }
 70689  70925   
 70690  70926   /*
................................................................................
 71455  71691       sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
 71456  71692       sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
 71457  71693       v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
 71458  71694       n1 = v1==0 ? 0 : c1.n;
 71459  71695       v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
 71460  71696       n2 = v2==0 ? 0 : c2.n;
 71461  71697       rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
 71462         -    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
        71698  +    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
 71463  71699       sqlite3VdbeMemRelease(&c1);
 71464  71700       sqlite3VdbeMemRelease(&c2);
 71465  71701       return rc;
 71466  71702     }
 71467  71703   }
 71468  71704   
 71469  71705   /*
................................................................................
 72730  72966                          SQLITE_UTF8, SQLITE_STATIC);
 72731  72967   }
 72732  72968   
 72733  72969   /* An SQLITE_NOMEM error. */
 72734  72970   SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
 72735  72971     assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 72736  72972     sqlite3VdbeMemSetNull(pCtx->pOut);
 72737         -  pCtx->isError = SQLITE_NOMEM;
        72973  +  pCtx->isError = SQLITE_NOMEM_BKPT;
 72738  72974     pCtx->fErrorOrAux = 1;
 72739  72975     sqlite3OomFault(pCtx->pOut->db);
 72740  72976   }
 72741  72977   
 72742  72978   /*
 72743  72979   ** This function is called after a transaction has been committed. It 
 72744  72980   ** invokes callbacks registered with sqlite3_wal_hook() as required.
................................................................................
 72806  73042   #endif
 72807  73043     }
 72808  73044   
 72809  73045     /* Check that malloc() has not failed. If it has, return early. */
 72810  73046     db = p->db;
 72811  73047     if( db->mallocFailed ){
 72812  73048       p->rc = SQLITE_NOMEM;
 72813         -    return SQLITE_NOMEM;
        73049  +    return SQLITE_NOMEM_BKPT;
 72814  73050     }
 72815  73051   
 72816  73052     if( p->pc<=0 && p->expired ){
 72817  73053       p->rc = SQLITE_SCHEMA;
 72818  73054       rc = SQLITE_ERROR;
 72819  73055       goto end_of_step;
 72820  73056     }
................................................................................
 72869  73105       if( p->rc!=SQLITE_OK ){
 72870  73106         rc = SQLITE_ERROR;
 72871  73107       }
 72872  73108     }
 72873  73109   
 72874  73110     db->errCode = rc;
 72875  73111     if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
 72876         -    p->rc = SQLITE_NOMEM;
        73112  +    p->rc = SQLITE_NOMEM_BKPT;
 72877  73113     }
 72878  73114   end_of_step:
 72879  73115     /* At this point local variable rc holds the value that should be 
 72880  73116     ** returned if this statement was compiled using the legacy 
 72881  73117     ** sqlite3_prepare() interface. According to the docs, this can only
 72882  73118     ** be one of the values in the first assert() below. Variable p->rc 
 72883  73119     ** contains the value that would be returned if sqlite3_finalize() 
................................................................................
 72936  73172       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
 72937  73173       sqlite3DbFree(db, v->zErrMsg);
 72938  73174       if( !db->mallocFailed ){
 72939  73175         v->zErrMsg = sqlite3DbStrDup(db, zErr);
 72940  73176         v->rc = rc2;
 72941  73177       } else {
 72942  73178         v->zErrMsg = 0;
 72943         -      v->rc = rc = SQLITE_NOMEM;
        73179  +      v->rc = rc = SQLITE_NOMEM_BKPT;
 72944  73180       }
 72945  73181     }
 72946  73182     rc = sqlite3ApiExit(db, rc);
 72947  73183     sqlite3_mutex_leave(db->mutex);
 72948  73184     return rc;
 72949  73185   }
 72950  73186   
................................................................................
 73560  73796   SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
 73561  73797     sqlite3_stmt *pStmt, 
 73562  73798     int i, 
 73563  73799     const void *zData, 
 73564  73800     int nData, 
 73565  73801     void (*xDel)(void*)
 73566  73802   ){
        73803  +#ifdef SQLITE_ENABLE_API_ARMOR
        73804  +  if( nData<0 ) return SQLITE_MISUSE_BKPT;
        73805  +#endif
 73567  73806     return bindText(pStmt, i, zData, nData, xDel, 0);
 73568  73807   }
 73569  73808   SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
 73570  73809     sqlite3_stmt *pStmt, 
 73571  73810     int i, 
 73572  73811     const void *zData, 
 73573  73812     sqlite3_uint64 nData, 
................................................................................
 74316  74555     **     different sized allocations. Memory cells provide growable
 74317  74556     **     allocations.
 74318  74557     **
 74319  74558     **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
 74320  74559     **     be freed lazily via the sqlite3_release_memory() API. This
 74321  74560     **     minimizes the number of malloc calls made by the system.
 74322  74561     **
 74323         -  ** Memory cells for cursors are allocated at the top of the address
 74324         -  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
 74325         -  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
        74562  +  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
        74563  +  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
        74564  +  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
 74326  74565     */
 74327         -  Mem *pMem = &p->aMem[p->nMem-iCur];
        74566  +  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
 74328  74567   
 74329  74568     int nByte;
 74330  74569     VdbeCursor *pCx = 0;
 74331  74570     nByte = 
 74332  74571         ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
 74333  74572         (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
 74334  74573   
 74335         -  assert( iCur<p->nCursor );
        74574  +  assert( iCur>=0 && iCur<p->nCursor );
 74336  74575     if( p->apCsr[iCur] ){
 74337  74576       sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
 74338  74577       p->apCsr[iCur] = 0;
 74339  74578     }
 74340  74579     if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 74341  74580       p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
 74342  74581       memset(pCx, 0, sizeof(VdbeCursor));
................................................................................
 74742  74981     sqlite3VdbeMemSetNull(pOut);
 74743  74982     pOut->flags = MEM_Int;
 74744  74983     return pOut;
 74745  74984   }
 74746  74985   static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
 74747  74986     Mem *pOut;
 74748  74987     assert( pOp->p2>0 );
 74749         -  assert( pOp->p2<=(p->nMem-p->nCursor) );
        74988  +  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 74750  74989     pOut = &p->aMem[pOp->p2];
 74751  74990     memAboutToChange(p, pOut);
 74752  74991     if( VdbeMemDynamic(pOut) ){
 74753  74992       return out2PrereleaseWithClear(pOut);
 74754  74993     }else{
 74755  74994       pOut->flags = MEM_Int;
 74756  74995       return pOut;
................................................................................
 74840  75079           }
 74841  75080         }
 74842  75081       }
 74843  75082       if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
 74844  75083     }
 74845  75084     sqlite3EndBenignMalloc();
 74846  75085   #endif
 74847         -  for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
        75086  +  for(pOp=&aOp[p->pc]; 1; pOp++){
        75087  +    /* Errors are detected by individual opcodes, with an immediate
        75088  +    ** jumps to abort_due_to_error. */
        75089  +    assert( rc==SQLITE_OK );
        75090  +
 74848  75091       assert( pOp>=aOp && pOp<&aOp[p->nOp]);
 74849  75092   #ifdef VDBE_PROFILE
 74850  75093       start = sqlite3Hwtime();
 74851  75094   #endif
 74852  75095       nVmStep++;
 74853  75096   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 74854  75097       if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
................................................................................
 74876  75119   #endif
 74877  75120   
 74878  75121       /* Sanity checking on other operands */
 74879  75122   #ifdef SQLITE_DEBUG
 74880  75123       assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
 74881  75124       if( (pOp->opflags & OPFLG_IN1)!=0 ){
 74882  75125         assert( pOp->p1>0 );
 74883         -      assert( pOp->p1<=(p->nMem-p->nCursor) );
        75126  +      assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
 74884  75127         assert( memIsValid(&aMem[pOp->p1]) );
 74885  75128         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
 74886  75129         REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
 74887  75130       }
 74888  75131       if( (pOp->opflags & OPFLG_IN2)!=0 ){
 74889  75132         assert( pOp->p2>0 );
 74890         -      assert( pOp->p2<=(p->nMem-p->nCursor) );
        75133  +      assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 74891  75134         assert( memIsValid(&aMem[pOp->p2]) );
 74892  75135         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
 74893  75136         REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
 74894  75137       }
 74895  75138       if( (pOp->opflags & OPFLG_IN3)!=0 ){
 74896  75139         assert( pOp->p3>0 );
 74897         -      assert( pOp->p3<=(p->nMem-p->nCursor) );
        75140  +      assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 74898  75141         assert( memIsValid(&aMem[pOp->p3]) );
 74899  75142         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
 74900  75143         REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
 74901  75144       }
 74902  75145       if( (pOp->opflags & OPFLG_OUT2)!=0 ){
 74903  75146         assert( pOp->p2>0 );
 74904         -      assert( pOp->p2<=(p->nMem-p->nCursor) );
        75147  +      assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 74905  75148         memAboutToChange(p, &aMem[pOp->p2]);
 74906  75149       }
 74907  75150       if( (pOp->opflags & OPFLG_OUT3)!=0 ){
 74908  75151         assert( pOp->p3>0 );
 74909         -      assert( pOp->p3<=(p->nMem-p->nCursor) );
        75152  +      assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 74910  75153         memAboutToChange(p, &aMem[pOp->p3]);
 74911  75154       }
 74912  75155   #endif
 74913  75156   #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 74914  75157       pOrigOp = pOp;
 74915  75158   #endif
 74916  75159     
................................................................................
 74987  75230     ** a return code SQLITE_ABORT.
 74988  75231     */
 74989  75232     if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
 74990  75233       assert( db->nProgressOps!=0 );
 74991  75234       nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
 74992  75235       if( db->xProgress(db->pProgressArg) ){
 74993  75236         rc = SQLITE_INTERRUPT;
 74994         -      goto vdbe_error_halt;
        75237  +      goto abort_due_to_error;
 74995  75238       }
 74996  75239     }
 74997  75240   #endif
 74998  75241     
 74999  75242     break;
 75000  75243   }
 75001  75244   
 75002  75245   /* Opcode:  Gosub P1 P2 * * *
 75003  75246   **
 75004  75247   ** Write the current address onto register P1
 75005  75248   ** and then jump to address P2.
 75006  75249   */
 75007  75250   case OP_Gosub: {            /* jump */
 75008         -  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
        75251  +  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 75009  75252     pIn1 = &aMem[pOp->p1];
 75010  75253     assert( VdbeMemDynamic(pIn1)==0 );
 75011  75254     memAboutToChange(p, pIn1);
 75012  75255     pIn1->flags = MEM_Int;
 75013  75256     pIn1->u.i = (int)(pOp-aOp);
 75014  75257     REGISTER_TRACE(pOp->p1, pIn1);
 75015  75258   
................................................................................
 75041  75284   ** If P2!=0 then the coroutine implementation immediately follows
 75042  75285   ** this opcode.  So jump over the coroutine implementation to
 75043  75286   ** address P2.
 75044  75287   **
 75045  75288   ** See also: EndCoroutine
 75046  75289   */
 75047  75290   case OP_InitCoroutine: {     /* jump */
 75048         -  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
        75291  +  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
 75049  75292     assert( pOp->p2>=0 && pOp->p2<p->nOp );
 75050  75293     assert( pOp->p3>=0 && pOp->p3<p->nOp );
 75051  75294     pOut = &aMem[pOp->p1];
 75052  75295     assert( !VdbeMemDynamic(pOut) );
 75053  75296     pOut->u.i = pOp->p3 - 1;
 75054  75297     pOut->flags = MEM_Int;
 75055  75298     if( pOp->p2 ) goto jump_to_p2;
................................................................................
 75266  75509     pOut = out2Prerelease(p, pOp);
 75267  75510     pOp->opcode = OP_String;
 75268  75511     pOp->p1 = sqlite3Strlen30(pOp->p4.z);
 75269  75512   
 75270  75513   #ifndef SQLITE_OMIT_UTF16
 75271  75514     if( encoding!=SQLITE_UTF8 ){
 75272  75515       rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
 75273         -    if( rc==SQLITE_TOOBIG ) goto too_big;
        75516  +    if( rc ){
        75517  +      assert( rc==SQLITE_TOOBIG ); /* This is the only possible error here */
        75518  +      goto too_big;
        75519  +    }
 75274  75520       if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
 75275  75521       assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
 75276  75522       assert( VdbeMemDynamic(pOut)==0 );
 75277  75523       pOut->szMalloc = 0;
 75278  75524       pOut->flags |= MEM_Static;
 75279  75525       if( pOp->p4type==P4_DYNAMIC ){
 75280  75526         sqlite3DbFree(db, pOp->p4.z);
................................................................................
 75307  75553     pOut->z = pOp->p4.z;
 75308  75554     pOut->n = pOp->p1;
 75309  75555     pOut->enc = encoding;
 75310  75556     UPDATE_MAX_BLOBSIZE(pOut);
 75311  75557   #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
 75312  75558     if( pOp->p5 ){
 75313  75559       assert( pOp->p3>0 );
 75314         -    assert( pOp->p3<=(p->nMem-p->nCursor) );
        75560  +    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 75315  75561       pIn3 = &aMem[pOp->p3];
 75316  75562       assert( pIn3->flags & MEM_Int );
 75317  75563       if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
 75318  75564     }
 75319  75565   #endif
 75320  75566     break;
 75321  75567   }
................................................................................
 75333  75579   ** OP_Ne or OP_Eq.
 75334  75580   */
 75335  75581   case OP_Null: {           /* out2 */
 75336  75582     int cnt;
 75337  75583     u16 nullFlag;
 75338  75584     pOut = out2Prerelease(p, pOp);
 75339  75585     cnt = pOp->p3-pOp->p2;
 75340         -  assert( pOp->p3<=(p->nMem-p->nCursor) );
        75586  +  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 75341  75587     pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
 75342  75588     while( cnt>0 ){
 75343  75589       pOut++;
 75344  75590       memAboutToChange(p, pOut);
 75345  75591       sqlite3VdbeMemSetNull(pOut);
 75346  75592       pOut->flags = nullFlag;
 75347  75593       cnt--;
................................................................................
 75354  75600   **
 75355  75601   ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
 75356  75602   ** instruction, but do not free any string or blob memory associated with
 75357  75603   ** the register, so that if the value was a string or blob that was
 75358  75604   ** previously copied using OP_SCopy, the copies will continue to be valid.
 75359  75605   */
 75360  75606   case OP_SoftNull: {
 75361         -  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
        75607  +  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 75362  75608     pOut = &aMem[pOp->p1];
 75363  75609     pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
 75364  75610     break;
 75365  75611   }
 75366  75612   
 75367  75613   /* Opcode: Blob P1 P2 * P4 *
 75368  75614   ** Synopsis: r[P2]=P4 (len=P1)
................................................................................
 75421  75667     p2 = pOp->p2;
 75422  75668     assert( n>0 && p1>0 && p2>0 );
 75423  75669     assert( p1+n<=p2 || p2+n<=p1 );
 75424  75670   
 75425  75671     pIn1 = &aMem[p1];
 75426  75672     pOut = &aMem[p2];
 75427  75673     do{
 75428         -    assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
 75429         -    assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
        75674  +    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
        75675  +    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
 75430  75676       assert( memIsValid(pIn1) );
 75431  75677       memAboutToChange(p, pOut);
 75432  75678       sqlite3VdbeMemMove(pOut, pIn1);
 75433  75679   #ifdef SQLITE_DEBUG
 75434  75680       if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
 75435  75681         pOut->pScopyFrom += pOp->p2 - p1;
 75436  75682       }
................................................................................
 75522  75768   ** the result row.
 75523  75769   */
 75524  75770   case OP_ResultRow: {
 75525  75771     Mem *pMem;
 75526  75772     int i;
 75527  75773     assert( p->nResColumn==pOp->p2 );
 75528  75774     assert( pOp->p1>0 );
 75529         -  assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
        75775  +  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
 75530  75776   
 75531  75777   #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 75532  75778     /* Run the progress counter just before returning.
 75533  75779     */
 75534  75780     if( db->xProgress!=0
 75535  75781      && nVmStep>=nProgressLimit
 75536  75782      && db->xProgress(db->pProgressArg)!=0
 75537  75783     ){
 75538  75784       rc = SQLITE_INTERRUPT;
 75539         -    goto vdbe_error_halt;
        75785  +    goto abort_due_to_error;
 75540  75786     }
 75541  75787   #endif
 75542  75788   
 75543  75789     /* If this statement has violated immediate foreign key constraints, do
 75544  75790     ** not return the number of rows modified. And do not RELEASE the statement
 75545  75791     ** transaction. It needs to be rolled back.  */
 75546  75792     if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
 75547  75793       assert( db->flags&SQLITE_CountRows );
 75548  75794       assert( p->usesStmtJournal );
 75549         -    break;
        75795  +    goto abort_due_to_error;
 75550  75796     }
 75551  75797   
 75552  75798     /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
 75553  75799     ** DML statements invoke this opcode to return the number of rows 
 75554  75800     ** modified to the user. This is the only way that a VM that
 75555  75801     ** opens a statement transaction may invoke this opcode.
 75556  75802     **
................................................................................
 75562  75808     ** may lead to overlapping statement transactions.
 75563  75809     **
 75564  75810     ** The statement transaction is never a top-level transaction.  Hence
 75565  75811     ** the RELEASE call below can never fail.
 75566  75812     */
 75567  75813     assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
 75568  75814     rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
 75569         -  if( NEVER(rc!=SQLITE_OK) ){
 75570         -    break;
 75571         -  }
        75815  +  assert( rc==SQLITE_OK );
 75572  75816   
 75573  75817     /* Invalidate all ephemeral cursor row caches */
 75574  75818     p->cacheCtr = (p->cacheCtr + 2)|1;
 75575  75819   
 75576  75820     /* Make sure the results of the current row are \000 terminated
 75577  75821     ** and have an assigned type.  The results are de-ephemeralized as
 75578  75822     ** a side effect.
................................................................................
 75836  76080   */
 75837  76081   case OP_Function0: {
 75838  76082     int n;
 75839  76083     sqlite3_context *pCtx;
 75840  76084   
 75841  76085     assert( pOp->p4type==P4_FUNCDEF );
 75842  76086     n = pOp->p5;
 75843         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 75844         -  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
        76087  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
        76088  +  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 75845  76089     assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 75846  76090     pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
 75847  76091     if( pCtx==0 ) goto no_mem;
 75848  76092     pCtx->pOut = 0;
 75849  76093     pCtx->pFunc = pOp->p4.pFunc;
 75850  76094     pCtx->iOp = (int)(pOp - aOp);
 75851  76095     pCtx->pVdbe = p;
................................................................................
 75887  76131   
 75888  76132     /* If the function returned an error, throw an exception */
 75889  76133     if( pCtx->fErrorOrAux ){
 75890  76134       if( pCtx->isError ){
 75891  76135         sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
 75892  76136         rc = pCtx->isError;
 75893  76137       }
 75894         -    sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
        76138  +    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
        76139  +    if( rc ) goto abort_due_to_error;
 75895  76140     }
 75896  76141   
 75897  76142     /* Copy the result of the function into register P3 */
 75898  76143     if( pOut->flags & (MEM_Str|MEM_Blob) ){
 75899  76144       sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
 75900  76145       if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
 75901  76146     }
................................................................................
 76071  76316     testcase( pOp->p2==SQLITE_AFF_INTEGER );
 76072  76317     testcase( pOp->p2==SQLITE_AFF_REAL );
 76073  76318     pIn1 = &aMem[pOp->p1];
 76074  76319     memAboutToChange(p, pIn1);
 76075  76320     rc = ExpandBlob(pIn1);
 76076  76321     sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
 76077  76322     UPDATE_MAX_BLOBSIZE(pIn1);
        76323  +  if( rc ) goto abort_due_to_error;
 76078  76324     break;
 76079  76325   }
 76080  76326   #endif /* SQLITE_OMIT_CAST */
 76081  76327   
 76082  76328   /* Opcode: Lt P1 P2 P3 P4 P5
 76083  76329   ** Synopsis: if r[P1]<r[P3] goto P2
 76084  76330   **
................................................................................
 76335  76581     assert( pKeyInfo!=0 );
 76336  76582     p1 = pOp->p1;
 76337  76583     p2 = pOp->p2;
 76338  76584   #if SQLITE_DEBUG
 76339  76585     if( aPermute ){
 76340  76586       int k, mx = 0;
 76341  76587       for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
 76342         -    assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
 76343         -    assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
        76588  +    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
        76589  +    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
 76344  76590     }else{
 76345         -    assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
 76346         -    assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
        76591  +    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
        76592  +    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
 76347  76593     }
 76348  76594   #endif /* SQLITE_DEBUG */
 76349  76595     for(i=0; i<n; i++){
 76350  76596       idx = aPermute ? aPermute[i] : i;
 76351  76597       assert( memIsValid(&aMem[p1+idx]) );
 76352  76598       assert( memIsValid(&aMem[p2+idx]) );
 76353  76599       REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
................................................................................
 76601  76847   
 76602  76848     pC = p->apCsr[pOp->p1];
 76603  76849     p2 = pOp->p2;
 76604  76850   
 76605  76851     /* If the cursor cache is stale, bring it up-to-date */
 76606  76852     rc = sqlite3VdbeCursorMoveto(&pC, &p2);
 76607  76853   
 76608         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
        76854  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 76609  76855     pDest = &aMem[pOp->p3];
 76610  76856     memAboutToChange(p, pDest);
 76611  76857     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 76612  76858     assert( pC!=0 );
 76613  76859     assert( p2<pC->nField );
 76614  76860     aOffset = pC->aOffset;
 76615  76861     assert( pC->eCurType!=CURTYPE_VTAB );
................................................................................
 76680  76926         ** types use so much data space that there can only be 4096 and 32 of
 76681  76927         ** them, respectively.  So the maximum header length results from a
 76682  76928         ** 3-byte type for each of the maximum of 32768 columns plus three
 76683  76929         ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
 76684  76930         */
 76685  76931         if( offset > 98307 || offset > pC->payloadSize ){
 76686  76932           rc = SQLITE_CORRUPT_BKPT;
 76687         -        goto op_column_error;
        76933  +        goto abort_due_to_error;
 76688  76934         }
 76689  76935       }
 76690  76936   
 76691  76937       /* The following goto is an optimization.  It can be omitted and
 76692  76938       ** everything will still work.  But OP_Column is measurably faster
 76693  76939       ** by skipping the subsequent conditional, which is always true.
 76694  76940       */
................................................................................
 76705  76951       */
 76706  76952       op_column_read_header:
 76707  76953       if( pC->iHdrOffset<aOffset[0] ){
 76708  76954         /* Make sure zData points to enough of the record to cover the header. */
 76709  76955         if( pC->aRow==0 ){
 76710  76956           memset(&sMem, 0, sizeof(sMem));
 76711  76957           rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
 76712         -        if( rc!=SQLITE_OK ) goto op_column_error;
        76958  +        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 76713  76959           zData = (u8*)sMem.z;
 76714  76960         }else{
 76715  76961           zData = pC->aRow;
 76716  76962         }
 76717  76963     
 76718  76964         /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
 76719  76965         i = pC->nHdrParsed;
................................................................................
 76741  76987         ** (2) the entire header was used but not all data was used
 76742  76988         ** (3) the end of the data extends beyond the end of the record.
 76743  76989         */
 76744  76990         if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
 76745  76991          || (offset64 > pC->payloadSize)
 76746  76992         ){
 76747  76993           rc = SQLITE_CORRUPT_BKPT;
 76748         -        goto op_column_error;
        76994  +        goto abort_due_to_error;
 76749  76995         }
 76750  76996       }else{
 76751  76997         t = 0;
 76752  76998       }
 76753  76999   
 76754  77000       /* If after trying to extract new entries from the header, nHdrParsed is
 76755  77001       ** still not up to p2, that means that the record has fewer than p2
................................................................................
 76814  77060         ** So we might as well use bogus content rather than reading
 76815  77061         ** content from disk. */
 76816  77062         static u8 aZero[8];  /* This is the bogus content */
 76817  77063         sqlite3VdbeSerialGet(aZero, t, pDest);
 76818  77064       }else{
 76819  77065         rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
 76820  77066                                      pDest);
 76821         -      if( rc==SQLITE_OK ){
 76822         -        sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
 76823         -        pDest->flags &= ~MEM_Ephem;
 76824         -      }
        77067  +      if( rc!=SQLITE_OK ) goto abort_due_to_error;
        77068  +      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
        77069  +      pDest->flags &= ~MEM_Ephem;
 76825  77070       }
 76826  77071     }
 76827  77072   
 76828  77073   op_column_out:
 76829         -op_column_error:
 76830  77074     UPDATE_MAX_BLOBSIZE(pDest);
 76831  77075     REGISTER_TRACE(pOp->p3, pDest);
 76832  77076     break;
 76833  77077   }
 76834  77078   
 76835  77079   /* Opcode: Affinity P1 P2 * P4 *
 76836  77080   ** Synopsis: affinity(r[P1@P2])
................................................................................
 76846  77090     char cAff;               /* A single character of affinity */
 76847  77091   
 76848  77092     zAffinity = pOp->p4.z;
 76849  77093     assert( zAffinity!=0 );
 76850  77094     assert( zAffinity[pOp->p2]==0 );
 76851  77095     pIn1 = &aMem[pOp->p1];
 76852  77096     while( (cAff = *(zAffinity++))!=0 ){
 76853         -    assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
        77097  +    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
 76854  77098       assert( memIsValid(pIn1) );
 76855  77099       applyAffinity(pIn1, cAff, encoding);
 76856  77100       pIn1++;
 76857  77101     }
 76858  77102     break;
 76859  77103   }
 76860  77104   
................................................................................
 76908  77152     ** of the record to data0.
 76909  77153     */
 76910  77154     nData = 0;         /* Number of bytes of data space */
 76911  77155     nHdr = 0;          /* Number of bytes of header space */
 76912  77156     nZero = 0;         /* Number of zero bytes at the end of the record */
 76913  77157     nField = pOp->p1;
 76914  77158     zAffinity = pOp->p4.z;
 76915         -  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
        77159  +  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
 76916  77160     pData0 = &aMem[nField];
 76917  77161     nField = pOp->p2;
 76918  77162     pLast = &pData0[nField-1];
 76919  77163     file_format = p->minWriteFileFormat;
 76920  77164   
 76921  77165     /* Identify the output register */
 76922  77166     assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
................................................................................
 76998  77242       /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
 76999  77243       ** immediately follow the header. */
 77000  77244       j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
 77001  77245     }while( (++pRec)<=pLast );
 77002  77246     assert( i==nHdr );
 77003  77247     assert( j==nByte );
 77004  77248   
 77005         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
        77249  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 77006  77250     pOut->n = (int)nByte;
 77007  77251     pOut->flags = MEM_Blob;
 77008  77252     if( nZero ){
 77009  77253       pOut->u.nZero = nZero;
 77010  77254       pOut->flags |= MEM_Zero;
 77011  77255     }
 77012  77256     pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
................................................................................
 77027  77271     BtCursor *pCrsr;
 77028  77272   
 77029  77273     assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
 77030  77274     pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
 77031  77275     assert( pCrsr );
 77032  77276     nEntry = 0;  /* Not needed.  Only used to silence a warning. */
 77033  77277     rc = sqlite3BtreeCount(pCrsr, &nEntry);
        77278  +  if( rc ) goto abort_due_to_error;
 77034  77279     pOut = out2Prerelease(p, pOp);
 77035  77280     pOut->u.i = nEntry;
 77036  77281     break;
 77037  77282   }
 77038  77283   #endif
 77039  77284   
 77040  77285   /* Opcode: Savepoint P1 * * P4 *
................................................................................
 77204  77449   
 77205  77450         if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
 77206  77451           rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
 77207  77452           if( rc!=SQLITE_OK ) goto abort_due_to_error;
 77208  77453         }
 77209  77454       }
 77210  77455     }
        77456  +  if( rc ) goto abort_due_to_error;
 77211  77457   
 77212  77458     break;
 77213  77459   }
 77214  77460   
 77215  77461   /* Opcode: AutoCommit P1 P2 * * *
 77216  77462   **
 77217  77463   ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
................................................................................
 77240  77486       }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
 77241  77487         /* If this instruction implements a COMMIT and other VMs are writing
 77242  77488         ** return an error indicating that the other VMs must complete first. 
 77243  77489         */
 77244  77490         sqlite3VdbeError(p, "cannot commit transaction - "
 77245  77491                             "SQL statements in progress");
 77246  77492         rc = SQLITE_BUSY;
 77247         -      break;
        77493  +      goto abort_due_to_error;
 77248  77494       }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 77249  77495         goto vdbe_return;
 77250  77496       }else{
 77251  77497         db->autoCommit = (u8)desiredAutoCommit;
 77252  77498       }
 77253  77499       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 77254  77500         p->pc = (int)(pOp - aOp);
................................................................................
 77267  77513     }else{
 77268  77514       sqlite3VdbeError(p,
 77269  77515           (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
 77270  77516           (iRollback)?"cannot rollback - no transaction is active":
 77271  77517                      "cannot commit - no transaction is active"));
 77272  77518            
 77273  77519       rc = SQLITE_ERROR;
        77520  +    goto abort_due_to_error;
 77274  77521     }
 77275  77522     break;
 77276  77523   }
 77277  77524   
 77278  77525   /* Opcode: Transaction P1 P2 P3 P4 P5
 77279  77526   **
 77280  77527   ** Begin a transaction on database P1 if a transaction is not already
................................................................................
 77389  77636       */
 77390  77637       if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
 77391  77638         sqlite3ResetOneSchema(db, pOp->p1);
 77392  77639       }
 77393  77640       p->expired = 1;
 77394  77641       rc = SQLITE_SCHEMA;
 77395  77642     }
        77643  +  if( rc ) goto abort_due_to_error;
 77396  77644     break;
 77397  77645   }
 77398  77646   
 77399  77647   /* Opcode: ReadCookie P1 P2 P3 * *
 77400  77648   **
 77401  77649   ** Read cookie number P3 from database P1 and write it into register P2.
 77402  77650   ** P3==1 is the schema version.  P3==2 is the database format.
................................................................................
 77458  77706     }
 77459  77707     if( pOp->p1==1 ){
 77460  77708       /* Invalidate all prepared statements whenever the TEMP database
 77461  77709       ** schema is changed.  Ticket #1644 */
 77462  77710       sqlite3ExpirePreparedStatements(db);
 77463  77711       p->expired = 0;
 77464  77712     }
        77713  +  if( rc ) goto abort_due_to_error;
 77465  77714     break;
 77466  77715   }
 77467  77716   
 77468  77717   /* Opcode: OpenRead P1 P2 P3 P4 P5
 77469  77718   ** Synopsis: root=P2 iDb=P3
 77470  77719   **
 77471  77720   ** Open a read-only cursor for the database table whose root page is
................................................................................
 77555  77804     assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
 77556  77805     assert( p->bIsReader );
 77557  77806     assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
 77558  77807             || p->readOnly==0 );
 77559  77808   
 77560  77809     if( p->expired ){
 77561  77810       rc = SQLITE_ABORT_ROLLBACK;
 77562         -    break;
        77811  +    goto abort_due_to_error;
 77563  77812     }
 77564  77813   
 77565  77814     nField = 0;
 77566  77815     pKeyInfo = 0;
 77567  77816     p2 = pOp->p2;
 77568  77817     iDb = pOp->p3;
 77569  77818     assert( iDb>=0 && iDb<db->nDb );
................................................................................
 77579  77828         p->minWriteFileFormat = pDb->pSchema->file_format;
 77580  77829       }
 77581  77830     }else{
 77582  77831       wrFlag = 0;
 77583  77832     }
 77584  77833     if( pOp->p5 & OPFLAG_P2ISREG ){
 77585  77834       assert( p2>0 );
 77586         -    assert( p2<=(p->nMem-p->nCursor) );
        77835  +    assert( p2<=(p->nMem+1 - p->nCursor) );
 77587  77836       pIn2 = &aMem[p2];
 77588  77837       assert( memIsValid(pIn2) );
 77589  77838       assert( (pIn2->flags & MEM_Int)!=0 );
 77590  77839       sqlite3VdbeMemIntegerify(pIn2);
 77591  77840       p2 = (int)pIn2->u.i;
 77592  77841       /* The p2 value always comes from a prior OP_CreateTable opcode and
 77593  77842       ** that opcode will always set the p2 value to 2 or more or else fail.
 77594  77843       ** If there were a failure, the prepared statement would have halted
 77595  77844       ** before reaching this instruction. */
 77596         -    if( NEVER(p2<2) ) {
 77597         -      rc = SQLITE_CORRUPT_BKPT;
 77598         -      goto abort_due_to_error;
 77599         -    }
        77845  +    assert( p2>=2 );
 77600  77846     }
 77601  77847     if( pOp->p4type==P4_KEYINFO ){
 77602  77848       pKeyInfo = pOp->p4.pKeyInfo;
 77603  77849       assert( pKeyInfo->enc==ENC(db) );
 77604  77850       assert( pKeyInfo->db==db );
 77605  77851       nField = pKeyInfo->nField+pKeyInfo->nXField;
 77606  77852     }else if( pOp->p4type==P4_INT32 ){
................................................................................
 77630  77876     assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
 77631  77877     testcase( pOp->p5 & OPFLAG_BULKCSR );
 77632  77878   #ifdef SQLITE_ENABLE_CURSOR_HINTS
 77633  77879     testcase( pOp->p2 & OPFLAG_SEEKEQ );
 77634  77880   #endif
 77635  77881     sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
 77636  77882                                  (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
        77883  +  if( rc ) goto abort_due_to_error;
 77637  77884     break;
 77638  77885   }
 77639  77886   
 77640  77887   /* Opcode: OpenEphemeral P1 P2 * P4 P5
 77641  77888   ** Synopsis: nColumn=P2
 77642  77889   **
 77643  77890   ** Open a new cursor P1 to a transient table.
................................................................................
 77706  77953         pCx->isTable = 0;
 77707  77954       }else{
 77708  77955         rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
 77709  77956                                 0, pCx->uc.pCursor);
 77710  77957         pCx->isTable = 1;
 77711  77958       }
 77712  77959     }
        77960  +  if( rc ) goto abort_due_to_error;
 77713  77961     pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
 77714  77962     break;
 77715  77963   }
 77716  77964   
 77717  77965   /* Opcode: SorterOpen P1 P2 P3 P4 *
 77718  77966   **
 77719  77967   ** This opcode works like OP_OpenEphemeral except that it opens
................................................................................
 77731  77979     assert( pOp->p2>=0 );
 77732  77980     pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
 77733  77981     if( pCx==0 ) goto no_mem;
 77734  77982     pCx->pKeyInfo = pOp->p4.pKeyInfo;
 77735  77983     assert( pCx->pKeyInfo->db==db );
 77736  77984     assert( pCx->pKeyInfo->enc==ENC(db) );
 77737  77985     rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
        77986  +  if( rc ) goto abort_due_to_error;
 77738  77987     break;
 77739  77988   }
 77740  77989   
 77741  77990   /* Opcode: SequenceTest P1 P2 * * *
 77742  77991   ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
 77743  77992   **
 77744  77993   ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
................................................................................
 78193  78442           break;
 78194  78443         }
 78195  78444       }
 78196  78445     }
 78197  78446     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
 78198  78447     sqlite3DbFree(db, pFree);
 78199  78448     if( rc!=SQLITE_OK ){
 78200         -    break;
        78449  +    goto abort_due_to_error;
 78201  78450     }
 78202  78451     pC->seekResult = res;
 78203  78452     alreadyExists = (res==0);
 78204  78453     pC->nullRow = 1-alreadyExists;
 78205  78454     pC->deferredMoveto = 0;
 78206  78455     pC->cacheStatus = CACHE_STALE;
 78207  78456     if( pOp->opcode==OP_Found ){
................................................................................
 78265  78514       assert( rc==SQLITE_OK );
 78266  78515       if( pOp->p2==0 ){
 78267  78516         rc = SQLITE_CORRUPT_BKPT;
 78268  78517       }else{
 78269  78518         goto jump_to_p2;
 78270  78519       }
 78271  78520     }
        78521  +  if( rc ) goto abort_due_to_error;
 78272  78522     break;
 78273  78523   }
 78274  78524   
 78275  78525   /* Opcode: Sequence P1 P2 * * *
 78276  78526   ** Synopsis: r[P2]=cursor[P1].ctr++
 78277  78527   **
 78278  78528   ** Find the next available sequence number for cursor P1.
................................................................................
 78373  78623         if( p->pFrame ){
 78374  78624           for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 78375  78625           /* Assert that P3 is a valid memory cell. */
 78376  78626           assert( pOp->p3<=pFrame->nMem );
 78377  78627           pMem = &pFrame->aMem[pOp->p3];
 78378  78628         }else{
 78379  78629           /* Assert that P3 is a valid memory cell. */
 78380         -        assert( pOp->p3<=(p->nMem-p->nCursor) );
        78630  +        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 78381  78631           pMem = &aMem[pOp->p3];
 78382  78632           memAboutToChange(p, pMem);
 78383  78633         }
 78384  78634         assert( memIsValid(pMem) );
 78385  78635   
 78386  78636         REGISTER_TRACE(pOp->p3, pMem);
 78387  78637         sqlite3VdbeMemIntegerify(pMem);
................................................................................
 78407  78657         do{
 78408  78658           sqlite3_randomness(sizeof(v), &v);
 78409  78659           v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
 78410  78660         }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
 78411  78661                                                    0, &res))==SQLITE_OK)
 78412  78662               && (res==0)
 78413  78663               && (++cnt<100));
 78414         -      if( rc==SQLITE_OK && res==0 ){
        78664  +      if( rc ) goto abort_due_to_error;
        78665  +      if( res==0 ){
 78415  78666           rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
 78416  78667           goto abort_due_to_error;
 78417  78668         }
 78418  78669         assert( v>0 );  /* EV: R-40812-03570 */
 78419  78670       }
 78420  78671       pC->deferredMoveto = 0;
 78421  78672       pC->cacheStatus = CACHE_STALE;
................................................................................
 78521  78772                             pData->z, pData->n, nZero,
 78522  78773                             (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
 78523  78774     );
 78524  78775     pC->deferredMoveto = 0;
 78525  78776     pC->cacheStatus = CACHE_STALE;
 78526  78777   
 78527  78778     /* Invoke the update-hook if required. */
 78528         -  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
        78779  +  if( rc ) goto abort_due_to_error;
        78780  +  if( db->xUpdateCallback && pOp->p4.z ){
 78529  78781       zDb = db->aDb[pC->iDb].zName;
 78530  78782       zTbl = pOp->p4.z;
 78531  78783       op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
 78532  78784       assert( pC->isTable );
 78533  78785       db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
 78534  78786       assert( pC->iDb>=0 );
 78535  78787     }
................................................................................
 78611  78863     }
 78612  78864   #endif
 78613  78865   
 78614  78866     rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
 78615  78867     pC->cacheStatus = CACHE_STALE;
 78616  78868   
 78617  78869     /* Invoke the update-hook if required. */
 78618         -  if( rc==SQLITE_OK && hasUpdateCallback ){
        78870  +  if( rc ) goto abort_due_to_error;
        78871  +  if( hasUpdateCallback ){
 78619  78872       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
 78620  78873                           db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
 78621  78874       assert( pC->iDb>=0 );
 78622  78875     }
 78623  78876     if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
 78624  78877     break;
 78625  78878   }
................................................................................
 78660  78913     assert( isSorter(pC) );
 78661  78914     assert( pOp->p4type==P4_INT32 );
 78662  78915     pIn3 = &aMem[pOp->p3];
 78663  78916     nKeyCol = pOp->p4.i;
 78664  78917     res = 0;
 78665  78918     rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
 78666  78919     VdbeBranchTaken(res!=0,2);
        78920  +  if( rc ) goto abort_due_to_error;
 78667  78921     if( res ) goto jump_to_p2;
 78668  78922     break;
 78669  78923   };
 78670  78924   
 78671  78925   /* Opcode: SorterData P1 P2 P3 * *
 78672  78926   ** Synopsis: r[P2]=data
 78673  78927   **
................................................................................
 78685  78939   
 78686  78940     pOut = &aMem[pOp->p2];
 78687  78941     pC = p->apCsr[pOp->p1];
 78688  78942     assert( isSorter(pC) );
 78689  78943     rc = sqlite3VdbeSorterRowkey(pC, pOut);
 78690  78944     assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
 78691  78945     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
        78946  +  if( rc ) goto abort_due_to_error;
 78692  78947     p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
 78693  78948     break;
 78694  78949   }
 78695  78950   
 78696  78951   /* Opcode: RowData P1 P2 * * *
 78697  78952   ** Synopsis: r[P2]=data
 78698  78953   **
................................................................................
 78773  79028     pOut->n = n;
 78774  79029     MemSetTypeFlag(pOut, MEM_Blob);
 78775  79030     if( pC->isTable==0 ){
 78776  79031       rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
 78777  79032     }else{
 78778  79033       rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
 78779  79034     }
        79035  +  if( rc ) goto abort_due_to_error;
 78780  79036     pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
 78781  79037     UPDATE_MAX_BLOBSIZE(pOut);
 78782  79038     REGISTER_TRACE(pOp->p2, pOut);
 78783  79039     break;
 78784  79040   }
 78785  79041   
 78786  79042   /* Opcode: Rowid P1 P2 * * *
................................................................................
 78813  79069     }else if( pC->eCurType==CURTYPE_VTAB ){
 78814  79070       assert( pC->uc.pVCur!=0 );
 78815  79071       pVtab = pC->uc.pVCur->pVtab;
 78816  79072       pModule = pVtab->pModule;
 78817  79073       assert( pModule->xRowid );
 78818  79074       rc = pModule->xRowid(pC->uc.pVCur, &v);
 78819  79075       sqlite3VtabImportErrmsg(p, pVtab);
        79076  +    if( rc ) goto abort_due_to_error;
 78820  79077   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 78821  79078     }else{
 78822  79079       assert( pC->eCurType==CURTYPE_BTREE );
 78823  79080       assert( pC->uc.pCursor!=0 );
 78824  79081       rc = sqlite3VdbeCursorRestore(pC);
 78825  79082       if( rc ) goto abort_due_to_error;
 78826  79083       if( pC->nullRow ){
................................................................................
 78883  79140     pC->nullRow = (u8)res;
 78884  79141     pC->deferredMoveto = 0;
 78885  79142     pC->cacheStatus = CACHE_STALE;
 78886  79143     pC->seekResult = pOp->p3;
 78887  79144   #ifdef SQLITE_DEBUG
 78888  79145     pC->seekOp = OP_Last;
 78889  79146   #endif
        79147  +  if( rc ) goto abort_due_to_error;
 78890  79148     if( pOp->p2>0 ){
 78891  79149       VdbeBranchTaken(res!=0,2);
 78892  79150       if( res ) goto jump_to_p2;
 78893  79151     }
 78894  79152     break;
 78895  79153   }
 78896  79154   
................................................................................
 78947  79205       assert( pC->eCurType==CURTYPE_BTREE );
 78948  79206       pCrsr = pC->uc.pCursor;
 78949  79207       assert( pCrsr );
 78950  79208       rc = sqlite3BtreeFirst(pCrsr, &res);
 78951  79209       pC->deferredMoveto = 0;
 78952  79210       pC->cacheStatus = CACHE_STALE;
 78953  79211     }
        79212  +  if( rc ) goto abort_due_to_error;
 78954  79213     pC->nullRow = (u8)res;
 78955  79214     assert( pOp->p2>0 && pOp->p2<p->nOp );
 78956  79215     VdbeBranchTaken(res!=0,2);
 78957  79216     if( res ) goto jump_to_p2;
 78958  79217     break;
 78959  79218   }
 78960  79219   
................................................................................
 79059  79318          || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
 79060  79319          || pC->seekOp==OP_Last );
 79061  79320   
 79062  79321     rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
 79063  79322   next_tail:
 79064  79323     pC->cacheStatus = CACHE_STALE;
 79065  79324     VdbeBranchTaken(res==0,2);
        79325  +  if( rc ) goto abort_due_to_error;
 79066  79326     if( res==0 ){
 79067  79327       pC->nullRow = 0;
 79068  79328       p->aCounter[pOp->p5]++;
 79069  79329   #ifdef SQLITE_TEST
 79070  79330       sqlite3_search_count++;
 79071  79331   #endif
 79072  79332       goto jump_to_p2_and_check_for_interrupt;
................................................................................
 79109  79369     assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
 79110  79370     pIn2 = &aMem[pOp->p2];
 79111  79371     assert( pIn2->flags & MEM_Blob );
 79112  79372     if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 79113  79373     assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
 79114  79374     assert( pC->isTable==0 );
 79115  79375     rc = ExpandBlob(pIn2);
 79116         -  if( rc==SQLITE_OK ){
 79117         -    if( pOp->opcode==OP_SorterInsert ){
 79118         -      rc = sqlite3VdbeSorterWrite(pC, pIn2);
 79119         -    }else{
 79120         -      nKey = pIn2->n;
 79121         -      zKey = pIn2->z;
 79122         -      rc = sqlite3BtreeInsert(pC->uc.pCursor, zKey, nKey, "", 0, 0, pOp->p3, 
 79123         -          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
 79124         -          );
 79125         -      assert( pC->deferredMoveto==0 );
 79126         -      pC->cacheStatus = CACHE_STALE;
 79127         -    }
        79376  +  if( rc ) goto abort_due_to_error;
        79377  +  if( pOp->opcode==OP_SorterInsert ){
        79378  +    rc = sqlite3VdbeSorterWrite(pC, pIn2);
        79379  +  }else{
        79380  +    nKey = pIn2->n;
        79381  +    zKey = pIn2->z;
        79382  +    rc = sqlite3BtreeInsert(pC->uc.pCursor, zKey, nKey, "", 0, 0, pOp->p3, 
        79383  +        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
        79384  +        );
        79385  +    assert( pC->deferredMoveto==0 );
        79386  +    pC->cacheStatus = CACHE_STALE;
 79128  79387     }
        79388  +  if( rc) goto abort_due_to_error;
 79129  79389     break;
 79130  79390   }
 79131  79391   
 79132  79392   /* Opcode: IdxDelete P1 P2 P3 * *
 79133  79393   ** Synopsis: key=r[P2@P3]
 79134  79394   **
 79135  79395   ** The content of P3 registers starting at register P2 form
................................................................................
 79139  79399   case OP_IdxDelete: {
 79140  79400     VdbeCursor *pC;
 79141  79401     BtCursor *pCrsr;
 79142  79402     int res;
 79143  79403     UnpackedRecord r;
 79144  79404   
 79145  79405     assert( pOp->p3>0 );
 79146         -  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
        79406  +  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
 79147  79407     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 79148  79408     pC = p->apCsr[pOp->p1];
 79149  79409     assert( pC!=0 );
 79150  79410     assert( pC->eCurType==CURTYPE_BTREE );
 79151  79411     pCrsr = pC->uc.pCursor;
 79152  79412     assert( pCrsr!=0 );
 79153  79413     assert( pOp->p5==0 );
 79154  79414     r.pKeyInfo = pC->pKeyInfo;
 79155  79415     r.nField = (u16)pOp->p3;
 79156  79416     r.default_rc = 0;
 79157  79417     r.aMem = &aMem[pOp->p2];
 79158  79418     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
 79159         -  if( rc==SQLITE_OK && res==0 ){
        79419  +  if( rc ) goto abort_due_to_error;
        79420  +  if( res==0 ){
 79160  79421       rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
        79422  +    if( rc ) goto abort_due_to_error;
 79161  79423     }
 79162  79424     assert( pC->deferredMoveto==0 );
 79163  79425     pC->cacheStatus = CACHE_STALE;
 79164  79426     break;
 79165  79427   }
 79166  79428   
 79167  79429   /* Opcode: Seek P1 * P3 P4 *
................................................................................
 79328  79590       assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
 79329  79591       res = -res;
 79330  79592     }else{
 79331  79593       assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
 79332  79594       res++;
 79333  79595     }
 79334  79596     VdbeBranchTaken(res>0,2);
        79597  +  if( rc ) goto abort_due_to_error;
 79335  79598     if( res>0 ) goto jump_to_p2;
 79336  79599     break;
 79337  79600   }
 79338  79601   
 79339  79602   /* Opcode: Destroy P1 P2 P3 * *
 79340  79603   **
 79341  79604   ** Delete an entire database table or index whose root page in the database
................................................................................
 79363  79626     assert( p->readOnly==0 );
 79364  79627     assert( pOp->p1>1 );
 79365  79628     pOut = out2Prerelease(p, pOp);
 79366  79629     pOut->flags = MEM_Null;
 79367  79630     if( db->nVdbeRead > db->nVDestroy+1 ){
 79368  79631       rc = SQLITE_LOCKED;
 79369  79632       p->errorAction = OE_Abort;
        79633  +    goto abort_due_to_error;
 79370  79634     }else{
 79371  79635       iDb = pOp->p3;
 79372  79636       assert( DbMaskTest(p->btreeMask, iDb) );
 79373  79637       iMoved = 0;  /* Not needed.  Only to silence a warning. */
 79374  79638       rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
 79375  79639       pOut->flags = MEM_Int;
 79376  79640       pOut->u.i = iMoved;
        79641  +    if( rc ) goto abort_due_to_error;
 79377  79642   #ifndef SQLITE_OMIT_AUTOVACUUM
 79378         -    if( rc==SQLITE_OK && iMoved!=0 ){
        79643  +    if( iMoved!=0 ){
 79379  79644         sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
 79380  79645         /* All OP_Destroy operations occur on the same btree */
 79381  79646         assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
 79382  79647         resetSchemaOnFault = iDb+1;
 79383  79648       }
 79384  79649   #endif
 79385  79650     }
................................................................................
 79417  79682       p->nChange += nChange;
 79418  79683       if( pOp->p3>0 ){
 79419  79684         assert( memIsValid(&aMem[pOp->p3]) );
 79420  79685         memAboutToChange(p, &aMem[pOp->p3]);
 79421  79686         aMem[pOp->p3].u.i += nChange;
 79422  79687       }
 79423  79688     }
        79689  +  if( rc ) goto abort_due_to_error;
 79424  79690     break;
 79425  79691   }
 79426  79692   
 79427  79693   /* Opcode: ResetSorter P1 * * * *
 79428  79694   **
 79429  79695   ** Delete all contents from the ephemeral table or sorter
 79430  79696   ** that is open on cursor P1.
................................................................................
 79440  79706     assert( pC!=0 );
 79441  79707     if( isSorter(pC) ){
 79442  79708       sqlite3VdbeSorterReset(db, pC->uc.pSorter);
 79443  79709     }else{
 79444  79710       assert( pC->eCurType==CURTYPE_BTREE );
 79445  79711       assert( pC->isEphemeral );
 79446  79712       rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
        79713  +    if( rc ) goto abort_due_to_error;
 79447  79714     }
 79448  79715     break;
 79449  79716   }
 79450  79717   
 79451  79718   /* Opcode: CreateTable P1 P2 * * *
 79452  79719   ** Synopsis: r[P2]=root iDb=P1
 79453  79720   **
................................................................................
 79488  79755     if( pOp->opcode==OP_CreateTable ){
 79489  79756       /* flags = BTREE_INTKEY; */
 79490  79757       flags = BTREE_INTKEY;
 79491  79758     }else{
 79492  79759       flags = BTREE_BLOBKEY;
 79493  79760     }
 79494  79761     rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
        79762  +  if( rc ) goto abort_due_to_error;
 79495  79763     pOut->u.i = pgno;
 79496  79764     break;
 79497  79765   }
 79498  79766   
 79499  79767   /* Opcode: ParseSchema P1 * * P4 *
 79500  79768   **
 79501  79769   ** Read and parse all entries from the SQLITE_MASTER table of database P1
................................................................................
 79528  79796       initData.db = db;
 79529  79797       initData.iDb = pOp->p1;
 79530  79798       initData.pzErrMsg = &p->zErrMsg;
 79531  79799       zSql = sqlite3MPrintf(db,
 79532  79800          "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
 79533  79801          db->aDb[iDb].zName, zMaster, pOp->p4.z);
 79534  79802       if( zSql==0 ){
 79535         -      rc = SQLITE_NOMEM;
        79803  +      rc = SQLITE_NOMEM_BKPT;
 79536  79804       }else{
 79537  79805         assert( db->init.busy==0 );
 79538  79806         db->init.busy = 1;
 79539  79807         initData.rc = SQLITE_OK;
 79540  79808         assert( !db->mallocFailed );
 79541  79809         rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
 79542  79810         if( rc==SQLITE_OK ) rc = initData.rc;
 79543  79811         sqlite3DbFree(db, zSql);
 79544  79812         db->init.busy = 0;
 79545  79813       }
 79546  79814     }
 79547         -  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
 79548         -  if( rc==SQLITE_NOMEM ){
 79549         -    goto no_mem;
        79815  +  if( rc ){
        79816  +    sqlite3ResetAllSchemasOfConnection(db);
        79817  +    if( rc==SQLITE_NOMEM ){
        79818  +      goto no_mem;
        79819  +    }
        79820  +    goto abort_due_to_error;
 79550  79821     }
 79551  79822     break;  
 79552  79823   }
 79553  79824   
 79554  79825   #if !defined(SQLITE_OMIT_ANALYZE)
 79555  79826   /* Opcode: LoadAnalysis P1 * * * *
 79556  79827   **
................................................................................
 79557  79828   ** Read the sqlite_stat1 table for database P1 and load the content
 79558  79829   ** of that table into the internal index hash table.  This will cause
 79559  79830   ** the analysis to be used when preparing all subsequent queries.
 79560  79831   */
 79561  79832   case OP_LoadAnalysis: {
 79562  79833     assert( pOp->p1>=0 && pOp->p1<db->nDb );
 79563  79834     rc = sqlite3AnalysisLoad(db, pOp->p1);
        79835  +  if( rc ) goto abort_due_to_error;
 79564  79836     break;  
 79565  79837   }
 79566  79838   #endif /* !defined(SQLITE_OMIT_ANALYZE) */
 79567  79839   
 79568  79840   /* Opcode: DropTable P1 * * P4 *
 79569  79841   **
 79570  79842   ** Remove the internal (in-memory) data structures that describe
................................................................................
 79602  79874   case OP_DropTrigger: {
 79603  79875     sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
 79604  79876     break;
 79605  79877   }
 79606  79878   
 79607  79879   
 79608  79880   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 79609         -/* Opcode: IntegrityCk P1 P2 P3 * P5
        79881  +/* Opcode: IntegrityCk P1 P2 P3 P4 P5
 79610  79882   **
 79611  79883   ** Do an analysis of the currently open database.  Store in
 79612  79884   ** register P1 the text of an error message describing any problems.
 79613  79885   ** If no problems are found, store a NULL in register P1.
 79614  79886   **
 79615  79887   ** The register P3 contains the maximum number of allowed errors.
 79616  79888   ** At most reg(P3) errors will be reported.
 79617  79889   ** In other words, the analysis stops as soon as reg(P1) errors are 
 79618  79890   ** seen.  Reg(P1) is updated with the number of errors remaining.
 79619  79891   **
 79620         -** The root page numbers of all tables in the database are integer
 79621         -** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
 79622         -** total.
        79892  +** The root page numbers of all tables in the database are integers
        79893  +** stored in P4_INTARRAY argument.
 79623  79894   **
 79624  79895   ** If P5 is not zero, the check is done on the auxiliary database
 79625  79896   ** file, not the main database file.
 79626  79897   **
 79627  79898   ** This opcode is used to implement the integrity_check pragma.
 79628  79899   */
 79629  79900   case OP_IntegrityCk: {
 79630  79901     int nRoot;      /* Number of tables to check.  (Number of root pages.) */
 79631  79902     int *aRoot;     /* Array of rootpage numbers for tables to be checked */
 79632         -  int j;          /* Loop counter */
 79633  79903     int nErr;       /* Number of errors reported */
 79634  79904     char *z;        /* Text of the error report */
 79635  79905     Mem *pnErr;     /* Register keeping track of errors remaining */
 79636  79906   
 79637  79907     assert( p->bIsReader );
 79638  79908     nRoot = pOp->p2;
        79909  +  aRoot = pOp->p4.ai;
 79639  79910     assert( nRoot>0 );
 79640         -  aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(nRoot+1) );
 79641         -  if( aRoot==0 ) goto no_mem;
 79642         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
        79911  +  assert( aRoot[nRoot]==0 );
        79912  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 79643  79913     pnErr = &aMem[pOp->p3];
 79644  79914     assert( (pnErr->flags & MEM_Int)!=0 );
 79645  79915     assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
 79646  79916     pIn1 = &aMem[pOp->p1];
 79647         -  for(j=0; j<nRoot; j++){
 79648         -    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
 79649         -  }
 79650         -  aRoot[j] = 0;
 79651  79917     assert( pOp->p5<db->nDb );
 79652  79918     assert( DbMaskTest(p->btreeMask, pOp->p5) );
 79653  79919     z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
 79654  79920                                    (int)pnErr->u.i, &nErr);
 79655         -  sqlite3DbFree(db, aRoot);
 79656  79921     pnErr->u.i -= nErr;
 79657  79922     sqlite3VdbeMemSetNull(pIn1);
 79658  79923     if( nErr==0 ){
 79659  79924       assert( z==0 );
 79660  79925     }else if( z==0 ){
 79661  79926       goto no_mem;
 79662  79927     }else{
................................................................................
 79816  80081       for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
 79817  80082       if( pFrame ) break;
 79818  80083     }
 79819  80084   
 79820  80085     if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
 79821  80086       rc = SQLITE_ERROR;
 79822  80087       sqlite3VdbeError(p, "too many levels of trigger recursion");
 79823         -    break;
        80088  +    goto abort_due_to_error;
 79824  80089     }
 79825  80090   
 79826  80091     /* Register pRt is used to store the memory required to save the state
 79827  80092     ** of the current program, and the memory required at runtime to execute
 79828  80093     ** the trigger program. If this trigger has been fired before, then pRt 
 79829  80094     ** is already allocated. Otherwise, it must be initialized.  */
 79830  80095     if( (pRt->flags&MEM_Frame)==0 ){
 79831  80096       /* SubProgram.nMem is set to the number of memory cells used by the 
 79832  80097       ** program stored in SubProgram.aOp. As well as these, one memory
 79833  80098       ** cell is required for each cursor used by the program. Set local
 79834  80099       ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
 79835  80100       */
 79836  80101       nMem = pProgram->nMem + pProgram->nCsr;
        80102  +    assert( nMem>0 );
        80103  +    if( pProgram->nCsr==0 ) nMem++;
 79837  80104       nByte = ROUND8(sizeof(VdbeFrame))
 79838  80105                 + nMem * sizeof(Mem)
 79839  80106                 + pProgram->nCsr * sizeof(VdbeCursor *)
 79840  80107                 + pProgram->nOnce * sizeof(u8);
 79841  80108       pFrame = sqlite3DbMallocZero(db, nByte);
 79842  80109       if( !pFrame ){
 79843  80110         goto no_mem;
................................................................................
 79866  80133       pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
 79867  80134       for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
 79868  80135         pMem->flags = MEM_Undefined;
 79869  80136         pMem->db = db;
 79870  80137       }
 79871  80138     }else{
 79872  80139       pFrame = pRt->u.pFrame;
 79873         -    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
        80140  +    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
        80141  +        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
 79874  80142       assert( pProgram->nCsr==pFrame->nChildCsr );
 79875  80143       assert( (int)(pOp - aOp)==pFrame->pc );
 79876  80144     }
 79877  80145   
 79878  80146     p->nFrame++;
 79879  80147     pFrame->pParent = p->pFrame;
 79880  80148     pFrame->lastRowid = lastRowid;
 79881  80149     pFrame->nChange = p->nChange;
 79882  80150     pFrame->nDbChange = p->db->nChange;
        80151  +  assert( pFrame->pAuxData==0 );
        80152  +  pFrame->pAuxData = p->pAuxData;
        80153  +  p->pAuxData = 0;
 79883  80154     p->nChange = 0;
 79884  80155     p->pFrame = pFrame;
 79885         -  p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
        80156  +  p->aMem = aMem = VdbeFrameMem(pFrame);
 79886  80157     p->nMem = pFrame->nChildMem;
 79887  80158     p->nCursor = (u16)pFrame->nChildCsr;
 79888         -  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
        80159  +  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
 79889  80160     p->aOp = aOp = pProgram->aOp;
 79890  80161     p->nOp = pProgram->nOp;
 79891  80162     p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
 79892  80163     p->nOnceFlag = pProgram->nOnce;
 79893  80164   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 79894  80165     p->anExec = 0;
 79895  80166   #endif
................................................................................
 80127  80398   */
 80128  80399   case OP_AggStep0: {
 80129  80400     int n;
 80130  80401     sqlite3_context *pCtx;
 80131  80402   
 80132  80403     assert( pOp->p4type==P4_FUNCDEF );
 80133  80404     n = pOp->p5;
 80134         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 80135         -  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
        80405  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
        80406  +  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 80136  80407     assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 80137  80408     pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
 80138  80409     if( pCtx==0 ) goto no_mem;
 80139  80410     pCtx->pMem = 0;
 80140  80411     pCtx->pFunc = pOp->p4.pFunc;
 80141  80412     pCtx->iOp = (int)(pOp - aOp);
 80142  80413     pCtx->pVdbe = p;
................................................................................
 80180  80451     (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
 80181  80452     if( pCtx->fErrorOrAux ){
 80182  80453       if( pCtx->isError ){
 80183  80454         sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
 80184  80455         rc = pCtx->isError;
 80185  80456       }
 80186  80457       sqlite3VdbeMemRelease(&t);
        80458  +    if( rc ) goto abort_due_to_error;
 80187  80459     }else{
 80188  80460       assert( t.flags==MEM_Null );
 80189  80461     }
 80190  80462     if( pCtx->skipFlag ){
 80191  80463       assert( pOp[-1].opcode==OP_CollSeq );
 80192  80464       i = pOp[-1].p1;
 80193  80465       if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
................................................................................
 80206  80478   ** argument is not used by this opcode.  It is only there to disambiguate
 80207  80479   ** functions that can take varying numbers of arguments.  The
 80208  80480   ** P4 argument is only needed for the degenerate case where
 80209  80481   ** the step function was not previously called.
 80210  80482   */
 80211  80483   case OP_AggFinal: {
 80212  80484     Mem *pMem;
 80213         -  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
        80485  +  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 80214  80486     pMem = &aMem[pOp->p1];
 80215  80487     assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
 80216  80488     rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
 80217  80489     if( rc ){
 80218  80490       sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
        80491  +    goto abort_due_to_error;
 80219  80492     }
 80220  80493     sqlite3VdbeChangeEncoding(pMem, encoding);
 80221  80494     UPDATE_MAX_BLOBSIZE(pMem);
 80222  80495     if( sqlite3VdbeMemTooBig(pMem) ){
 80223  80496       goto too_big;
 80224  80497     }
 80225  80498     break;
................................................................................
 80247  80520     aRes[1] = aRes[2] = -1;
 80248  80521     assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
 80249  80522          || pOp->p2==SQLITE_CHECKPOINT_FULL
 80250  80523          || pOp->p2==SQLITE_CHECKPOINT_RESTART
 80251  80524          || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
 80252  80525     );
 80253  80526     rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
 80254         -  if( rc==SQLITE_BUSY ){
        80527  +  if( rc ){
        80528  +    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
 80255  80529       rc = SQLITE_OK;
 80256  80530       aRes[0] = 1;
 80257  80531     }
 80258  80532     for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
 80259  80533       sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
 80260  80534     }    
 80261  80535     break;
................................................................................
 80320  80594     ){
 80321  80595       if( !db->autoCommit || db->nVdbeRead>1 ){
 80322  80596         rc = SQLITE_ERROR;
 80323  80597         sqlite3VdbeError(p,
 80324  80598             "cannot change %s wal mode from within a transaction",
 80325  80599             (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
 80326  80600         );
 80327         -      break;
        80601  +      goto abort_due_to_error;
 80328  80602       }else{
 80329  80603    
 80330  80604         if( eOld==PAGER_JOURNALMODE_WAL ){
 80331  80605           /* If leaving WAL mode, close the log file. If successful, the call
 80332  80606           ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
 80333  80607           ** file. An EXCLUSIVE lock may still be held on the database file 
 80334  80608           ** after a successful return. 
................................................................................
 80350  80624         if( rc==SQLITE_OK ){
 80351  80625           rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
 80352  80626         }
 80353  80627       }
 80354  80628     }
 80355  80629   #endif /* ifndef SQLITE_OMIT_WAL */
 80356  80630   
 80357         -  if( rc ){
 80358         -    eNew = eOld;
 80359         -  }
        80631  +  if( rc ) eNew = eOld;
 80360  80632     eNew = sqlite3PagerSetJournalMode(pPager, eNew);
 80361  80633   
 80362  80634     pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 80363  80635     pOut->z = (char *)sqlite3JournalModename(eNew);
 80364  80636     pOut->n = sqlite3Strlen30(pOut->z);
 80365  80637     pOut->enc = SQLITE_UTF8;
 80366  80638     sqlite3VdbeChangeEncoding(pOut, encoding);
        80639  +  if( rc ) goto abort_due_to_error;
 80367  80640     break;
 80368  80641   };
 80369  80642   #endif /* SQLITE_OMIT_PRAGMA */
 80370  80643   
 80371  80644   #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
 80372  80645   /* Opcode: Vacuum * * * * *
 80373  80646   **
................................................................................
 80374  80647   ** Vacuum the entire database.  This opcode will cause other virtual
 80375  80648   ** machines to be created and run.  It may not be called from within
 80376  80649   ** a transaction.
 80377  80650   */
 80378  80651   case OP_Vacuum: {
 80379  80652     assert( p->readOnly==0 );
 80380  80653     rc = sqlite3RunVacuum(&p->zErrMsg, db);
        80654  +  if( rc ) goto abort_due_to_error;
 80381  80655     break;
 80382  80656   }
 80383  80657   #endif
 80384  80658   
 80385  80659   #if !defined(SQLITE_OMIT_AUTOVACUUM)
 80386  80660   /* Opcode: IncrVacuum P1 P2 * * *
 80387  80661   **
................................................................................
 80394  80668   
 80395  80669     assert( pOp->p1>=0 && pOp->p1<db->nDb );
 80396  80670     assert( DbMaskTest(p->btreeMask, pOp->p1) );
 80397  80671     assert( p->readOnly==0 );
 80398  80672     pBt = db->aDb[pOp->p1].pBt;
 80399  80673     rc = sqlite3BtreeIncrVacuum(pBt);
 80400  80674     VdbeBranchTaken(rc==SQLITE_DONE,2);
 80401         -  if( rc==SQLITE_DONE ){
        80675  +  if( rc ){
        80676  +    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
 80402  80677       rc = SQLITE_OK;
 80403  80678       goto jump_to_p2;
 80404  80679     }
 80405  80680     break;
 80406  80681   }
 80407  80682   #endif
 80408  80683   
................................................................................
 80445  80720     u8 isWriteLock = (u8)pOp->p3;
 80446  80721     if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
 80447  80722       int p1 = pOp->p1; 
 80448  80723       assert( p1>=0 && p1<db->nDb );
 80449  80724       assert( DbMaskTest(p->btreeMask, p1) );
 80450  80725       assert( isWriteLock==0 || isWriteLock==1 );
 80451  80726       rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
 80452         -    if( (rc&0xFF)==SQLITE_LOCKED ){
 80453         -      const char *z = pOp->p4.z;
 80454         -      sqlite3VdbeError(p, "database table is locked: %s", z);
        80727  +    if( rc ){
        80728  +      if( (rc&0xFF)==SQLITE_LOCKED ){
        80729  +        const char *z = pOp->p4.z;
        80730  +        sqlite3VdbeError(p, "database table is locked: %s", z);
        80731  +      }
        80732  +      goto abort_due_to_error;
 80455  80733       }
 80456  80734     }
 80457  80735     break;
 80458  80736   }
 80459  80737   #endif /* SQLITE_OMIT_SHARED_CACHE */
 80460  80738   
 80461  80739   #ifndef SQLITE_OMIT_VIRTUALTABLE
................................................................................
 80469  80747   ** code will be set to SQLITE_LOCKED.
 80470  80748   */
 80471  80749   case OP_VBegin: {
 80472  80750     VTable *pVTab;
 80473  80751     pVTab = pOp->p4.pVtab;
 80474  80752     rc = sqlite3VtabBegin(db, pVTab);
 80475  80753     if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
        80754  +  if( rc ) goto abort_due_to_error;
 80476  80755     break;
 80477  80756   }
 80478  80757   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80479  80758   
 80480  80759   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80481  80760   /* Opcode: VCreate P1 P2 * * *
 80482  80761   **
................................................................................
 80497  80776     assert( rc==SQLITE_OK );
 80498  80777     zTab = (const char*)sqlite3_value_text(&sMem);
 80499  80778     assert( zTab || db->mallocFailed );
 80500  80779     if( zTab ){
 80501  80780       rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
 80502  80781     }
 80503  80782     sqlite3VdbeMemRelease(&sMem);
        80783  +  if( rc ) goto abort_due_to_error;
 80504  80784     break;
 80505  80785   }
 80506  80786   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80507  80787   
 80508  80788   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80509  80789   /* Opcode: VDestroy P1 * * P4 *
 80510  80790   **
................................................................................
 80511  80791   ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
 80512  80792   ** of that table.
 80513  80793   */
 80514  80794   case OP_VDestroy: {
 80515  80795     db->nVDestroy++;
 80516  80796     rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
 80517  80797     db->nVDestroy--;
        80798  +  if( rc ) goto abort_due_to_error;
 80518  80799     break;
 80519  80800   }
 80520  80801   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80521  80802   
 80522  80803   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80523  80804   /* Opcode: VOpen P1 * * P4 *
 80524  80805   **
................................................................................
 80534  80815   
 80535  80816     assert( p->bIsReader );
 80536  80817     pCur = 0;
 80537  80818     pVCur = 0;
 80538  80819     pVtab = pOp->p4.pVtab->pVtab;
 80539  80820     if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 80540  80821       rc = SQLITE_LOCKED;
 80541         -    break;
        80822  +    goto abort_due_to_error;
 80542  80823     }
 80543  80824     pModule = pVtab->pModule;
 80544  80825     rc = pModule->xOpen(pVtab, &pVCur);
 80545  80826     sqlite3VtabImportErrmsg(p, pVtab);
 80546         -  if( SQLITE_OK==rc ){
 80547         -    /* Initialize sqlite3_vtab_cursor base class */
 80548         -    pVCur->pVtab = pVtab;
        80827  +  if( rc ) goto abort_due_to_error;
 80549  80828   
 80550         -    /* Initialize vdbe cursor object */
 80551         -    pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
 80552         -    if( pCur ){
 80553         -      pCur->uc.pVCur = pVCur;
 80554         -      pVtab->nRef++;
 80555         -    }else{
 80556         -      assert( db->mallocFailed );
 80557         -      pModule->xClose(pVCur);
 80558         -      goto no_mem;
 80559         -    }
        80829  +  /* Initialize sqlite3_vtab_cursor base class */
        80830  +  pVCur->pVtab = pVtab;
        80831  +
        80832  +  /* Initialize vdbe cursor object */
        80833  +  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
        80834  +  if( pCur ){
        80835  +    pCur->uc.pVCur = pVCur;
        80836  +    pVtab->nRef++;
        80837  +  }else{
        80838  +    assert( db->mallocFailed );
        80839  +    pModule->xClose(pVCur);
        80840  +    goto no_mem;
 80560  80841     }
 80561  80842     break;
 80562  80843   }
 80563  80844   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80564  80845   
 80565  80846   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80566  80847   /* Opcode: VFilter P1 P2 P3 P4 *
................................................................................
 80614  80895     res = 0;
 80615  80896     apArg = p->apArg;
 80616  80897     for(i = 0; i<nArg; i++){
 80617  80898       apArg[i] = &pArgc[i+1];
 80618  80899     }
 80619  80900     rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
 80620  80901     sqlite3VtabImportErrmsg(p, pVtab);
 80621         -  if( rc==SQLITE_OK ){
 80622         -    res = pModule->xEof(pVCur);
 80623         -  }
        80902  +  if( rc ) goto abort_due_to_error;
        80903  +  res = pModule->xEof(pVCur);
 80624  80904     pCur->nullRow = 0;
 80625  80905     VdbeBranchTaken(res!=0,2);
 80626  80906     if( res ) goto jump_to_p2;
 80627  80907     break;
 80628  80908   }
 80629  80909   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80630  80910   
................................................................................
 80640  80920     sqlite3_vtab *pVtab;
 80641  80921     const sqlite3_module *pModule;
 80642  80922     Mem *pDest;
 80643  80923     sqlite3_context sContext;
 80644  80924   
 80645  80925     VdbeCursor *pCur = p->apCsr[pOp->p1];
 80646  80926     assert( pCur->eCurType==CURTYPE_VTAB );
 80647         -  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
        80927  +  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 80648  80928     pDest = &aMem[pOp->p3];
 80649  80929     memAboutToChange(p, pDest);
 80650  80930     if( pCur->nullRow ){
 80651  80931       sqlite3VdbeMemSetNull(pDest);
 80652  80932       break;
 80653  80933     }
 80654  80934     pVtab = pCur->uc.pVCur->pVtab;
................................................................................
 80665  80945     sqlite3VdbeChangeEncoding(pDest, encoding);
 80666  80946     REGISTER_TRACE(pOp->p3, pDest);
 80667  80947     UPDATE_MAX_BLOBSIZE(pDest);
 80668  80948   
 80669  80949     if( sqlite3VdbeMemTooBig(pDest) ){
 80670  80950       goto too_big;
 80671  80951     }
        80952  +  if( rc ) goto abort_due_to_error;
 80672  80953     break;
 80673  80954   }
 80674  80955   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80675  80956   
 80676  80957   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80677  80958   /* Opcode: VNext P1 P2 * * *
 80678  80959   **
................................................................................
 80700  80981     ** underlying implementation to return an error if one occurs during
 80701  80982     ** xNext(). Instead, if an error occurs, true is returned (indicating that 
 80702  80983     ** data is available) and the error code returned when xColumn or
 80703  80984     ** some other method is next invoked on the save virtual table cursor.
 80704  80985     */
 80705  80986     rc = pModule->xNext(pCur->uc.pVCur);
 80706  80987     sqlite3VtabImportErrmsg(p, pVtab);
 80707         -  if( rc==SQLITE_OK ){
 80708         -    res = pModule->xEof(pCur->uc.pVCur);
 80709         -  }
        80988  +  if( rc ) goto abort_due_to_error;
        80989  +  res = pModule->xEof(pCur->uc.pVCur);
 80710  80990     VdbeBranchTaken(!res,2);
 80711  80991     if( !res ){
 80712  80992       /* If there is data, jump to P2 */
 80713  80993       goto jump_to_p2_and_check_for_interrupt;
 80714  80994     }
 80715  80995     goto check_for_interrupt;
 80716  80996   }
................................................................................
 80734  81014     assert( p->readOnly==0 );
 80735  81015     REGISTER_TRACE(pOp->p1, pName);
 80736  81016     assert( pName->flags & MEM_Str );
 80737  81017     testcase( pName->enc==SQLITE_UTF8 );
 80738  81018     testcase( pName->enc==SQLITE_UTF16BE );
 80739  81019     testcase( pName->enc==SQLITE_UTF16LE );
 80740  81020     rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
 80741         -  if( rc==SQLITE_OK ){
 80742         -    rc = pVtab->pModule->xRename(pVtab, pName->z);
 80743         -    sqlite3VtabImportErrmsg(p, pVtab);
 80744         -    p->expired = 0;
 80745         -  }
        81021  +  if( rc ) goto abort_due_to_error;
        81022  +  rc = pVtab->pModule->xRename(pVtab, pName->z);
        81023  +  sqlite3VtabImportErrmsg(p, pVtab);
        81024  +  p->expired = 0;
        81025  +  if( rc ) goto abort_due_to_error;
 80746  81026     break;
 80747  81027   }
 80748  81028   #endif
 80749  81029   
 80750  81030   #ifndef SQLITE_OMIT_VIRTUALTABLE
 80751  81031   /* Opcode: VUpdate P1 P2 P3 P4 P5
 80752  81032   ** Synopsis: data=r[P3@P2]
................................................................................
 80787  81067     assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
 80788  81068          || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
 80789  81069     );
 80790  81070     assert( p->readOnly==0 );
 80791  81071     pVtab = pOp->p4.pVtab->pVtab;
 80792  81072     if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 80793  81073       rc = SQLITE_LOCKED;
 80794         -    break;
        81074  +    goto abort_due_to_error;
 80795  81075     }
 80796  81076     pModule = pVtab->pModule;
 80797  81077     nArg = pOp->p2;
 80798  81078     assert( pOp->p4type==P4_VTAB );
 80799  81079     if( ALWAYS(pModule->xUpdate) ){
 80800  81080       u8 vtabOnConflict = db->vtabOnConflict;
 80801  81081       apArg = p->apArg;
................................................................................
 80819  81099           rc = SQLITE_OK;
 80820  81100         }else{
 80821  81101           p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
 80822  81102         }
 80823  81103       }else{
 80824  81104         p->nChange++;
 80825  81105       }
        81106  +    if( rc ) goto abort_due_to_error;
 80826  81107     }
 80827  81108     break;
 80828  81109   }
 80829  81110   #endif /* SQLITE_OMIT_VIRTUALTABLE */
 80830  81111   
 80831  81112   #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 80832  81113   /* Opcode: Pagecount P1 P2 * * *
................................................................................
 80990  81271   #endif  /* SQLITE_DEBUG */
 80991  81272   #endif  /* NDEBUG */
 80992  81273     }  /* The end of the for(;;) loop the loops through opcodes */
 80993  81274   
 80994  81275     /* If we reach this point, it means that execution is finished with
 80995  81276     ** an error of some kind.
 80996  81277     */
 80997         -vdbe_error_halt:
        81278  +abort_due_to_error:
        81279  +  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
 80998  81280     assert( rc );
        81281  +  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
        81282  +    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
        81283  +  }
 80999  81284     p->rc = rc;
        81285  +  sqlite3SystemError(db, rc);
 81000  81286     testcase( sqlite3GlobalConfig.xLog!=0 );
 81001  81287     sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
 81002  81288                      (int)(pOp - aOp), p->zSql, p->zErrMsg);
 81003  81289     sqlite3VdbeHalt(p);
 81004  81290     if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
 81005  81291     rc = SQLITE_ERROR;
 81006  81292     if( resetSchemaOnFault>0 ){
................................................................................
 81022  81308   
 81023  81309     /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
 81024  81310     ** is encountered.
 81025  81311     */
 81026  81312   too_big:
 81027  81313     sqlite3VdbeError(p, "string or blob too big");
 81028  81314     rc = SQLITE_TOOBIG;
 81029         -  goto vdbe_error_halt;
        81315  +  goto abort_due_to_error;
 81030  81316   
 81031  81317     /* Jump to here if a malloc() fails.
 81032  81318     */
 81033  81319   no_mem:
 81034  81320     sqlite3OomFault(db);
 81035  81321     sqlite3VdbeError(p, "out of memory");
 81036         -  rc = SQLITE_NOMEM;
 81037         -  goto vdbe_error_halt;
 81038         -
 81039         -  /* Jump to here for any other kind of fatal error.  The "rc" variable
 81040         -  ** should hold the error number.
 81041         -  */
 81042         -abort_due_to_error:
 81043         -  assert( p->zErrMsg==0 );
 81044         -  if( db->mallocFailed ) rc = SQLITE_NOMEM;
 81045         -  if( rc!=SQLITE_IOERR_NOMEM ){
 81046         -    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 81047         -  }
 81048         -  goto vdbe_error_halt;
        81322  +  rc = SQLITE_NOMEM_BKPT;
        81323  +  goto abort_due_to_error;
 81049  81324   
 81050  81325     /* Jump to here if the sqlite3_interrupt() API sets the interrupt
 81051  81326     ** flag.
 81052  81327     */
 81053  81328   abort_due_to_interrupt:
 81054  81329     assert( db->u1.isInterrupted );
 81055         -  rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_INTERRUPT;
        81330  +  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
 81056  81331     p->rc = rc;
 81057  81332     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 81058         -  goto vdbe_error_halt;
        81333  +  goto abort_due_to_error;
 81059  81334   }
 81060  81335   
 81061  81336   
 81062  81337   /************** End of vdbe.c ************************************************/
 81063  81338   /************** Begin file vdbeblob.c ****************************************/
 81064  81339   /*
 81065  81340   ** 2007 May 1
................................................................................
 82079  82354   
 82080  82355       /* Extend the p->aAlloc[] allocation if required. */
 82081  82356       if( p->nAlloc<nByte ){
 82082  82357         u8 *aNew;
 82083  82358         int nNew = MAX(128, p->nAlloc*2);
 82084  82359         while( nByte>nNew ) nNew = nNew*2;
 82085  82360         aNew = sqlite3Realloc(p->aAlloc, nNew);
 82086         -      if( !aNew ) return SQLITE_NOMEM;
        82361  +      if( !aNew ) return SQLITE_NOMEM_BKPT;
 82087  82362         p->nAlloc = nNew;
 82088  82363         p->aAlloc = aNew;
 82089  82364       }
 82090  82365   
 82091  82366       /* Copy as much data as is available in the buffer into the start of
 82092  82367       ** p->aAlloc[].  */
 82093  82368       memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
................................................................................
 82191  82466   
 82192  82467     rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
 82193  82468     if( rc==SQLITE_OK && pReadr->aMap==0 ){
 82194  82469       int pgsz = pTask->pSorter->pgsz;
 82195  82470       int iBuf = pReadr->iReadOff % pgsz;
 82196  82471       if( pReadr->aBuffer==0 ){
 82197  82472         pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
 82198         -      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
        82473  +      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
 82199  82474         pReadr->nBuffer = pgsz;
 82200  82475       }
 82201  82476       if( rc==SQLITE_OK && iBuf ){
 82202  82477         int nRead = pgsz - iBuf;
 82203  82478         if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
 82204  82479           nRead = (int)(pReadr->iEof - pReadr->iReadOff);
 82205  82480         }
................................................................................
 82507  82782     assert( pCsr->eCurType==CURTYPE_SORTER );
 82508  82783     szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
 82509  82784     sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
 82510  82785   
 82511  82786     pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
 82512  82787     pCsr->uc.pSorter = pSorter;
 82513  82788     if( pSorter==0 ){
 82514         -    rc = SQLITE_NOMEM;
        82789  +    rc = SQLITE_NOMEM_BKPT;
 82515  82790     }else{
 82516  82791       pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
 82517  82792       memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
 82518  82793       pKeyInfo->db = 0;
 82519  82794       if( nField && nWorker==0 ){
 82520  82795         pKeyInfo->nXField += (pKeyInfo->nField - nField);
 82521  82796         pKeyInfo->nField = nField;
................................................................................
 82541  82816         ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
 82542  82817         ** large heap allocations.
 82543  82818         */
 82544  82819         if( sqlite3GlobalConfig.pScratch==0 ){
 82545  82820           assert( pSorter->iMemory==0 );
 82546  82821           pSorter->nMemory = pgsz;
 82547  82822           pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
 82548         -        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
        82823  +        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
 82549  82824         }
 82550  82825       }
 82551  82826   
 82552  82827       if( (pKeyInfo->nField+pKeyInfo->nXField)<13 
 82553  82828        && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
 82554  82829       ){
 82555  82830         pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
................................................................................
 82863  83138   static int vdbeSortAllocUnpacked(SortSubtask *pTask){
 82864  83139     if( pTask->pUnpacked==0 ){
 82865  83140       char *pFree;
 82866  83141       pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
 82867  83142           pTask->pSorter->pKeyInfo, 0, 0, &pFree
 82868  83143       );
 82869  83144       assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
 82870         -    if( pFree==0 ) return SQLITE_NOMEM;
        83145  +    if( pFree==0 ) return SQLITE_NOMEM_BKPT;
 82871  83146       pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
 82872  83147       pTask->pUnpacked->errCode = 0;
 82873  83148     }
 82874  83149     return SQLITE_OK;
 82875  83150   }
 82876  83151   
 82877  83152   
................................................................................
 82938  83213     if( rc!=SQLITE_OK ) return rc;
 82939  83214   
 82940  83215     p = pList->pList;
 82941  83216     pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
 82942  83217   
 82943  83218     aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
 82944  83219     if( !aSlot ){
 82945         -    return SQLITE_NOMEM;
        83220  +    return SQLITE_NOMEM_BKPT;
 82946  83221     }
 82947  83222   
 82948  83223     while( p ){
 82949  83224       SorterRecord *pNext;
 82950  83225       if( pList->aMemory ){
 82951  83226         if( (u8*)p==pList->aMemory ){
 82952  83227           pNext = 0;
................................................................................
 82988  83263     PmaWriter *p,                   /* Object to populate */
 82989  83264     int nBuf,                       /* Buffer size */
 82990  83265     i64 iStart                      /* Offset of pFd to begin writing at */
 82991  83266   ){
 82992  83267     memset(p, 0, sizeof(PmaWriter));
 82993  83268     p->aBuffer = (u8*)sqlite3Malloc(nBuf);
 82994  83269     if( !p->aBuffer ){
 82995         -    p->eFWErr = SQLITE_NOMEM;
        83270  +    p->eFWErr = SQLITE_NOMEM_BKPT;
 82996  83271     }else{
 82997  83272       p->iBufEnd = p->iBufStart = (iStart % nBuf);
 82998  83273       p->iWriteOff = iStart - p->iBufStart;
 82999  83274       p->nBuffer = nBuf;
 83000  83275       p->pFd = pFd;
 83001  83276     }
 83002  83277   }
................................................................................
 83276  83551         pSorter->list.pList = 0;
 83277  83552         pSorter->list.szPMA = 0;
 83278  83553         if( aMem ){
 83279  83554           pSorter->list.aMemory = aMem;
 83280  83555           pSorter->nMemory = sqlite3MallocSize(aMem);
 83281  83556         }else if( pSorter->list.aMemory ){
 83282  83557           pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
 83283         -        if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
        83558  +        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
 83284  83559         }
 83285  83560   
 83286  83561         rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
 83287  83562       }
 83288  83563     }
 83289  83564   
 83290  83565     return rc;
................................................................................
 83367  83642         int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
 83368  83643         int nNew = pSorter->nMemory * 2;
 83369  83644         while( nNew < nMin ) nNew = nNew*2;
 83370  83645         if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
 83371  83646         if( nNew < nMin ) nNew = nMin;
 83372  83647   
 83373  83648         aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
 83374         -      if( !aNew ) return SQLITE_NOMEM;
        83649  +      if( !aNew ) return SQLITE_NOMEM_BKPT;
 83375  83650         pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
 83376  83651         pSorter->list.aMemory = aNew;
 83377  83652         pSorter->nMemory = nNew;
 83378  83653       }
 83379  83654   
 83380  83655       pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
 83381  83656       pSorter->iMemory += ROUND8(nReq);
 83382  83657       if( pSorter->list.pList ){
 83383  83658         pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
 83384  83659       }
 83385  83660     }else{
 83386  83661       pNew = (SorterRecord *)sqlite3Malloc(nReq);
 83387  83662       if( pNew==0 ){
 83388         -      return SQLITE_NOMEM;
        83663  +      return SQLITE_NOMEM_BKPT;
 83389  83664       }
 83390  83665       pNew->u.pNext = pSorter->list.pList;
 83391  83666     }
 83392  83667   
 83393  83668     memcpy(SRVAL(pNew), pVal->z, pVal->n);
 83394  83669     pNew->nVal = pVal->n;
 83395  83670     pSorter->list.pList = pNew;
................................................................................
 83528  83803     if( pIncr ){
 83529  83804       pIncr->pMerger = pMerger;
 83530  83805       pIncr->pTask = pTask;
 83531  83806       pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
 83532  83807       pTask->file2.iEof += pIncr->mxSz;
 83533  83808     }else{
 83534  83809       vdbeMergeEngineFree(pMerger);
 83535         -    rc = SQLITE_NOMEM;
        83810  +    rc = SQLITE_NOMEM_BKPT;
 83536  83811     }
 83537  83812     return rc;
 83538  83813   }
 83539  83814   
 83540  83815   #if SQLITE_MAX_WORKER_THREADS>0
 83541  83816   /*
 83542  83817   ** Set the "use-threads" flag on object pIncr.
................................................................................
 83833  84108   ){
 83834  84109     MergeEngine *pNew;              /* Merge engine to return */
 83835  84110     i64 iOff = *piOffset;
 83836  84111     int i;
 83837  84112     int rc = SQLITE_OK;
 83838  84113   
 83839  84114     *ppOut = pNew = vdbeMergeEngineNew(nPMA);
 83840         -  if( pNew==0 ) rc = SQLITE_NOMEM;
        84115  +  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
 83841  84116   
 83842  84117     for(i=0; i<nPMA && rc==SQLITE_OK; i++){
 83843         -    i64 nDummy;
        84118  +    i64 nDummy = 0;
 83844  84119       PmaReader *pReadr = &pNew->aReadr[i];
 83845  84120       rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
 83846  84121       iOff = pReadr->iEof;
 83847  84122     }
 83848  84123   
 83849  84124     if( rc!=SQLITE_OK ){
 83850  84125       vdbeMergeEngineFree(pNew);
................................................................................
 83904  84179     for(i=1; i<nDepth && rc==SQLITE_OK; i++){
 83905  84180       int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
 83906  84181       PmaReader *pReadr = &p->aReadr[iIter];
 83907  84182   
 83908  84183       if( pReadr->pIncr==0 ){
 83909  84184         MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 83910  84185         if( pNew==0 ){
 83911         -        rc = SQLITE_NOMEM;
        84186  +        rc = SQLITE_NOMEM_BKPT;
 83912  84187         }else{
 83913  84188           rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
 83914  84189         }
 83915  84190       }
 83916  84191       if( rc==SQLITE_OK ){
 83917  84192         p = pReadr->pIncr->pMerger;
 83918  84193         nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
................................................................................
 83949  84224   #if SQLITE_MAX_WORKER_THREADS>0
 83950  84225     /* If the sorter uses more than one task, then create the top-level 
 83951  84226     ** MergeEngine here. This MergeEngine will read data from exactly 
 83952  84227     ** one PmaReader per sub-task.  */
 83953  84228     assert( pSorter->bUseThreads || pSorter->nTask==1 );
 83954  84229     if( pSorter->nTask>1 ){
 83955  84230       pMain = vdbeMergeEngineNew(pSorter->nTask);
 83956         -    if( pMain==0 ) rc = SQLITE_NOMEM;
        84231  +    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
 83957  84232     }
 83958  84233   #endif
 83959  84234   
 83960  84235     for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
 83961  84236       SortSubtask *pTask = &pSorter->aTask[iTask];
 83962  84237       assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
 83963  84238       if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
................................................................................
 83967  84242   
 83968  84243         if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
 83969  84244           rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
 83970  84245         }else{
 83971  84246           int i;
 83972  84247           int iSeq = 0;
 83973  84248           pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 83974         -        if( pRoot==0 ) rc = SQLITE_NOMEM;
        84249  +        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
 83975  84250           for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
 83976  84251             MergeEngine *pMerger = 0; /* New level-0 PMA merger */
 83977  84252             int nReader;              /* Number of level-0 PMAs to merge */
 83978  84253   
 83979  84254             nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
 83980  84255             rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
 83981  84256             if( rc==SQLITE_OK ){
................................................................................
 84038  84313         int iTask;
 84039  84314         PmaReader *pReadr = 0;
 84040  84315         SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
 84041  84316         rc = vdbeSortAllocUnpacked(pLast);
 84042  84317         if( rc==SQLITE_OK ){
 84043  84318           pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
 84044  84319           pSorter->pReader = pReadr;
 84045         -        if( pReadr==0 ) rc = SQLITE_NOMEM;
        84320  +        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
 84046  84321         }
 84047  84322         if( rc==SQLITE_OK ){
 84048  84323           rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
 84049  84324           if( rc==SQLITE_OK ){
 84050  84325             vdbeIncrMergerSetThreads(pReadr->pIncr);
 84051  84326             for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
 84052  84327               IncrMerger *pIncr;
................................................................................
 84215  84490     VdbeSorter *pSorter;
 84216  84491     void *pKey; int nKey;           /* Sorter key to copy into pOut */
 84217  84492   
 84218  84493     assert( pCsr->eCurType==CURTYPE_SORTER );
 84219  84494     pSorter = pCsr->uc.pSorter;
 84220  84495     pKey = vdbeSorterRowkey(pSorter, &nKey);
 84221  84496     if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
 84222         -    return SQLITE_NOMEM;
        84497  +    return SQLITE_NOMEM_BKPT;
 84223  84498     }
 84224  84499     pOut->n = nKey;
 84225  84500     MemSetTypeFlag(pOut, MEM_Blob);
 84226  84501     memcpy(pOut->z, pKey, nKey);
 84227  84502   
 84228  84503     return SQLITE_OK;
 84229  84504   }
................................................................................
 84260  84535     pSorter = pCsr->uc.pSorter;
 84261  84536     r2 = pSorter->pUnpacked;
 84262  84537     pKeyInfo = pCsr->pKeyInfo;
 84263  84538     if( r2==0 ){
 84264  84539       char *p;
 84265  84540       r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
 84266  84541       assert( pSorter->pUnpacked==(UnpackedRecord*)p );
 84267         -    if( r2==0 ) return SQLITE_NOMEM;
        84542  +    if( r2==0 ) return SQLITE_NOMEM_BKPT;
 84268  84543       r2->nField = nKeyCol;
 84269  84544     }
 84270  84545     assert( r2->nField==nKeyCol );
 84271  84546   
 84272  84547     pKey = vdbeSorterRowkey(pSorter, &nKey);
 84273  84548     sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
 84274  84549     for(i=0; i<nKeyCol; i++){
................................................................................
 84279  84554     }
 84280  84555   
 84281  84556     *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
 84282  84557     return SQLITE_OK;
 84283  84558   }
 84284  84559   
 84285  84560   /************** End of vdbesort.c ********************************************/
 84286         -/************** Begin file journal.c *****************************************/
 84287         -/*
 84288         -** 2007 August 22
 84289         -**
 84290         -** The author disclaims copyright to this source code.  In place of
 84291         -** a legal notice, here is a blessing:
 84292         -**
 84293         -**    May you do good and not evil.
 84294         -**    May you find forgiveness for yourself and forgive others.
 84295         -**    May you share freely, never taking more than you give.
 84296         -**
 84297         -*************************************************************************
 84298         -**
 84299         -** This file implements a special kind of sqlite3_file object used
 84300         -** by SQLite to create journal files if the atomic-write optimization
 84301         -** is enabled.
 84302         -**
 84303         -** The distinctive characteristic of this sqlite3_file is that the
 84304         -** actual on disk file is created lazily. When the file is created,
 84305         -** the caller specifies a buffer size for an in-memory buffer to
 84306         -** be used to service read() and write() requests. The actual file
 84307         -** on disk is not created or populated until either:
 84308         -**
 84309         -**   1) The in-memory representation grows too large for the allocated 
 84310         -**      buffer, or
 84311         -**   2) The sqlite3JournalCreate() function is called.
 84312         -*/
 84313         -#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 84314         -/* #include "sqliteInt.h" */
 84315         -
 84316         -
 84317         -/*
 84318         -** A JournalFile object is a subclass of sqlite3_file used by
 84319         -** as an open file handle for journal files.
 84320         -*/
 84321         -struct JournalFile {
 84322         -  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
 84323         -  int nBuf;                       /* Size of zBuf[] in bytes */
 84324         -  char *zBuf;                     /* Space to buffer journal writes */
 84325         -  int iSize;                      /* Amount of zBuf[] currently used */
 84326         -  int flags;                      /* xOpen flags */
 84327         -  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
 84328         -  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
 84329         -  const char *zJournal;           /* Name of the journal file */
 84330         -};
 84331         -typedef struct JournalFile JournalFile;
 84332         -
 84333         -/*
 84334         -** If it does not already exists, create and populate the on-disk file 
 84335         -** for JournalFile p.
 84336         -*/
 84337         -static int createFile(JournalFile *p){
 84338         -  int rc = SQLITE_OK;
 84339         -  if( !p->pReal ){
 84340         -    sqlite3_file *pReal = (sqlite3_file *)&p[1];
 84341         -    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
 84342         -    if( rc==SQLITE_OK ){
 84343         -      p->pReal = pReal;
 84344         -      if( p->iSize>0 ){
 84345         -        assert(p->iSize<=p->nBuf);
 84346         -        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
 84347         -      }
 84348         -      if( rc!=SQLITE_OK ){
 84349         -        /* If an error occurred while writing to the file, close it before
 84350         -        ** returning. This way, SQLite uses the in-memory journal data to 
 84351         -        ** roll back changes made to the internal page-cache before this
 84352         -        ** function was called.  */
 84353         -        sqlite3OsClose(pReal);
 84354         -        p->pReal = 0;
 84355         -      }
 84356         -    }
 84357         -  }
 84358         -  return rc;
 84359         -}
 84360         -
 84361         -/*
 84362         -** Close the file.
 84363         -*/
 84364         -static int jrnlClose(sqlite3_file *pJfd){
 84365         -  JournalFile *p = (JournalFile *)pJfd;
 84366         -  if( p->pReal ){
 84367         -    sqlite3OsClose(p->pReal);
 84368         -  }
 84369         -  sqlite3_free(p->zBuf);
 84370         -  return SQLITE_OK;
 84371         -}
 84372         -
 84373         -/*
 84374         -** Read data from the file.
 84375         -*/
 84376         -static int jrnlRead(
 84377         -  sqlite3_file *pJfd,    /* The journal file from which to read */
 84378         -  void *zBuf,            /* Put the results here */
 84379         -  int iAmt,              /* Number of bytes to read */
 84380         -  sqlite_int64 iOfst     /* Begin reading at this offset */
 84381         -){
 84382         -  int rc = SQLITE_OK;
 84383         -  JournalFile *p = (JournalFile *)pJfd;
 84384         -  if( p->pReal ){
 84385         -    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
 84386         -  }else if( (iAmt+iOfst)>p->iSize ){
 84387         -    rc = SQLITE_IOERR_SHORT_READ;
 84388         -  }else{
 84389         -    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
 84390         -  }
 84391         -  return rc;
 84392         -}
 84393         -
 84394         -/*
 84395         -** Write data to the file.
 84396         -*/
 84397         -static int jrnlWrite(
 84398         -  sqlite3_file *pJfd,    /* The journal file into which to write */
 84399         -  const void *zBuf,      /* Take data to be written from here */
 84400         -  int iAmt,              /* Number of bytes to write */
 84401         -  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 84402         -){
 84403         -  int rc = SQLITE_OK;
 84404         -  JournalFile *p = (JournalFile *)pJfd;
 84405         -  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
 84406         -    rc = createFile(p);
 84407         -  }
 84408         -  if( rc==SQLITE_OK ){
 84409         -    if( p->pReal ){
 84410         -      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
 84411         -    }else{
 84412         -      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
 84413         -      if( p->iSize<(iOfst+iAmt) ){
 84414         -        p->iSize = (iOfst+iAmt);
 84415         -      }
 84416         -    }
 84417         -  }
 84418         -  return rc;
 84419         -}
 84420         -
 84421         -/*
 84422         -** Truncate the file.
 84423         -*/
 84424         -static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 84425         -  int rc = SQLITE_OK;
 84426         -  JournalFile *p = (JournalFile *)pJfd;
 84427         -  if( p->pReal ){
 84428         -    rc = sqlite3OsTruncate(p->pReal, size);
 84429         -  }else if( size<p->iSize ){
 84430         -    p->iSize = size;
 84431         -  }
 84432         -  return rc;
 84433         -}
 84434         -
 84435         -/*
 84436         -** Sync the file.
 84437         -*/
 84438         -static int jrnlSync(sqlite3_file *pJfd, int flags){
 84439         -  int rc;
 84440         -  JournalFile *p = (JournalFile *)pJfd;
 84441         -  if( p->pReal ){
 84442         -    rc = sqlite3OsSync(p->pReal, flags);
 84443         -  }else{
 84444         -    rc = SQLITE_OK;
 84445         -  }
 84446         -  return rc;
 84447         -}
 84448         -
 84449         -/*
 84450         -** Query the size of the file in bytes.
 84451         -*/
 84452         -static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
 84453         -  int rc = SQLITE_OK;
 84454         -  JournalFile *p = (JournalFile *)pJfd;
 84455         -  if( p->pReal ){
 84456         -    rc = sqlite3OsFileSize(p->pReal, pSize);
 84457         -  }else{
 84458         -    *pSize = (sqlite_int64) p->iSize;
 84459         -  }
 84460         -  return rc;
 84461         -}
 84462         -
 84463         -/*
 84464         -** Table of methods for JournalFile sqlite3_file object.
 84465         -*/
 84466         -static struct sqlite3_io_methods JournalFileMethods = {
 84467         -  1,             /* iVersion */
 84468         -  jrnlClose,     /* xClose */
 84469         -  jrnlRead,      /* xRead */
 84470         -  jrnlWrite,     /* xWrite */
 84471         -  jrnlTruncate,  /* xTruncate */
 84472         -  jrnlSync,      /* xSync */
 84473         -  jrnlFileSize,  /* xFileSize */
 84474         -  0,             /* xLock */
 84475         -  0,             /* xUnlock */
 84476         -  0,             /* xCheckReservedLock */
 84477         -  0,             /* xFileControl */
 84478         -  0,             /* xSectorSize */
 84479         -  0,             /* xDeviceCharacteristics */
 84480         -  0,             /* xShmMap */
 84481         -  0,             /* xShmLock */
 84482         -  0,             /* xShmBarrier */
 84483         -  0              /* xShmUnmap */
 84484         -};
 84485         -
 84486         -/* 
 84487         -** Open a journal file.
 84488         -*/
 84489         -SQLITE_PRIVATE int sqlite3JournalOpen(
 84490         -  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
 84491         -  const char *zName,         /* Name of the journal file */
 84492         -  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
 84493         -  int flags,                 /* Opening flags */
 84494         -  int nBuf                   /* Bytes buffered before opening the file */
 84495         -){
 84496         -  JournalFile *p = (JournalFile *)pJfd;
 84497         -  memset(p, 0, sqlite3JournalSize(pVfs));
 84498         -  if( nBuf>0 ){
 84499         -    p->zBuf = sqlite3MallocZero(nBuf);
 84500         -    if( !p->zBuf ){
 84501         -      return SQLITE_NOMEM;
 84502         -    }
 84503         -  }else{
 84504         -    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
 84505         -  }
 84506         -  p->pMethod = &JournalFileMethods;
 84507         -  p->nBuf = nBuf;
 84508         -  p->flags = flags;
 84509         -  p->zJournal = zName;
 84510         -  p->pVfs = pVfs;
 84511         -  return SQLITE_OK;
 84512         -}
 84513         -
 84514         -/*
 84515         -** If the argument p points to a JournalFile structure, and the underlying
 84516         -** file has not yet been created, create it now.
 84517         -*/
 84518         -SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
 84519         -  if( p->pMethods!=&JournalFileMethods ){
 84520         -    return SQLITE_OK;
 84521         -  }
 84522         -  return createFile((JournalFile *)p);
 84523         -}
 84524         -
 84525         -/*
 84526         -** The file-handle passed as the only argument is guaranteed to be an open
 84527         -** file. It may or may not be of class JournalFile. If the file is a
 84528         -** JournalFile, and the underlying file on disk has not yet been opened,
 84529         -** return 0. Otherwise, return 1.
 84530         -*/
 84531         -SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
 84532         -  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
 84533         -}
 84534         -
 84535         -/* 
 84536         -** Return the number of bytes required to store a JournalFile that uses vfs
 84537         -** pVfs to create the underlying on-disk files.
 84538         -*/
 84539         -SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
 84540         -  return (pVfs->szOsFile+sizeof(JournalFile));
 84541         -}
 84542         -#endif
 84543         -
 84544         -/************** End of journal.c *********************************************/
 84545  84561   /************** Begin file memjournal.c **************************************/
 84546  84562   /*
 84547  84563   ** 2008 October 7
 84548  84564   **
 84549  84565   ** The author disclaims copyright to this source code.  In place of
 84550  84566   ** a legal notice, here is a blessing:
 84551  84567   **
................................................................................
 84562  84578   /* #include "sqliteInt.h" */
 84563  84579   
 84564  84580   /* Forward references to internal structures */
 84565  84581   typedef struct MemJournal MemJournal;
 84566  84582   typedef struct FilePoint FilePoint;
 84567  84583   typedef struct FileChunk FileChunk;
 84568  84584   
 84569         -/* Space to hold the rollback journal is allocated in increments of
 84570         -** this many bytes.
 84571         -**
 84572         -** The size chosen is a little less than a power of two.  That way,
 84573         -** the FileChunk object will have a size that almost exactly fills
 84574         -** a power-of-two allocation.  This minimizes wasted space in power-of-two
 84575         -** memory allocators.
 84576         -*/
 84577         -#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
 84578         -
 84579  84585   /*
 84580  84586   ** The rollback journal is composed of a linked list of these structures.
        84587  +**
        84588  +** The zChunk array is always at least 8 bytes in size - usually much more.
        84589  +** Its actual size is stored in the MemJournal.nChunkSize variable.
 84581  84590   */
 84582  84591   struct FileChunk {
 84583  84592     FileChunk *pNext;               /* Next chunk in the journal */
 84584         -  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
        84593  +  u8 zChunk[8];                   /* Content of this chunk */
 84585  84594   };
 84586  84595   
        84596  +/*
        84597  +** By default, allocate this many bytes of memory for each FileChunk object.
        84598  +*/
        84599  +#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
        84600  +
        84601  +/*
        84602  +** For chunk size nChunkSize, return the number of bytes that should
        84603  +** be allocated for each FileChunk structure.
        84604  +*/
        84605  +#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
        84606  +
 84587  84607   /*
 84588  84608   ** An instance of this object serves as a cursor into the rollback journal.
 84589  84609   ** The cursor can be either for reading or writing.
 84590  84610   */
 84591  84611   struct FilePoint {
 84592  84612     sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
 84593  84613     FileChunk *pChunk;              /* Specific chunk into which cursor points */
 84594  84614   };
 84595  84615   
 84596  84616   /*
 84597         -** This subclass is a subclass of sqlite3_file.  Each open memory-journal
        84617  +** This structure is a subclass of sqlite3_file. Each open memory-journal
 84598  84618   ** is an instance of this class.
 84599  84619   */
 84600  84620   struct MemJournal {
 84601         -  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
        84621  +  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
        84622  +  int nChunkSize;                 /* In-memory chunk-size */
        84623  +
        84624  +  int nSpill;                     /* Bytes of data before flushing */
        84625  +  int nSize;                      /* Bytes of data currently in memory */
 84602  84626     FileChunk *pFirst;              /* Head of in-memory chunk-list */
 84603  84627     FilePoint endpoint;             /* Pointer to the end of the file */
 84604  84628     FilePoint readpoint;            /* Pointer to the end of the last xRead() */
        84629  +
        84630  +  int flags;                      /* xOpen flags */
        84631  +  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
        84632  +  const char *zJournal;           /* Name of the journal file */
 84605  84633   };
 84606  84634   
 84607  84635   /*
 84608  84636   ** Read data from the in-memory journal file.  This is the implementation
 84609  84637   ** of the sqlite3_vfs.xRead method.
 84610  84638   */
 84611  84639   static int memjrnlRead(
................................................................................
 84616  84644   ){
 84617  84645     MemJournal *p = (MemJournal *)pJfd;
 84618  84646     u8 *zOut = zBuf;
 84619  84647     int nRead = iAmt;
 84620  84648     int iChunkOffset;
 84621  84649     FileChunk *pChunk;
 84622  84650   
 84623         -  /* SQLite never tries to read past the end of a rollback journal file */
 84624         -  assert( iOfst+iAmt<=p->endpoint.iOffset );
        84651  +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
        84652  +  if( (iAmt+iOfst)>p->endpoint.iOffset ){
        84653  +    return SQLITE_IOERR_SHORT_READ;
        84654  +  }
        84655  +#endif
 84625  84656   
        84657  +  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
 84626  84658     if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
 84627  84659       sqlite3_int64 iOff = 0;
 84628  84660       for(pChunk=p->pFirst; 
 84629         -        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
        84661  +        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
 84630  84662           pChunk=pChunk->pNext
 84631  84663       ){
 84632         -      iOff += JOURNAL_CHUNKSIZE;
        84664  +      iOff += p->nChunkSize;
 84633  84665       }
 84634  84666     }else{
 84635  84667       pChunk = p->readpoint.pChunk;
 84636  84668     }
 84637  84669   
 84638         -  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
        84670  +  iChunkOffset = (int)(iOfst%p->nChunkSize);
 84639  84671     do {
 84640         -    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
 84641         -    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
 84642         -    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
        84672  +    int iSpace = p->nChunkSize - iChunkOffset;
        84673  +    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
        84674  +    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
 84643  84675       zOut += nCopy;
 84644  84676       nRead -= iSpace;
 84645  84677       iChunkOffset = 0;
 84646  84678     } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
 84647  84679     p->readpoint.iOffset = iOfst+iAmt;
 84648  84680     p->readpoint.pChunk = pChunk;
 84649  84681   
 84650  84682     return SQLITE_OK;
 84651  84683   }
        84684  +
        84685  +/*
        84686  +** Free the list of FileChunk structures headed at MemJournal.pFirst.
        84687  +*/
        84688  +static void memjrnlFreeChunks(MemJournal *p){
        84689  +  FileChunk *pIter;
        84690  +  FileChunk *pNext;
        84691  +  for(pIter=p->pFirst; pIter; pIter=pNext){
        84692  +    pNext = pIter->pNext;
        84693  +    sqlite3_free(pIter);
        84694  +  } 
        84695  +  p->pFirst = 0;
        84696  +}
        84697  +
        84698  +/*
        84699  +** Flush the contents of memory to a real file on disk.
        84700  +*/
        84701  +static int memjrnlCreateFile(MemJournal *p){
        84702  +  int rc;
        84703  +  sqlite3_file *pReal = (sqlite3_file*)p;
        84704  +  MemJournal copy = *p;
        84705  +
        84706  +  memset(p, 0, sizeof(MemJournal));
        84707  +  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
        84708  +  if( rc==SQLITE_OK ){
        84709  +    int nChunk = copy.nChunkSize;
        84710  +    i64 iOff = 0;
        84711  +    FileChunk *pIter;
        84712  +    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
        84713  +      if( iOff + nChunk > copy.endpoint.iOffset ){
        84714  +        nChunk = copy.endpoint.iOffset - iOff;
        84715  +      }
        84716  +      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
        84717  +      if( rc ) break;
        84718  +      iOff += nChunk;
        84719  +    }
        84720  +    if( rc==SQLITE_OK ){
        84721  +      /* No error has occurred. Free the in-memory buffers. */
        84722  +      memjrnlFreeChunks(&copy);
        84723  +    }
        84724  +  }
        84725  +  if( rc!=SQLITE_OK ){
        84726  +    /* If an error occurred while creating or writing to the file, restore
        84727  +    ** the original before returning. This way, SQLite uses the in-memory
        84728  +    ** journal data to roll back changes made to the internal page-cache
        84729  +    ** before this function was called.  */
        84730  +    sqlite3OsClose(pReal);
        84731  +    *p = copy;
        84732  +  }
        84733  +  return rc;
        84734  +}
        84735  +
 84652  84736   
 84653  84737   /*
 84654  84738   ** Write data to the file.
 84655  84739   */
 84656  84740   static int memjrnlWrite(
 84657  84741     sqlite3_file *pJfd,    /* The journal file into which to write */
 84658  84742     const void *zBuf,      /* Take data to be written from here */
................................................................................
 84659  84743     int iAmt,              /* Number of bytes to write */
 84660  84744     sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 84661  84745   ){
 84662  84746     MemJournal *p = (MemJournal *)pJfd;
 84663  84747     int nWrite = iAmt;
 84664  84748     u8 *zWrite = (u8 *)zBuf;
 84665  84749   
 84666         -  /* An in-memory journal file should only ever be appended to. Random
 84667         -  ** access writes are not required by sqlite.
 84668         -  */
 84669         -  assert( iOfst==p->endpoint.iOffset );
 84670         -  UNUSED_PARAMETER(iOfst);
 84671         -
 84672         -  while( nWrite>0 ){
 84673         -    FileChunk *pChunk = p->endpoint.pChunk;
 84674         -    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
 84675         -    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
 84676         -
 84677         -    if( iChunkOffset==0 ){
 84678         -      /* New chunk is required to extend the file. */
 84679         -      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
 84680         -      if( !pNew ){
 84681         -        return SQLITE_IOERR_NOMEM;
 84682         -      }
 84683         -      pNew->pNext = 0;
 84684         -      if( pChunk ){
 84685         -        assert( p->pFirst );
 84686         -        pChunk->pNext = pNew;
 84687         -      }else{
 84688         -        assert( !p->pFirst );
 84689         -        p->pFirst = pNew;
 84690         -      }
 84691         -      p->endpoint.pChunk = pNew;
 84692         -    }
 84693         -
 84694         -    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
 84695         -    zWrite += iSpace;
 84696         -    nWrite -= iSpace;
 84697         -    p->endpoint.iOffset += iSpace;
        84750  +  /* If the file should be created now, create it and write the new data
        84751  +  ** into the file on disk. */
        84752  +  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
        84753  +    int rc = memjrnlCreateFile(p);
        84754  +    if( rc==SQLITE_OK ){
        84755  +      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
        84756  +    }
        84757  +    return rc;
        84758  +  }
        84759  +
        84760  +  /* If the contents of this write should be stored in memory */
        84761  +  else{
        84762  +    /* An in-memory journal file should only ever be appended to. Random
        84763  +    ** access writes are not required. The only exception to this is when
        84764  +    ** the in-memory journal is being used by a connection using the
        84765  +    ** atomic-write optimization. In this case the first 28 bytes of the
        84766  +    ** journal file may be written as part of committing the transaction. */ 
        84767  +    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
        84768  +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
        84769  +    if( iOfst==0 && p->pFirst ){
        84770  +      assert( p->nChunkSize>iAmt );
        84771  +      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
        84772  +    }else
        84773  +#else
        84774  +    assert( iOfst>0 || p->pFirst==0 );
        84775  +#endif
        84776  +    {
        84777  +      while( nWrite>0 ){
        84778  +        FileChunk *pChunk = p->endpoint.pChunk;
        84779  +        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
        84780  +        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
        84781  +
        84782  +        if( iChunkOffset==0 ){
        84783  +          /* New chunk is required to extend the file. */
        84784  +          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
        84785  +          if( !pNew ){
        84786  +            return SQLITE_IOERR_NOMEM_BKPT;
        84787  +          }
        84788  +          pNew->pNext = 0;
        84789  +          if( pChunk ){
        84790  +            assert( p->pFirst );
        84791  +            pChunk->pNext = pNew;
        84792  +          }else{
        84793  +            assert( !p->pFirst );
        84794  +            p->pFirst = pNew;
        84795  +          }
        84796  +          p->endpoint.pChunk = pNew;
        84797  +        }
        84798  +
        84799  +        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
        84800  +        zWrite += iSpace;
        84801  +        nWrite -= iSpace;
        84802  +        p->endpoint.iOffset += iSpace;
        84803  +      }
        84804  +      p->nSize = iAmt + iOfst;
        84805  +    }
 84698  84806     }
 84699  84807   
 84700  84808     return SQLITE_OK;
 84701  84809   }
 84702  84810   
 84703  84811   /*
 84704  84812   ** Truncate the file.
        84813  +**
        84814  +** If the journal file is already on disk, truncate it there. Or, if it
        84815  +** is still in main memory but is being truncated to zero bytes in size,
        84816  +** ignore 
 84705  84817   */
 84706  84818   static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 84707  84819     MemJournal *p = (MemJournal *)pJfd;
 84708         -  FileChunk *pChunk;
 84709         -  assert(size==0);
 84710         -  UNUSED_PARAMETER(size);
 84711         -  pChunk = p->pFirst;
 84712         -  while( pChunk ){
 84713         -    FileChunk *pTmp = pChunk;
 84714         -    pChunk = pChunk->pNext;
 84715         -    sqlite3_free(pTmp);
        84820  +  if( ALWAYS(size==0) ){
        84821  +    memjrnlFreeChunks(p);
        84822  +    p->nSize = 0;
        84823  +    p->endpoint.pChunk = 0;
        84824  +    p->endpoint.iOffset = 0;
        84825  +    p->readpoint.pChunk = 0;
        84826  +    p->readpoint.iOffset = 0;
 84716  84827     }
 84717         -  sqlite3MemJournalOpen(pJfd);
 84718  84828     return SQLITE_OK;
 84719  84829   }
 84720  84830   
 84721  84831   /*
 84722  84832   ** Close the file.
 84723  84833   */
 84724  84834   static int memjrnlClose(sqlite3_file *pJfd){
 84725         -  memjrnlTruncate(pJfd, 0);
        84835  +  MemJournal *p = (MemJournal *)pJfd;
        84836  +  memjrnlFreeChunks(p);
 84726  84837     return SQLITE_OK;
 84727  84838   }
 84728         -
 84729  84839   
 84730  84840   /*
 84731  84841   ** Sync the file.
 84732  84842   **
 84733         -** Syncing an in-memory journal is a no-op.  And, in fact, this routine
 84734         -** is never called in a working implementation.  This implementation
 84735         -** exists purely as a contingency, in case some malfunction in some other
 84736         -** part of SQLite causes Sync to be called by mistake.
        84843  +** If the real file has been created, call its xSync method. Otherwise, 
        84844  +** syncing an in-memory journal is a no-op. 
 84737  84845   */
 84738         -static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
 84739         -  UNUSED_PARAMETER2(NotUsed, NotUsed2);
        84846  +static int memjrnlSync(sqlite3_file *pJfd, int flags){
        84847  +  UNUSED_PARAMETER2(pJfd, flags);
 84740  84848     return SQLITE_OK;
 84741  84849   }
 84742  84850   
 84743  84851   /*
 84744  84852   ** Query the size of the file in bytes.
 84745  84853   */
 84746  84854   static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
................................................................................
 84771  84879     0,                /* xShmBarrier */
 84772  84880     0,                /* xShmUnmap */
 84773  84881     0,                /* xFetch */
 84774  84882     0                 /* xUnfetch */
 84775  84883   };
 84776  84884   
 84777  84885   /* 
 84778         -** Open a journal file.
        84886  +** Open a journal file. 
        84887  +**
        84888  +** The behaviour of the journal file depends on the value of parameter 
        84889  +** nSpill. If nSpill is 0, then the journal file is always create and 
        84890  +** accessed using the underlying VFS. If nSpill is less than zero, then
        84891  +** all content is always stored in main-memory. Finally, if nSpill is a
        84892  +** positive value, then the journal file is initially created in-memory
        84893  +** but may be flushed to disk later on. In this case the journal file is
        84894  +** flushed to disk either when it grows larger than nSpill bytes in size,
        84895  +** or when sqlite3JournalCreate() is called.
        84896  +*/
        84897  +SQLITE_PRIVATE int sqlite3JournalOpen(
        84898  +  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
        84899  +  const char *zName,         /* Name of the journal file */
        84900  +  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
        84901  +  int flags,                 /* Opening flags */
        84902  +  int nSpill                 /* Bytes buffered before opening the file */
        84903  +){
        84904  +  MemJournal *p = (MemJournal*)pJfd;
        84905  +
        84906  +  /* Zero the file-handle object. If nSpill was passed zero, initialize
        84907  +  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
        84908  +  ** case none of the code in this module is executed as a result of calls
        84909  +  ** made on the journal file-handle.  */
        84910  +  memset(p, 0, sizeof(MemJournal));
        84911  +  if( nSpill==0 ){
        84912  +    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
        84913  +  }
        84914  +
        84915  +  if( nSpill>0 ){
        84916  +    p->nChunkSize = nSpill;
        84917  +  }else{
        84918  +    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
        84919  +    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
        84920  +  }
        84921  +
        84922  +  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
        84923  +  p->nSpill = nSpill;
        84924  +  p->flags = flags;
        84925  +  p->zJournal = zName;
        84926  +  p->pVfs = pVfs;
        84927  +  return SQLITE_OK;
        84928  +}
        84929  +
        84930  +/*
        84931  +** Open an in-memory journal file.
 84779  84932   */
 84780  84933   SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
 84781         -  MemJournal *p = (MemJournal *)pJfd;
 84782         -  assert( EIGHT_BYTE_ALIGNMENT(p) );
 84783         -  memset(p, 0, sqlite3MemJournalSize());
 84784         -  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
 84785         -}
 84786         -
 84787         -/*
 84788         -** Return true if the file-handle passed as an argument is 
 84789         -** an in-memory journal 
 84790         -*/
 84791         -SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
 84792         -  return pJfd->pMethods==&MemJournalMethods;
 84793         -}
 84794         -
 84795         -/* 
 84796         -** Return the number of bytes required to store a MemJournal file descriptor.
 84797         -*/
 84798         -SQLITE_PRIVATE int sqlite3MemJournalSize(void){
 84799         -  return sizeof(MemJournal);
        84934  +  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
        84935  +}
        84936  +
        84937  +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
        84938  +/*
        84939  +** If the argument p points to a MemJournal structure that is not an 
        84940  +** in-memory-only journal file (i.e. is one that was opened with a +ve
        84941  +** nSpill parameter), and the underlying file has not yet been created, 
        84942  +** create it now.
        84943  +*/
        84944  +SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
        84945  +  int rc = SQLITE_OK;
        84946  +  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
        84947  +    rc = memjrnlCreateFile((MemJournal*)p);
        84948  +  }
        84949  +  return rc;
        84950  +}
        84951  +#endif
        84952  +
        84953  +/*
        84954  +** The file-handle passed as the only argument is open on a journal file.
        84955  +** Return true if this "journal file" is currently stored in heap memory,
        84956  +** or false otherwise.
        84957  +*/
        84958  +SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
        84959  +  return p->pMethods==&MemJournalMethods;
        84960  +}
        84961  +
        84962  +/* 
        84963  +** Return the number of bytes required to store a JournalFile that uses vfs
        84964  +** pVfs to create the underlying on-disk files.
        84965  +*/
        84966  +SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
        84967  +  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
 84800  84968   }
 84801  84969   
 84802  84970   /************** End of memjournal.c ******************************************/
 84803  84971   /************** Begin file walker.c ******************************************/
 84804  84972   /*
 84805  84973   ** 2008 August 16
 84806  84974   **
................................................................................
 85619  85787         FuncDef *pDef;              /* Information about the function */
 85620  85788         u8 enc = ENC(pParse->db);   /* The database encoding */
 85621  85789   
 85622  85790         assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 85623  85791         notValid(pParse, pNC, "functions", NC_PartIdx);
 85624  85792         zId = pExpr->u.zToken;
 85625  85793         nId = sqlite3Strlen30(zId);
 85626         -      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
        85794  +      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
 85627  85795         if( pDef==0 ){
 85628         -        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
        85796  +        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
 85629  85797           if( pDef==0 ){
 85630  85798             no_such_func = 1;
 85631  85799           }else{
 85632  85800             wrong_num_args = 1;
 85633  85801           }
 85634  85802         }else{
 85635  85803           is_agg = pDef->xFinalize!=0;
................................................................................
 87745  87913   */
 87746  87914   SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
 87747  87915     int i;
 87748  87916     u32 m = 0;
 87749  87917     if( pList ){
 87750  87918       for(i=0; i<pList->nExpr; i++){
 87751  87919          Expr *pExpr = pList->a[i].pExpr;
 87752         -       if( ALWAYS(pExpr) ) m |= pExpr->flags;
        87920  +       assert( pExpr!=0 );
        87921  +       m |= pExpr->flags;
 87753  87922       }
 87754  87923     }
 87755  87924     return m;
 87756  87925   }
 87757  87926   
 87758  87927   /*
 87759  87928   ** These routines are Walker callbacks used to check expressions to
................................................................................
 88030  88199     if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
 88031  88200     if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
 88032  88201     if( sqlite3StrICmp(z, "OID")==0 ) return 1;
 88033  88202     return 0;
 88034  88203   }
 88035  88204   
 88036  88205   /*
 88037         -** Return true if we are able to the IN operator optimization on a
 88038         -** query of the form
 88039         -**
 88040         -**       x IN (SELECT ...)
 88041         -**
 88042         -** Where the SELECT... clause is as specified by the parameter to this
 88043         -** routine.
 88044         -**
 88045         -** The Select object passed in has already been preprocessed and no
 88046         -** errors have been found.
        88206  +** pX is the RHS of an IN operator.  If pX is a SELECT statement 
        88207  +** that can be simplified to a direct table access, then return
        88208  +** a pointer to the SELECT statement.  If pX is not a SELECT statement,
        88209  +** or if the SELECT statement needs to be manifested into a transient
        88210  +** table, then return NULL.
 88047  88211   */
 88048  88212   #ifndef SQLITE_OMIT_SUBQUERY
 88049         -static int isCandidateForInOpt(Select *p){
        88213  +static Select *isCandidateForInOpt(Expr *pX){
        88214  +  Select *p;
 88050  88215     SrcList *pSrc;
 88051  88216     ExprList *pEList;
        88217  +  Expr *pRes;
 88052  88218     Table *pTab;
 88053         -  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
        88219  +  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
        88220  +  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
        88221  +  p = pX->x.pSelect;
 88054  88222     if( p->pPrior ) return 0;              /* Not a compound SELECT */
 88055  88223     if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
 88056  88224       testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
 88057  88225       testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
 88058  88226       return 0; /* No DISTINCT keyword and no aggregate functions */
 88059  88227     }
 88060  88228     assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
................................................................................
 88062  88230     assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
 88063  88231     if( p->pWhere ) return 0;              /* Has no WHERE clause */
 88064  88232     pSrc = p->pSrc;
 88065  88233     assert( pSrc!=0 );
 88066  88234     if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
 88067  88235     if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
 88068  88236     pTab = pSrc->a[0].pTab;
 88069         -  if( NEVER(pTab==0) ) return 0;
        88237  +  assert( pTab!=0 );
 88070  88238     assert( pTab->pSelect==0 );            /* FROM clause is not a view */
 88071  88239     if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
 88072  88240     pEList = p->pEList;
 88073  88241     if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
 88074         -  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
 88075         -  return 1;
        88242  +  pRes = pEList->a[0].pExpr;
        88243  +  if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
        88244  +  assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
        88245  +  return p;
 88076  88246   }
 88077  88247   #endif /* SQLITE_OMIT_SUBQUERY */
 88078  88248   
 88079  88249   /*
 88080  88250   ** Code an OP_Once instruction and allocate space for its flag. Return the 
 88081  88251   ** address of the new instruction.
 88082  88252   */
................................................................................
 88200  88370     assert( pX->op==TK_IN );
 88201  88371     mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
 88202  88372   
 88203  88373     /* Check to see if an existing table or index can be used to
 88204  88374     ** satisfy the query.  This is preferable to generating a new 
 88205  88375     ** ephemeral table.
 88206  88376     */
 88207         -  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
 88208         -  if( pParse->nErr==0 && isCandidateForInOpt(p) ){
        88377  +  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
 88209  88378       sqlite3 *db = pParse->db;              /* Database connection */
 88210  88379       Table *pTab;                           /* Table <table>. */
 88211  88380       Expr *pExpr;                           /* Expression <column> */
 88212  88381       i16 iCol;                              /* Index of column <column> */
 88213  88382       i16 iDb;                               /* Database idx for pTab */
 88214  88383   
 88215         -    assert( p );                        /* Because of isCandidateForInOpt(p) */
 88216  88384       assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
 88217  88385       assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
 88218  88386       assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
 88219  88387       pTab = p->pSrc->a[0].pTab;
 88220  88388       pExpr = p->pEList->a[0].pExpr;
 88221  88389       iCol = (i16)pExpr->iColumn;
 88222  88390      
................................................................................
 89350  89518         }
 89351  89519         break;
 89352  89520       }
 89353  89521       case TK_FUNCTION: {
 89354  89522         ExprList *pFarg;       /* List of function arguments */
 89355  89523         int nFarg;             /* Number of function arguments */
 89356  89524         FuncDef *pDef;         /* The function definition object */
 89357         -      int nId;               /* Length of the function name in bytes */
 89358  89525         const char *zId;       /* The function name */
 89359  89526         u32 constMask = 0;     /* Mask of function arguments that are constant */
 89360  89527         int i;                 /* Loop counter */
 89361  89528         u8 enc = ENC(db);      /* The text encoding used by this database */
 89362  89529         CollSeq *pColl = 0;    /* A collating sequence */
 89363  89530   
 89364  89531         assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
................................................................................
 89366  89533           pFarg = 0;
 89367  89534         }else{
 89368  89535           pFarg = pExpr->x.pList;
 89369  89536         }
 89370  89537         nFarg = pFarg ? pFarg->nExpr : 0;
 89371  89538         assert( !ExprHasProperty(pExpr, EP_IntValue) );
 89372  89539         zId = pExpr->u.zToken;
 89373         -      nId = sqlite3Strlen30(zId);
 89374         -      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
        89540  +      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
 89375  89541         if( pDef==0 || pDef->xFinalize!=0 ){
 89376         -        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
        89542  +        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
 89377  89543           break;
 89378  89544         }
 89379  89545   
 89380  89546         /* Attempt a direct implementation of the built-in COALESCE() and
 89381  89547         ** IFNULL() functions.  This avoids unnecessary evaluation of
 89382  89548         ** arguments past the first non-NULL argument.
 89383  89549         */
................................................................................
 89534  89700         codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
 89535  89701         VdbeCoverage(v);
 89536  89702         sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
 89537  89703         sqlite3ReleaseTempReg(pParse, r3);
 89538  89704         sqlite3ReleaseTempReg(pParse, r4);
 89539  89705         break;
 89540  89706       }
        89707  +    case TK_SPAN:
 89541  89708       case TK_COLLATE: 
 89542  89709       case TK_UPLUS: {
 89543  89710         inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 89544  89711         break;
 89545  89712       }
 89546  89713   
 89547  89714       case TK_TRIGGER: {
................................................................................
 90012  90179         break;
 90013  90180       }
 90014  90181       case TK_NOT: {
 90015  90182         testcase( jumpIfNull==0 );
 90016  90183         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 90017  90184         break;
 90018  90185       }
        90186  +    case TK_IS:
        90187  +    case TK_ISNOT:
        90188  +      testcase( op==TK_IS );
        90189  +      testcase( op==TK_ISNOT );
        90190  +      op = (op==TK_IS) ? TK_EQ : TK_NE;
        90191  +      jumpIfNull = SQLITE_NULLEQ;
        90192  +      /* Fall thru */
 90019  90193       case TK_LT:
 90020  90194       case TK_LE:
 90021  90195       case TK_GT:
 90022  90196       case TK_GE:
 90023  90197       case TK_NE:
 90024  90198       case TK_EQ: {
 90025  90199         testcase( jumpIfNull==0 );
................................................................................
 90027  90201         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 90028  90202         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 90029  90203                     r1, r2, dest, jumpIfNull);
 90030  90204         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 90031  90205         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 90032  90206         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 90033  90207         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 90034         -      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 90035         -      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 90036         -      testcase( regFree1==0 );
 90037         -      testcase( regFree2==0 );
 90038         -      break;
 90039         -    }
 90040         -    case TK_IS:
 90041         -    case TK_ISNOT: {
 90042         -      testcase( op==TK_IS );
 90043         -      testcase( op==TK_ISNOT );
 90044         -      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 90045         -      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 90046         -      op = (op==TK_IS) ? TK_EQ : TK_NE;
 90047         -      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 90048         -                  r1, r2, dest, SQLITE_NULLEQ);
 90049         -      VdbeCoverageIf(v, op==TK_EQ);
 90050         -      VdbeCoverageIf(v, op==TK_NE);
        90208  +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
        90209  +      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
        90210  +      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
        90211  +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
        90212  +      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
        90213  +      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
 90051  90214         testcase( regFree1==0 );
 90052  90215         testcase( regFree2==0 );
 90053  90216         break;
 90054  90217       }
 90055  90218       case TK_ISNULL:
 90056  90219       case TK_NOTNULL: {
 90057  90220         assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
................................................................................
 90168  90331         break;
 90169  90332       }
 90170  90333       case TK_NOT: {
 90171  90334         testcase( jumpIfNull==0 );
 90172  90335         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 90173  90336         break;
 90174  90337       }
        90338  +    case TK_IS:
        90339  +    case TK_ISNOT:
        90340  +      testcase( pExpr->op==TK_IS );
        90341  +      testcase( pExpr->op==TK_ISNOT );
        90342  +      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
        90343  +      jumpIfNull = SQLITE_NULLEQ;
        90344  +      /* Fall thru */
 90175  90345       case TK_LT:
 90176  90346       case TK_LE:
 90177  90347       case TK_GT:
 90178  90348       case TK_GE:
 90179  90349       case TK_NE:
 90180  90350       case TK_EQ: {
 90181  90351         testcase( jumpIfNull==0 );
................................................................................
 90183  90353         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 90184  90354         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 90185  90355                     r1, r2, dest, jumpIfNull);
 90186  90356         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 90187  90357         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 90188  90358         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 90189  90359         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 90190         -      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 90191         -      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 90192         -      testcase( regFree1==0 );
 90193         -      testcase( regFree2==0 );
 90194         -      break;
 90195         -    }
 90196         -    case TK_IS:
 90197         -    case TK_ISNOT: {
 90198         -      testcase( pExpr->op==TK_IS );
 90199         -      testcase( pExpr->op==TK_ISNOT );
 90200         -      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 90201         -      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 90202         -      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
 90203         -      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 90204         -                  r1, r2, dest, SQLITE_NULLEQ);
 90205         -      VdbeCoverageIf(v, op==TK_EQ);
 90206         -      VdbeCoverageIf(v, op==TK_NE);
        90360  +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
        90361  +      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
        90362  +      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
        90363  +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
        90364  +      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
        90365  +      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
 90207  90366         testcase( regFree1==0 );
 90208  90367         testcase( regFree2==0 );
 90209  90368         break;
 90210  90369       }
 90211  90370       case TK_ISNULL:
 90212  90371       case TK_NOTNULL: {
 90213  90372         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
................................................................................
 90594  90753             if( i>=0 ){
 90595  90754               assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 90596  90755               pItem = &pAggInfo->aFunc[i];
 90597  90756               pItem->pExpr = pExpr;
 90598  90757               pItem->iMem = ++pParse->nMem;
 90599  90758               assert( !ExprHasProperty(pExpr, EP_IntValue) );
 90600  90759               pItem->pFunc = sqlite3FindFunction(pParse->db,
 90601         -                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
        90760  +                   pExpr->u.zToken, 
 90602  90761                      pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
 90603  90762               if( pExpr->flags & EP_Distinct ){
 90604  90763                 pItem->iDistinct = pParse->nTab++;
 90605  90764               }else{
 90606  90765                 pItem->iDistinct = -1;
 90607  90766               }
 90608  90767             }
................................................................................
 90723  90882   ** Mark all temporary registers as being unavailable for reuse.
 90724  90883   */
 90725  90884   SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
 90726  90885     pParse->nTempReg = 0;
 90727  90886     pParse->nRangeReg = 0;
 90728  90887   }
 90729  90888   
        90889  +/*
        90890  +** Validate that no temporary register falls within the range of
        90891  +** iFirst..iLast, inclusive.  This routine is only call from within assert()
        90892  +** statements.
        90893  +*/
        90894  +#ifdef SQLITE_DEBUG
        90895  +SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
        90896  +  int i;
        90897  +  if( pParse->nRangeReg>0
        90898  +   && pParse->iRangeReg+pParse->nRangeReg<iLast
        90899  +   && pParse->iRangeReg>=iFirst
        90900  +  ){
        90901  +     return 0;
        90902  +  }
        90903  +  for(i=0; i<pParse->nTempReg; i++){
        90904  +    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
        90905  +      return 0;
        90906  +    }
        90907  +  }
        90908  +  return 1;
        90909  +}
        90910  +#endif /* SQLITE_DEBUG */
        90911  +
 90730  90912   /************** End of expr.c ************************************************/
 90731  90913   /************** Begin file alter.c *******************************************/
 90732  90914   /*
 90733  90915   ** 2005 February 15
 90734  90916   **
 90735  90917   ** The author disclaims copyright to this source code.  In place of
 90736  90918   ** a legal notice, here is a blessing:
................................................................................
 90956  91138   }
 90957  91139   #endif   /* !SQLITE_OMIT_TRIGGER */
 90958  91140   
 90959  91141   /*
 90960  91142   ** Register built-in functions used to help implement ALTER TABLE
 90961  91143   */
 90962  91144   SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 90963         -  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
        91145  +  static FuncDef aAlterTableFuncs[] = {
 90964  91146       FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
 90965  91147   #ifndef SQLITE_OMIT_TRIGGER
 90966  91148       FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
 90967  91149   #endif
 90968  91150   #ifndef SQLITE_OMIT_FOREIGN_KEY
 90969  91151       FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
 90970  91152   #endif
 90971  91153     };
 90972         -  int i;
 90973         -  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 90974         -  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
 90975         -
 90976         -  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
 90977         -    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 90978         -  }
        91154  +  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
 90979  91155   }
 90980  91156   
 90981  91157   /*
 90982  91158   ** This function is used to create the text of expressions of the form:
 90983  91159   **
 90984  91160   **   name=<constant1> OR name=<constant2> OR ...
 90985  91161   **
................................................................................
 91361  91537     }
 91362  91538   #endif
 91363  91539   
 91364  91540     /* If the default value for the new column was specified with a 
 91365  91541     ** literal NULL, then set pDflt to 0. This simplifies checking
 91366  91542     ** for an SQL NULL default below.
 91367  91543     */
 91368         -  if( pDflt && pDflt->op==TK_NULL ){
        91544  +  assert( pDflt==0 || pDflt->op==TK_SPAN );
        91545  +  if( pDflt && pDflt->pLeft->op==TK_NULL ){
 91369  91546       pDflt = 0;
 91370  91547     }
 91371  91548   
 91372  91549     /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
 91373  91550     ** If there is a NOT NULL constraint, then the default value for the
 91374  91551     ** column must not be NULL.
 91375  91552     */
................................................................................
 91518  91695       goto exit_begin_add_column;
 91519  91696     }
 91520  91697     memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
 91521  91698     for(i=0; i<pNew->nCol; i++){
 91522  91699       Column *pCol = &pNew->aCol[i];
 91523  91700       pCol->zName = sqlite3DbStrDup(db, pCol->zName);
 91524  91701       pCol->zColl = 0;
 91525         -    pCol->zType = 0;
 91526  91702       pCol->pDflt = 0;
 91527         -    pCol->zDflt = 0;
 91528  91703     }
 91529  91704     pNew->pSchema = db->aDb[iDb].pSchema;
 91530  91705     pNew->addColOffset = pTab->addColOffset;
 91531  91706     pNew->nRef = 1;
 91532  91707   
 91533  91708     /* Begin a transaction and increment the schema cookie.  */
 91534  91709     sqlite3BeginWriteOperation(pParse, 0, iDb);
................................................................................
 92023  92198     2+IsStat34,      /* nArg */
 92024  92199     SQLITE_UTF8,     /* funcFlags */
 92025  92200     0,               /* pUserData */
 92026  92201     0,               /* pNext */
 92027  92202     statInit,        /* xSFunc */
 92028  92203     0,               /* xFinalize */
 92029  92204     "stat_init",     /* zName */
 92030         -  0,               /* pHash */
 92031         -  0                /* pDestructor */
        92205  +  {0}
 92032  92206   };
 92033  92207   
 92034  92208   #ifdef SQLITE_ENABLE_STAT4
 92035  92209   /*
 92036  92210   ** pNew and pOld are both candidate non-periodic samples selected for 
 92037  92211   ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
 92038  92212   ** considering only any trailing columns and the sample hash value, this
................................................................................
 92323  92497     2+IsStat34,      /* nArg */
 92324  92498     SQLITE_UTF8,     /* funcFlags */
 92325  92499     0,               /* pUserData */
 92326  92500     0,               /* pNext */
 92327  92501     statPush,        /* xSFunc */
 92328  92502     0,               /* xFinalize */
 92329  92503     "stat_push",     /* zName */
 92330         -  0,               /* pHash */
 92331         -  0                /* pDestructor */
        92504  +  {0}
 92332  92505   };
 92333  92506   
 92334  92507   #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
 92335  92508   #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
 92336  92509   #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
 92337  92510   #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
 92338  92511   #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
................................................................................
 92469  92642     1+IsStat34,      /* nArg */
 92470  92643     SQLITE_UTF8,     /* funcFlags */
 92471  92644     0,               /* pUserData */
 92472  92645     0,               /* pNext */
 92473  92646     statGet,         /* xSFunc */
 92474  92647     0,               /* xFinalize */
 92475  92648     "stat_get",      /* zName */
 92476         -  0,               /* pHash */
 92477         -  0                /* pDestructor */
        92649  +  {0}
 92478  92650   };
 92479  92651   
 92480  92652   static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
 92481  92653     assert( regOut!=regStat4 && regOut!=regStat4+1 );
 92482  92654   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 92483  92655     sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
 92484  92656   #elif SQLITE_DEBUG
................................................................................
 93215  93387     char *zSql;                   /* Text of the SQL statement */
 93216  93388     Index *pPrevIdx = 0;          /* Previous index in the loop */
 93217  93389     IndexSample *pSample;         /* A slot in pIdx->aSample[] */
 93218  93390   
 93219  93391     assert( db->lookaside.bDisable );
 93220  93392     zSql = sqlite3MPrintf(db, zSql1, zDb);
 93221  93393     if( !zSql ){
 93222         -    return SQLITE_NOMEM;
        93394  +    return SQLITE_NOMEM_BKPT;
 93223  93395     }
 93224  93396     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 93225  93397     sqlite3DbFree(db, zSql);
 93226  93398     if( rc ) return rc;
 93227  93399   
 93228  93400     while( sqlite3_step(pStmt)==SQLITE_ROW ){
 93229  93401       int nIdxCol = 1;              /* Number of columns in stat4 records */
................................................................................
 93255  93427       nByte = sizeof(IndexSample) * nSample;
 93256  93428       nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
 93257  93429       nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
 93258  93430   
 93259  93431       pIdx->aSample = sqlite3DbMallocZero(db, nByte);
 93260  93432       if( pIdx->aSample==0 ){
 93261  93433         sqlite3_finalize(pStmt);
 93262         -      return SQLITE_NOMEM;
        93434  +      return SQLITE_NOMEM_BKPT;
 93263  93435       }
 93264  93436       pSpace = (tRowcnt*)&pIdx->aSample[nSample];
 93265  93437       pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
 93266  93438       for(i=0; i<nSample; i++){
 93267  93439         pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
 93268  93440         pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
 93269  93441         pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
................................................................................
 93271  93443       assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
 93272  93444     }
 93273  93445     rc = sqlite3_finalize(pStmt);
 93274  93446     if( rc ) return rc;
 93275  93447   
 93276  93448     zSql = sqlite3MPrintf(db, zSql2, zDb);
 93277  93449     if( !zSql ){
 93278         -    return SQLITE_NOMEM;
        93450  +    return SQLITE_NOMEM_BKPT;
 93279  93451     }
 93280  93452     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 93281  93453     sqlite3DbFree(db, zSql);
 93282  93454     if( rc ) return rc;
 93283  93455   
 93284  93456     while( sqlite3_step(pStmt)==SQLITE_ROW ){
 93285  93457       char *zIndex;                 /* Index name */
................................................................................
 93309  93481       ** end of the allocated buffer before it realizes it is dealing with
 93310  93482       ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
 93311  93483       ** a buffer overread.  */
 93312  93484       pSample->n = sqlite3_column_bytes(pStmt, 4);
 93313  93485       pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
 93314  93486       if( pSample->p==0 ){
 93315  93487         sqlite3_finalize(pStmt);
 93316         -      return SQLITE_NOMEM;
        93488  +      return SQLITE_NOMEM_BKPT;
 93317  93489       }
 93318  93490       memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
 93319  93491       pIdx->nSample++;
 93320  93492     }
 93321  93493     rc = sqlite3_finalize(pStmt);
 93322  93494     if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
 93323  93495     return rc;
................................................................................
 93398  93570       return SQLITE_ERROR;
 93399  93571     }
 93400  93572   
 93401  93573     /* Load new statistics out of the sqlite_stat1 table */
 93402  93574     zSql = sqlite3MPrintf(db, 
 93403  93575         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
 93404  93576     if( zSql==0 ){
 93405         -    rc = SQLITE_NOMEM;
        93577  +    rc = SQLITE_NOMEM_BKPT;
 93406  93578     }else{
 93407  93579       rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
 93408  93580       sqlite3DbFree(db, zSql);
 93409  93581     }
 93410  93582   
 93411  93583   
 93412  93584     /* Load the statistics from the sqlite_stat4 table. */
................................................................................
 93576  93748     if( rc==SQLITE_CONSTRAINT ){
 93577  93749       rc = SQLITE_ERROR;
 93578  93750       zErrDyn = sqlite3MPrintf(db, "database is already attached");
 93579  93751     }else if( rc==SQLITE_OK ){
 93580  93752       Pager *pPager;
 93581  93753       aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
 93582  93754       if( !aNew->pSchema ){
 93583         -      rc = SQLITE_NOMEM;
        93755  +      rc = SQLITE_NOMEM_BKPT;
 93584  93756       }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
 93585  93757         zErrDyn = sqlite3MPrintf(db, 
 93586  93758           "attached databases must use the same text encoding as main database");
 93587  93759         rc = SQLITE_ERROR;
 93588  93760       }
 93589  93761       sqlite3BtreeEnter(aNew->pBt);
 93590  93762       pPager = sqlite3BtreePager(aNew->pBt);
................................................................................
 93593  93765                                sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
 93594  93766   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 93595  93767       sqlite3BtreeSetPagerFlags(aNew->pBt,
 93596  93768                         PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
 93597  93769   #endif
 93598  93770       sqlite3BtreeLeave(aNew->pBt);
 93599  93771     }
 93600         -  aNew->safety_level = 3;
        93772  +  aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
 93601  93773     aNew->zName = sqlite3DbStrDup(db, zName);
 93602  93774     if( rc==SQLITE_OK && aNew->zName==0 ){
 93603         -    rc = SQLITE_NOMEM;
        93775  +    rc = SQLITE_NOMEM_BKPT;
 93604  93776     }
 93605  93777   
 93606  93778   
 93607  93779   #ifdef SQLITE_HAS_CODEC
 93608  93780     if( rc==SQLITE_OK ){
 93609  93781       extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
 93610  93782       extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
................................................................................
 93824  93996       1,                /* nArg */
 93825  93997       SQLITE_UTF8,      /* funcFlags */
 93826  93998       0,                /* pUserData */
 93827  93999       0,                /* pNext */
 93828  94000       detachFunc,       /* xSFunc */
 93829  94001       0,                /* xFinalize */
 93830  94002       "sqlite_detach",  /* zName */
 93831         -    0,                /* pHash */
 93832         -    0                 /* pDestructor */
        94003  +    {0}
 93833  94004     };
 93834  94005     codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
 93835  94006   }
 93836  94007   
 93837  94008   /*
 93838  94009   ** Called by the parser to compile an ATTACH statement.
 93839  94010   **
................................................................................
 93844  94015       3,                /* nArg */
 93845  94016       SQLITE_UTF8,      /* funcFlags */
 93846  94017       0,                /* pUserData */
 93847  94018       0,                /* pNext */
 93848  94019       attachFunc,       /* xSFunc */
 93849  94020       0,                /* xFinalize */
 93850  94021       "sqlite_attach",  /* zName */
 93851         -    0,                /* pHash */
 93852         -    0                 /* pDestructor */
        94022  +    {0}
 93853  94023     };
 93854  94024     codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
 93855  94025   }
 93856  94026   #endif /* SQLITE_OMIT_ATTACH */
 93857  94027   
 93858  94028   /*
 93859  94029   ** Initialize a DbFixer structure.  This routine must be called prior
................................................................................
 94852  95022     int i;
 94853  95023     Column *pCol;
 94854  95024     assert( pTable!=0 );
 94855  95025     if( (pCol = pTable->aCol)!=0 ){
 94856  95026       for(i=0; i<pTable->nCol; i++, pCol++){
 94857  95027         sqlite3DbFree(db, pCol->zName);
 94858  95028         sqlite3ExprDelete(db, pCol->pDflt);
 94859         -      sqlite3DbFree(db, pCol->zDflt);
 94860         -      sqlite3DbFree(db, pCol->zType);
 94861  95029         sqlite3DbFree(db, pCol->zColl);
 94862  95030       }
 94863  95031       sqlite3DbFree(db, pTable->aCol);
 94864  95032     }
 94865  95033   }
 94866  95034   
 94867  95035   /*
................................................................................
 94991  95159   ** function returns the index of the named database in db->aDb[], or
 94992  95160   ** -1 if the named db cannot be found.
 94993  95161   */
 94994  95162   SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
 94995  95163     int i = -1;         /* Database number */
 94996  95164     if( zName ){
 94997  95165       Db *pDb;
 94998         -    int n = sqlite3Strlen30(zName);
 94999  95166       for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
 95000         -      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
 95001         -          0==sqlite3StrICmp(pDb->zName, zName) ){
 95002         -        break;
 95003         -      }
        95167  +      if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
 95004  95168       }
 95005  95169     }
 95006  95170     return i;
 95007  95171   }
 95008  95172   
 95009  95173   /*
 95010  95174   ** The token *pName contains the name of a database (either "main" or
................................................................................
 95208  95372         goto begin_table_error;
 95209  95373       }
 95210  95374     }
 95211  95375   
 95212  95376     pTable = sqlite3DbMallocZero(db, sizeof(Table));
 95213  95377     if( pTable==0 ){
 95214  95378       assert( db->mallocFailed );
 95215         -    pParse->rc = SQLITE_NOMEM;
        95379  +    pParse->rc = SQLITE_NOMEM_BKPT;
 95216  95380       pParse->nErr++;
 95217  95381       goto begin_table_error;
 95218  95382     }
 95219  95383     pTable->zName = zName;
 95220  95384     pTable->iPKey = -1;
 95221  95385     pTable->pSchema = db->aDb[iDb].pSchema;
 95222  95386     pTable->nRef = 1;
................................................................................
 95324  95488   ** Add a new column to the table currently being constructed.
 95325  95489   **
 95326  95490   ** The parser calls this routine once for each column declaration
 95327  95491   ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
 95328  95492   ** first to get things going.  Then this routine is called for each
 95329  95493   ** column.
 95330  95494   */
 95331         -SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
        95495  +SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
 95332  95496     Table *p;
 95333  95497     int i;
 95334  95498     char *z;
        95499  +  char *zType;
 95335  95500     Column *pCol;
 95336  95501     sqlite3 *db = pParse->db;
 95337  95502     if( (p = pParse->pNewTable)==0 ) return;
 95338  95503   #if SQLITE_MAX_COLUMN
 95339  95504     if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 95340  95505       sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
 95341  95506       return;
 95342  95507     }
 95343  95508   #endif
 95344         -  z = sqlite3NameFromToken(db, pName);
        95509  +  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
 95345  95510     if( z==0 ) return;
        95511  +  memcpy(z, pName->z, pName->n);
        95512  +  z[pName->n] = 0;
        95513  +  sqlite3Dequote(z);
        95514  +  zType = z + sqlite3Strlen30(z) + 1;
        95515  +  memcpy(zType, pType->z, pType->n);
        95516  +  zType[pType->n] = 0;
 95346  95517     for(i=0; i<p->nCol; i++){
 95347  95518       if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
 95348  95519         sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
 95349  95520         sqlite3DbFree(db, z);
 95350  95521         return;
 95351  95522       }
 95352  95523     }
................................................................................
 95360  95531       p->aCol = aNew;
 95361  95532     }
 95362  95533     pCol = &p->aCol[p->nCol];
 95363  95534     memset(pCol, 0, sizeof(p->aCol[0]));
 95364  95535     pCol->zName = z;
 95365  95536     sqlite3ColumnPropertiesFromName(p, pCol);
 95366  95537    
 95367         -  /* If there is no type specified, columns have the default affinity
 95368         -  ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
 95369         -  ** be called next to set pCol->affinity correctly.
 95370         -  */
 95371         -  pCol->affinity = SQLITE_AFF_BLOB;
 95372         -  pCol->szEst = 1;
        95538  +  if( pType->n==0 ){
        95539  +    /* If there is no type specified, columns have the default affinity
        95540  +    ** 'BLOB'. */
        95541  +    pCol->affinity = SQLITE_AFF_BLOB;
        95542  +    pCol->szEst = 1;
        95543  +  }else{
        95544  +    pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
        95545  +  }
 95373  95546     p->nCol++;
        95547  +  pParse->constraintName.n = 0;
 95374  95548   }
 95375  95549   
 95376  95550   /*
 95377  95551   ** This routine is called by the parser while in the middle of
 95378  95552   ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
 95379  95553   ** been seen on a column.  This routine sets the notNull flag on
 95380  95554   ** the column currently under construction.
................................................................................
 95412  95586   ** SQLITE_AFF_NUMERIC is returned.
 95413  95587   */
 95414  95588   SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
 95415  95589     u32 h = 0;
 95416  95590     char aff = SQLITE_AFF_NUMERIC;
 95417  95591     const char *zChar = 0;
 95418  95592   
 95419         -  if( zIn==0 ) return aff;
        95593  +  assert( zIn!=0 );
 95420  95594     while( zIn[0] ){
 95421  95595       h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
 95422  95596       zIn++;
 95423  95597       if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
 95424  95598         aff = SQLITE_AFF_TEXT;
 95425  95599         zChar = zIn;
 95426  95600       }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
................................................................................
 95469  95643           *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
 95470  95644         }
 95471  95645       }
 95472  95646     }
 95473  95647     return aff;
 95474  95648   }
 95475  95649   
 95476         -/*
 95477         -** This routine is called by the parser while in the middle of
 95478         -** parsing a CREATE TABLE statement.  The pFirst token is the first
 95479         -** token in the sequence of tokens that describe the type of the
 95480         -** column currently under construction.   pLast is the last token
 95481         -** in the sequence.  Use this information to construct a string
 95482         -** that contains the typename of the column and store that string
 95483         -** in zType.
 95484         -*/ 
 95485         -SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
 95486         -  Table *p;
 95487         -  Column *pCol;
 95488         -
 95489         -  p = pParse->pNewTable;
 95490         -  if( p==0 || NEVER(p->nCol<1) ) return;
 95491         -  pCol = &p->aCol[p->nCol-1];
 95492         -  assert( pCol->zType==0 || CORRUPT_DB );
 95493         -  sqlite3DbFree(pParse->db, pCol->zType);
 95494         -  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
 95495         -  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
 95496         -}
 95497         -
 95498  95650   /*
 95499  95651   ** The expression is the default value for the most recently added column
 95500  95652   ** of the table currently under construction.
 95501  95653   **
 95502  95654   ** Default value expressions must be constant.  Raise an exception if this
 95503  95655   ** is not the case.
 95504  95656   **
................................................................................
 95516  95668         sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
 95517  95669             pCol->zName);
 95518  95670       }else{
 95519  95671         /* A copy of pExpr is used instead of the original, as pExpr contains
 95520  95672         ** tokens that point to volatile memory. The 'span' of the expression
 95521  95673         ** is required by pragma table_info.
 95522  95674         */
        95675  +      Expr x;
 95523  95676         sqlite3ExprDelete(db, pCol->pDflt);
 95524         -      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
 95525         -      sqlite3DbFree(db, pCol->zDflt);
 95526         -      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
 95527         -                                     (int)(pSpan->zEnd - pSpan->zStart));
        95677  +      memset(&x, 0, sizeof(x));
        95678  +      x.op = TK_SPAN;
        95679  +      x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
        95680  +                                    (int)(pSpan->zEnd - pSpan->zStart));
        95681  +      x.pLeft = pSpan->pExpr;
        95682  +      x.flags = EP_Skip;
        95683  +      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
        95684  +      sqlite3DbFree(db, x.u.zToken);
 95528  95685       }
 95529  95686     }
 95530  95687     sqlite3ExprDelete(db, pSpan->pExpr);
 95531  95688   }
 95532  95689   
 95533  95690   /*
 95534  95691   ** Backwards Compatibility Hack:
................................................................................
 95576  95733     Parse *pParse,    /* Parsing context */
 95577  95734     ExprList *pList,  /* List of field names to be indexed */
 95578  95735     int onError,      /* What to do with a uniqueness conflict */
 95579  95736     int autoInc,      /* True if the AUTOINCREMENT keyword is present */
 95580  95737     int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
 95581  95738   ){
 95582  95739     Table *pTab = pParse->pNewTable;
 95583         -  char *zType = 0;
        95740  +  const char *zName = 0;
 95584  95741     int iCol = -1, i;
 95585  95742     int nTerm;
 95586  95743     if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
 95587  95744     if( pTab->tabFlags & TF_HasPrimaryKey ){
 95588  95745       sqlite3ErrorMsg(pParse, 
 95589  95746         "table \"%s\" has more than one primary key", pTab->zName);
 95590  95747       goto primary_key_exit;
 95591  95748     }
 95592  95749     pTab->tabFlags |= TF_HasPrimaryKey;
 95593  95750     if( pList==0 ){
 95594  95751       iCol = pTab->nCol - 1;
 95595  95752       pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
 95596         -    zType = pTab->aCol[iCol].zType;
        95753  +    zName = pTab->aCol[iCol].zName;
 95597  95754       nTerm = 1;
 95598  95755     }else{
 95599  95756       nTerm = pList->nExpr;
 95600  95757       for(i=0; i<nTerm; i++){
 95601  95758         Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
 95602  95759         assert( pCExpr!=0 );
 95603  95760         sqlite3StringToId(pCExpr);
 95604  95761         if( pCExpr->op==TK_ID ){
 95605  95762           const char *zCName = pCExpr->u.zToken;
 95606  95763           for(iCol=0; iCol<pTab->nCol; iCol++){
 95607  95764             if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
 95608  95765               pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
 95609         -            zType = pTab->aCol[iCol].zType;
        95766  +            zName = pTab->aCol[iCol].zName;
 95610  95767               break;
 95611  95768             }
 95612  95769           }
 95613  95770         }
 95614  95771       }
 95615  95772     }
 95616  95773     if( nTerm==1
 95617         -   && zType && sqlite3StrICmp(zType, "INTEGER")==0
        95774  +   && zName
        95775  +   && sqlite3StrICmp(sqlite3StrNext(zName), "INTEGER")==0
 95618  95776      && sortOrder!=SQLITE_SO_DESC
 95619  95777     ){
 95620  95778       pTab->iPKey = iCol;
 95621  95779       pTab->keyConf = (u8)onError;
 95622  95780       assert( autoInc==0 || autoInc==1 );
 95623  95781       pTab->tabFlags |= autoInc*TF_Autoincrement;
 95624  95782       if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
................................................................................
 95889  96047   static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
 95890  96048     char *zExtra;
 95891  96049     int nByte;
 95892  96050     if( pIdx->nColumn>=N ) return SQLITE_OK;
 95893  96051     assert( pIdx->isResized==0 );
 95894  96052     nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
 95895  96053     zExtra = sqlite3DbMallocZero(db, nByte);
 95896         -  if( zExtra==0 ) return SQLITE_NOMEM;
        96054  +  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
 95897  96055     memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
 95898  96056     pIdx->azColl = (const char**)zExtra;
 95899  96057     zExtra += sizeof(char*)*N;
 95900  96058     memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
 95901  96059     pIdx->aiColumn = (i16*)zExtra;
 95902  96060     zExtra += sizeof(i16)*N;
 95903  96061     memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
................................................................................
 97480  97638       assert( i==pIndex->nColumn );
 97481  97639     }else{
 97482  97640       pIndex->aiColumn[i] = XN_ROWID;
 97483  97641       pIndex->azColl[i] = sqlite3StrBINARY;
 97484  97642     }
 97485  97643     sqlite3DefaultRowEst(pIndex);
 97486  97644     if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
        97645  +
        97646  +  /* If this index contains every column of its table, then mark
        97647  +  ** it as a covering index */
        97648  +  assert( HasRowid(pTab) 
        97649  +      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
        97650  +  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
        97651  +    pIndex->isCovering = 1;
        97652  +    for(j=0; j<pTab->nCol; j++){
        97653  +      if( j==pTab->iPKey ) continue;
        97654  +      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
        97655  +      pIndex->isCovering = 0;
        97656  +      break;
        97657  +    }
        97658  +  }
 97487  97659   
 97488  97660     if( pTab==pParse->pNewTable ){
 97489  97661       /* This routine has been called to create an automatic index as a
 97490  97662       ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
 97491  97663       ** a PRIMARY KEY or UNIQUE clause following the column definitions.
 97492  97664       ** i.e. one of:
 97493  97665       **
................................................................................
 97518  97690         for(k=0; k<pIdx->nKeyCol; k++){
 97519  97691           const char *z1;
 97520  97692           const char *z2;
 97521  97693           assert( pIdx->aiColumn[k]>=0 );
 97522  97694           if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
 97523  97695           z1 = pIdx->azColl[k];
 97524  97696           z2 = pIndex->azColl[k];
 97525         -        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
        97697  +        if( sqlite3StrICmp(z1, z2) ) break;
 97526  97698         }
 97527  97699         if( k==pIdx->nKeyCol ){
 97528  97700           if( pIdx->onError!=pIndex->onError ){
 97529  97701             /* This constraint creates the same index as a previous
 97530  97702             ** constraint specified somewhere in the CREATE TABLE statement.
 97531  97703             ** However the ON CONFLICT clauses are different. If both this 
 97532  97704             ** constraint and the previous equivalent constraint have explicit
................................................................................
 98971  99143   }
 98972  99144   
 98973  99145   /*
 98974  99146   ** Search a FuncDefHash for a function with the given name.  Return
 98975  99147   ** a pointer to the matching FuncDef if found, or 0 if there is no match.
 98976  99148   */
 98977  99149   static FuncDef *functionSearch(
 98978         -  FuncDefHash *pHash,  /* Hash table to search */
 98979  99150     int h,               /* Hash of the name */
 98980         -  const char *zFunc,   /* Name of function */
 98981         -  int nFunc            /* Number of bytes in zFunc */
        99151  +  const char *zFunc    /* Name of function */
 98982  99152   ){
 98983  99153     FuncDef *p;
 98984         -  for(p=pHash->a[h]; p; p=p->pHash){
 98985         -    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
        99154  +  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
        99155  +    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
 98986  99156         return p;
 98987  99157       }
 98988  99158     }
 98989  99159     return 0;
 98990  99160   }
 98991  99161   
 98992  99162   /*
 98993  99163   ** Insert a new FuncDef into a FuncDefHash hash table.
 98994  99164   */
 98995         -SQLITE_PRIVATE void sqlite3FuncDefInsert(
 98996         -  FuncDefHash *pHash,  /* The hash table into which to insert */
 98997         -  FuncDef *pDef        /* The function definition to insert */
        99165  +SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
        99166  +  FuncDef *aDef,      /* List of global functions to be inserted */
        99167  +  int nDef            /* Length of the apDef[] list */
 98998  99168   ){
 98999         -  FuncDef *pOther;
 99000         -  int nName = sqlite3Strlen30(pDef->zName);
 99001         -  u8 c1 = (u8)pDef->zName[0];
 99002         -  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
 99003         -  pOther = functionSearch(pHash, h, pDef->zName, nName);
 99004         -  if( pOther ){
 99005         -    assert( pOther!=pDef && pOther->pNext!=pDef );
 99006         -    pDef->pNext = pOther->pNext;
 99007         -    pOther->pNext = pDef;
 99008         -  }else{
 99009         -    pDef->pNext = 0;
 99010         -    pDef->pHash = pHash->a[h];
 99011         -    pHash->a[h] = pDef;
        99169  +  int i;
        99170  +  for(i=0; i<nDef; i++){
        99171  +    FuncDef *pOther;
        99172  +    const char *zName = aDef[i].zName;
        99173  +    int nName = sqlite3Strlen30(zName);
        99174  +    int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
        99175  +    pOther = functionSearch(h, zName);
        99176  +    if( pOther ){
        99177  +      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
        99178  +      aDef[i].pNext = pOther->pNext;
        99179  +      pOther->pNext = &aDef[i];
        99180  +    }else{
        99181  +      aDef[i].pNext = 0;
        99182  +      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
        99183  +      sqlite3BuiltinFunctions.a[h] = &aDef[i];
        99184  +    }
 99012  99185     }
 99013  99186   }
 99014  99187     
 99015  99188     
 99016  99189   
 99017  99190   /*
 99018  99191   ** Locate a user function given a name, a number of arguments and a flag
................................................................................
 99031  99204   **
 99032  99205   ** If createFlag is false, then a function with the required name and
 99033  99206   ** number of arguments may be returned even if the eTextRep flag does not
 99034  99207   ** match that requested.
 99035  99208   */
 99036  99209   SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
 99037  99210     sqlite3 *db,       /* An open database */
 99038         -  const char *zName, /* Name of the function.  Not null-terminated */
 99039         -  int nName,         /* Number of characters in the name */
        99211  +  const char *zName, /* Name of the function.  zero-terminated */
 99040  99212     int nArg,          /* Number of arguments.  -1 means any number */
 99041  99213     u8 enc,            /* Preferred text encoding */
 99042  99214     u8 createFlag      /* Create new entry if true and does not otherwise exist */
 99043  99215   ){
 99044  99216     FuncDef *p;         /* Iterator variable */
 99045  99217     FuncDef *pBest = 0; /* Best match found so far */
 99046  99218     int bestScore = 0;  /* Score of best match */
 99047  99219     int h;              /* Hash value */
        99220  +  int nName;          /* Length of the name */
 99048  99221   
 99049  99222     assert( nArg>=(-2) );
 99050  99223     assert( nArg>=(-1) || createFlag==0 );
 99051         -  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
        99224  +  nName = sqlite3Strlen30(zName);
 99052  99225   
 99053  99226     /* First search for a match amongst the application-defined functions.
 99054  99227     */
 99055         -  p = functionSearch(&db->aFunc, h, zName, nName);
        99228  +  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
 99056  99229     while( p ){
 99057  99230       int score = matchQuality(p, nArg, enc);
 99058  99231       if( score>bestScore ){
 99059  99232         pBest = p;
 99060  99233         bestScore = score;
 99061  99234       }
 99062  99235       p = p->pNext;
................................................................................
 99071  99244     ** Except, if createFlag is true, that means that we are trying to
 99072  99245     ** install a new function.  Whatever FuncDef structure is returned it will
 99073  99246     ** have fields overwritten with new information appropriate for the
 99074  99247     ** new function.  But the FuncDefs for built-in functions are read-only.
 99075  99248     ** So we must not search for built-ins when creating a new function.
 99076  99249     */ 
 99077  99250     if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
 99078         -    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 99079  99251       bestScore = 0;
 99080         -    p = functionSearch(pHash, h, zName, nName);
        99252  +    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
        99253  +    p = functionSearch(h, zName);
 99081  99254       while( p ){
 99082  99255         int score = matchQuality(p, nArg, enc);
 99083  99256         if( score>bestScore ){
 99084  99257           pBest = p;
 99085  99258           bestScore = score;
 99086  99259         }
 99087  99260         p = p->pNext;
................................................................................
 99090  99263   
 99091  99264     /* If the createFlag parameter is true and the search did not reveal an
 99092  99265     ** exact match for the name, number of arguments and encoding, then add a
 99093  99266     ** new entry to the hash table and return it.
 99094  99267     */
 99095  99268     if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
 99096  99269         (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
 99097         -    pBest->zName = (char *)&pBest[1];
        99270  +    FuncDef *pOther;
        99271  +    pBest->zName = (const char*)&pBest[1];
 99098  99272       pBest->nArg = (u16)nArg;
 99099  99273       pBest->funcFlags = enc;
 99100         -    memcpy(pBest->zName, zName, nName);
 99101         -    pBest->zName[nName] = 0;
 99102         -    sqlite3FuncDefInsert(&db->aFunc, pBest);
        99274  +    memcpy((char*)&pBest[1], zName, nName+1);
        99275  +    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
        99276  +    if( pOther==pBest ){
        99277  +      sqlite3DbFree(db, pBest);
        99278  +      sqlite3OomFault(db);
        99279  +      return 0;
        99280  +    }else{
        99281  +      pBest->pNext = pOther;
        99282  +    }
 99103  99283     }
 99104  99284   
 99105  99285     if( pBest && (pBest->xSFunc || createFlag) ){
 99106  99286       return pBest;
 99107  99287     }
 99108  99288     return 0;
 99109  99289   }
................................................................................
101679 101859   }
101680 101860   
101681 101861   /*
101682 101862   ** This routine does per-connection function registration.  Most
101683 101863   ** of the built-in functions above are part of the global function set.
101684 101864   ** This routine only deals with those that are not global.
101685 101865   */
101686         -SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
       101866  +SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
101687 101867     int rc = sqlite3_overload_function(db, "MATCH", 2);
101688 101868     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
101689 101869     if( rc==SQLITE_NOMEM ){
101690 101870       sqlite3OomFault(db);
101691 101871     }
101692 101872   }
101693 101873   
101694 101874   /*
101695 101875   ** Set the LIKEOPT flag on the 2-argument function with the given name.
101696 101876   */
101697 101877   static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
101698 101878     FuncDef *pDef;
101699         -  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
101700         -                             2, SQLITE_UTF8, 0);
       101879  +  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
101701 101880     if( ALWAYS(pDef) ){
101702 101881       pDef->funcFlags |= flagVal;
101703 101882     }
101704 101883   }
101705 101884   
101706 101885   /*
101707 101886   ** Register the built-in LIKE and GLOB functions.  The caseSensitive
................................................................................
101741 101920     if( pExpr->op!=TK_FUNCTION 
101742 101921      || !pExpr->x.pList 
101743 101922      || pExpr->x.pList->nExpr!=2
101744 101923     ){
101745 101924       return 0;
101746 101925     }
101747 101926     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
101748         -  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
101749         -                             sqlite3Strlen30(pExpr->u.zToken),
101750         -                             2, SQLITE_UTF8, 0);
       101927  +  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
101751 101928     if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
101752 101929       return 0;
101753 101930     }
101754 101931   
101755 101932     /* The memcpy() statement assumes that the wildcard characters are
101756 101933     ** the first three statements in the compareInfo structure.  The
101757 101934     ** asserts() that follow verify that assumption
................................................................................
101767 101944   /*
101768 101945   ** All of the FuncDef structures in the aBuiltinFunc[] array above
101769 101946   ** to the global function hash table.  This occurs at start-time (as
101770 101947   ** a consequence of calling sqlite3_initialize()).
101771 101948   **
101772 101949   ** After this routine runs
101773 101950   */
101774         -SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
       101951  +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
101775 101952     /*
101776 101953     ** The following array holds FuncDef structures for all of the functions
101777 101954     ** defined in this file.
101778 101955     **
101779 101956     ** The array cannot be constant since changes are made to the
101780 101957     ** FuncDef.pHash elements at start-time.  The elements of this array
101781 101958     ** are read-only after initialization is complete.
       101959  +  **
       101960  +  ** For peak efficiency, put the most frequently used function last.
101782 101961     */
101783         -  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
       101962  +  static FuncDef aBuiltinFunc[] = {
       101963  +#ifdef SQLITE_SOUNDEX
       101964  +    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
       101965  +#endif
       101966  +#ifndef SQLITE_OMIT_LOAD_EXTENSION
       101967  +    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
       101968  +    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
       101969  +#endif
       101970  +#if SQLITE_USER_AUTHENTICATION
       101971  +    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
       101972  +#endif
       101973  +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
       101974  +    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
       101975  +    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
       101976  +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
       101977  +    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
       101978  +    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
       101979  +    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
101784 101980       FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
101785 101981       FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
101786 101982       FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
101787 101983       FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
101788 101984       FUNCTION(trim,               1, 3, 0, trimFunc         ),
101789 101985       FUNCTION(trim,               2, 3, 0, trimFunc         ),
101790 101986       FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
................................................................................
101794 101990       FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
101795 101991       FUNCTION(max,                0, 1, 1, 0                ),
101796 101992       AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
101797 101993                                             SQLITE_FUNC_MINMAX ),
101798 101994       FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
101799 101995       FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
101800 101996       FUNCTION(instr,              2, 0, 0, instrFunc        ),
101801         -    FUNCTION(substr,             2, 0, 0, substrFunc       ),
101802         -    FUNCTION(substr,             3, 0, 0, substrFunc       ),
101803 101997       FUNCTION(printf,            -1, 0, 0, printfFunc       ),
101804 101998       FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
101805 101999       FUNCTION(char,              -1, 0, 0, charFunc         ),
101806 102000       FUNCTION(abs,                1, 0, 0, absFunc          ),
101807 102001   #ifndef SQLITE_OMIT_FLOATING_POINT
101808 102002       FUNCTION(round,              1, 0, 0, roundFunc        ),
101809 102003       FUNCTION(round,              2, 0, 0, roundFunc        ),
101810 102004   #endif
101811 102005       FUNCTION(upper,              1, 0, 0, upperFunc        ),
101812 102006       FUNCTION(lower,              1, 0, 0, lowerFunc        ),
101813         -    FUNCTION(coalesce,           1, 0, 0, 0                ),
101814         -    FUNCTION(coalesce,           0, 0, 0, 0                ),
101815         -    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
101816 102007       FUNCTION(hex,                1, 0, 0, hexFunc          ),
101817 102008       FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
101818         -    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
101819         -    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
101820         -    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
101821 102009       VFUNCTION(random,            0, 0, 0, randomFunc       ),
101822 102010       VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
101823 102011       FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
101824 102012       DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
101825 102013       DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
101826 102014       FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
101827         -#if SQLITE_USER_AUTHENTICATION
101828         -    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
101829         -#endif
101830         -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
101831         -    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
101832         -    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
101833         -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
101834 102015       FUNCTION(quote,              1, 0, 0, quoteFunc        ),
101835 102016       VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
101836 102017       VFUNCTION(changes,           0, 0, 0, changes          ),
101837 102018       VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
101838 102019       FUNCTION(replace,            3, 0, 0, replaceFunc      ),
101839 102020       FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
101840         -  #ifdef SQLITE_SOUNDEX
101841         -    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
101842         -  #endif
101843         -  #ifndef SQLITE_OMIT_LOAD_EXTENSION
101844         -    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
101845         -    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
101846         -  #endif
       102021  +    FUNCTION(substr,             2, 0, 0, substrFunc       ),
       102022  +    FUNCTION(substr,             3, 0, 0, substrFunc       ),
101847 102023       AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
101848 102024       AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
101849 102025       AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
101850 102026       AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
101851 102027                  SQLITE_FUNC_COUNT  ),
101852 102028       AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
101853 102029       AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
................................................................................
101857 102033     #ifdef SQLITE_CASE_SENSITIVE_LIKE
101858 102034       LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
101859 102035       LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
101860 102036     #else
101861 102037       LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
101862 102038       LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
101863 102039     #endif
       102040  +    FUNCTION(coalesce,           1, 0, 0, 0                ),
       102041  +    FUNCTION(coalesce,           0, 0, 0, 0                ),
       102042  +    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
101864 102043     };
101865         -
101866         -  int i;
101867         -  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
101868         -  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
101869         -
101870         -  for(i=0; i<ArraySize(aBuiltinFunc); i++){
101871         -    sqlite3FuncDefInsert(pHash, &aFunc[i]);
101872         -  }
101873         -  sqlite3RegisterDateTimeFunctions();
101874 102044   #ifndef SQLITE_OMIT_ALTERTABLE
101875 102045     sqlite3AlterFunctions();
101876 102046   #endif
101877 102047   #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
101878 102048     sqlite3AnalyzeFunctions();
       102049  +#endif
       102050  +  sqlite3RegisterDateTimeFunctions();
       102051  +  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
       102052  +
       102053  +#if 0  /* Enable to print out how the built-in functions are hashed */
       102054  +  {
       102055  +    int i;
       102056  +    FuncDef *p;
       102057  +    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
       102058  +      printf("FUNC-HASH %02d:", i);
       102059  +      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
       102060  +        int n = sqlite3Strlen30(p->zName);
       102061  +        int h = p->zName[0] + n;
       102062  +        printf(" %s(%d)", p->zName, h);
       102063  +      }
       102064  +      printf("\n");
       102065  +    }
       102066  +  }
101879 102067   #endif
101880 102068   }
101881 102069   
101882 102070   /************** End of func.c ************************************************/
101883 102071   /************** Begin file fkey.c ********************************************/
101884 102072   /*
101885 102073   **
................................................................................
103041 103229   ){
103042 103230     sqlite3 *db = pParse->db;       /* Database handle */
103043 103231     int action;                     /* One of OE_None, OE_Cascade etc. */
103044 103232     Trigger *pTrigger;              /* Trigger definition to return */
103045 103233     int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
103046 103234   
103047 103235     action = pFKey->aAction[iAction];
       103236  +  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
       103237  +    return 0;
       103238  +  }
       103239  +
103048 103240     pTrigger = pFKey->apTrigger[iAction];
103049 103241   
103050 103242     if( action!=OE_None && !pTrigger ){
103051 103243       char const *zFrom;            /* Name of child table */
103052 103244       int nFrom;                    /* Length in bytes of zFrom */
103053 103245       Index *pIdx = 0;              /* Parent key index for this FK */
103054 103246       int *aiCol = 0;               /* child table cols -> parent key cols */
................................................................................
105285 105477       if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
105286 105478         return 0;    /* Collating sequence must be the same on all columns */
105287 105479       }
105288 105480       if( pDestCol->notNull && !pSrcCol->notNull ){
105289 105481         return 0;    /* tab2 must be NOT NULL if tab1 is */
105290 105482       }
105291 105483       /* Default values for second and subsequent columns need to match. */
105292         -    if( i>0
105293         -     && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 
105294         -         || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
105295         -    ){
105296         -      return 0;    /* Default values must be the same for all columns */
       105484  +    if( i>0 ){
       105485  +      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
       105486  +      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
       105487  +      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
       105488  +       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
       105489  +                                       pSrcCol->pDflt->u.zToken)!=0)
       105490  +      ){
       105491  +        return 0;    /* Default values must be the same for all columns */
       105492  +      }
105297 105493       }
105298 105494     }
105299 105495     for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
105300 105496       if( IsUniqueIndex(pDestIdx) ){
105301 105497         destHasUniqueIdx = 1;
105302 105498       }
105303 105499       for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
................................................................................
105594 105790     rc = sqlite3ApiExit(db, rc);
105595 105791     if( rc!=SQLITE_OK && pzErrMsg ){
105596 105792       int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
105597 105793       *pzErrMsg = sqlite3Malloc(nErrMsg);
105598 105794       if( *pzErrMsg ){
105599 105795         memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
105600 105796       }else{
105601         -      rc = SQLITE_NOMEM;
       105797  +      rc = SQLITE_NOMEM_BKPT;
105602 105798         sqlite3Error(db, SQLITE_NOMEM);
105603 105799       }
105604 105800     }else if( pzErrMsg ){
105605 105801       *pzErrMsg = 0;
105606 105802     }
105607 105803   
105608 105804     assert( (rc&db->errMask)==rc );
................................................................................
105909 106105     /* Version 3.9.0 and later */
105910 106106     unsigned int (*value_subtype)(sqlite3_value*);
105911 106107     void (*result_subtype)(sqlite3_context*,unsigned int);
105912 106108     /* Version 3.10.0 and later */
105913 106109     int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
105914 106110     int (*strlike)(const char*,const char*,unsigned int);
105915 106111     int (*db_cacheflush)(sqlite3*);
       106112  +  /* Version 3.12.0 and later */
       106113  +  int (*system_errno)(sqlite3*);
105916 106114   };
105917 106115   
105918 106116   /*
105919 106117   ** The following macros redefine the API routines so that they are
105920 106118   ** redirected through the global sqlite3_api structure.
105921 106119   **
105922 106120   ** This header file is also used by the loadext.c source file
................................................................................
106152 106350   /* Version 3.9.0 and later */
106153 106351   #define sqlite3_value_subtype          sqlite3_api->value_subtype
106154 106352   #define sqlite3_result_subtype         sqlite3_api->result_subtype
106155 106353   /* Version 3.10.0 and later */
106156 106354   #define sqlite3_status64               sqlite3_api->status64
106157 106355   #define sqlite3_strlike                sqlite3_api->strlike
106158 106356   #define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
       106357  +/* Version 3.12.0 and later */
       106358  +#define sqlite3_system_errno           sqlite3_api->system_errno
106159 106359   #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
106160 106360   
106161 106361   #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
106162 106362     /* This case when the file really is being compiled as a loadable 
106163 106363     ** extension */
106164 106364   # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
106165 106365   # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
................................................................................
106570 106770     sqlite3_bind_zeroblob64,
106571 106771     /* Version 3.9.0 and later */
106572 106772     sqlite3_value_subtype,
106573 106773     sqlite3_result_subtype,
106574 106774     /* Version 3.10.0 and later */
106575 106775     sqlite3_status64,
106576 106776     sqlite3_strlike,
106577         -  sqlite3_db_cacheflush
       106777  +  sqlite3_db_cacheflush,
       106778  +  /* Version 3.12.0 and later */
       106779  +  sqlite3_system_errno
106578 106780   };
106579 106781   
106580 106782   /*
106581 106783   ** Attempt to load an SQLite extension library contained in the file
106582 106784   ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
106583 106785   ** default entry point name (sqlite3_extension_init) is used.  Use
106584 106786   ** of the default name is recommended.
................................................................................
106634 106836   
106635 106837     zEntry = zProc ? zProc : "sqlite3_extension_init";
106636 106838   
106637 106839     handle = sqlite3OsDlOpen(pVfs, zFile);
106638 106840   #if SQLITE_OS_UNIX || SQLITE_OS_WIN
106639 106841     for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
106640 106842       char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
106641         -    if( zAltFile==0 ) return SQLITE_NOMEM;
       106843  +    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
106642 106844       handle = sqlite3OsDlOpen(pVfs, zAltFile);
106643 106845       sqlite3_free(zAltFile);
106644 106846     }
106645 106847   #endif
106646 106848     if( handle==0 ){
106647 106849       if( pzErrMsg ){
106648 106850         *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
................................................................................
106670 106872     */
106671 106873     if( xInit==0 && zProc==0 ){
106672 106874       int iFile, iEntry, c;
106673 106875       int ncFile = sqlite3Strlen30(zFile);
106674 106876       zAltEntry = sqlite3_malloc64(ncFile+30);
106675 106877       if( zAltEntry==0 ){
106676 106878         sqlite3OsDlClose(pVfs, handle);
106677         -      return SQLITE_NOMEM;
       106879  +      return SQLITE_NOMEM_BKPT;
106678 106880       }
106679 106881       memcpy(zAltEntry, "sqlite3_", 8);
106680 106882       for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
106681 106883       iFile++;
106682 106884       if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
106683 106885       for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
106684 106886         if( sqlite3Isalpha(c) ){
................................................................................
106713 106915       sqlite3OsDlClose(pVfs, handle);
106714 106916       return SQLITE_ERROR;
106715 106917     }
106716 106918   
106717 106919     /* Append the new shared library handle to the db->aExtension array. */
106718 106920     aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
106719 106921     if( aHandle==0 ){
106720         -    return SQLITE_NOMEM;
       106922  +    return SQLITE_NOMEM_BKPT;
106721 106923     }
106722 106924     if( db->nExtension>0 ){
106723 106925       memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
106724 106926     }
106725 106927     sqlite3DbFree(db, db->aExtension);
106726 106928     db->aExtension = aHandle;
106727 106929   
................................................................................
106835 107037         if( wsdAutoext.aExt[i]==xInit ) break;
106836 107038       }
106837 107039       if( i==wsdAutoext.nExt ){
106838 107040         u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
106839 107041         void (**aNew)(void);
106840 107042         aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
106841 107043         if( aNew==0 ){
106842         -        rc = SQLITE_NOMEM;
       107044  +        rc = SQLITE_NOMEM_BKPT;
106843 107045         }else{
106844 107046           wsdAutoext.aExt = aNew;
106845 107047           wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
106846 107048           wsdAutoext.nExt++;
106847 107049         }
106848 107050       }
106849 107051       sqlite3_mutex_leave(mutex);
................................................................................
108402 108604         if( !db->autoCommit ){
108403 108605           sqlite3ErrorMsg(pParse, 
108404 108606               "Safety level may not be changed inside a transaction");
108405 108607         }else{
108406 108608           int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
108407 108609           if( iLevel==0 ) iLevel = 1;
108408 108610           pDb->safety_level = iLevel;
       108611  +        pDb->bSyncSet = 1;
108409 108612           setAllPagerFlags(db);
108410 108613         }
108411 108614       }
108412 108615       break;
108413 108616     }
108414 108617   #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
108415 108618   
................................................................................
108474 108677         Column *pCol;
108475 108678         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
108476 108679         pParse->nMem = 6;
108477 108680         sqlite3CodeVerifySchema(pParse, iDb);
108478 108681         setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
108479 108682         sqlite3ViewGetColumnNames(pParse, pTab);
108480 108683         for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
       108684  +        const char *zName;
108481 108685           if( IsHiddenColumn(pCol) ){
108482 108686             nHidden++;
108483 108687             continue;
108484 108688           }
108485 108689           if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
108486 108690             k = 0;
108487 108691           }else if( pPk==0 ){
108488 108692             k = 1;
108489 108693           }else{
108490 108694             for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
108491 108695           }
       108696  +        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
       108697  +        zName = pCol->zName;
108492 108698           sqlite3VdbeMultiLoad(v, 1, "issisi",
108493 108699                  i-nHidden,
108494         -               pCol->zName,
108495         -               pCol->zType ? pCol->zType : "",
       108700  +               zName,
       108701  +               sqlite3StrNext(zName),
108496 108702                  pCol->notNull ? 1 : 0,
108497         -               pCol->zDflt,
       108703  +               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
108498 108704                  k);
108499 108705           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
108500 108706         }
108501 108707       }
108502 108708     }
108503 108709     break;
108504 108710   
................................................................................
108511 108717       sqlite3CodeVerifySchema(pParse, iDb);
108512 108718       setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
108513 108719       for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
108514 108720         Table *pTab = sqliteHashData(i);
108515 108721         sqlite3VdbeMultiLoad(v, 1, "ssii",
108516 108722              pTab->zName,
108517 108723              0,
108518         -           (int)sqlite3LogEstToInt(pTab->szTabRow),
108519         -           (int)sqlite3LogEstToInt(pTab->nRowLogEst));
       108724  +           pTab->szTabRow,
       108725  +           pTab->nRowLogEst);
108520 108726         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
108521 108727         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
108522 108728           sqlite3VdbeMultiLoad(v, 2, "sii",
108523 108729              pIdx->zName,
108524         -           (int)sqlite3LogEstToInt(pIdx->szIdxRow),
108525         -           (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]));
       108730  +           pIdx->szIdxRow,
       108731  +           pIdx->aiRowLogEst[0]);
108526 108732           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
108527 108733         }
108528 108734       }
108529 108735     }
108530 108736     break;
108531 108737   
108532 108738     case PragTyp_INDEX_INFO: if( zRight ){
................................................................................
108844 109050       }
108845 109051       sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
108846 109052   
108847 109053       /* Do an integrity check on each database file */
108848 109054       for(i=0; i<db->nDb; i++){
108849 109055         HashElem *x;
108850 109056         Hash *pTbls;
       109057  +      int *aRoot;
108851 109058         int cnt = 0;
       109059  +      int mxIdx = 0;
       109060  +      int nIdx;
108852 109061   
108853 109062         if( OMIT_TEMPDB && i==1 ) continue;
108854 109063         if( iDb>=0 && i!=iDb ) continue;
108855 109064   
108856 109065         sqlite3CodeVerifySchema(pParse, i);
108857 109066         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
108858 109067         VdbeCoverage(v);
108859 109068         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
108860 109069         sqlite3VdbeJumpHere(v, addr);
108861 109070   
108862 109071         /* Do an integrity check of the B-Tree
108863 109072         **
108864         -      ** Begin by filling registers 2, 3, ... with the root pages numbers
       109073  +      ** Begin by finding the root pages numbers
108865 109074         ** for all tables and indices in the database.
108866 109075         */
108867 109076         assert( sqlite3SchemaMutexHeld(db, i, 0) );
108868 109077         pTbls = &db->aDb[i].pSchema->tblHash;
108869         -      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
       109078  +      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
       109079  +        Table *pTab = sqliteHashData(x);
       109080  +        Index *pIdx;
       109081  +        if( HasRowid(pTab) ) cnt++;
       109082  +        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
       109083  +        if( nIdx>mxIdx ) mxIdx = nIdx;
       109084  +      }
       109085  +      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
       109086  +      if( aRoot==0 ) break;
       109087  +      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
108870 109088           Table *pTab = sqliteHashData(x);
108871 109089           Index *pIdx;
108872         -        if( HasRowid(pTab) ){
108873         -          sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
108874         -          VdbeComment((v, "%s", pTab->zName));
108875         -          cnt++;
108876         -        }
       109090  +        if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
108877 109091           for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
108878         -          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
108879         -          VdbeComment((v, "%s", pIdx->zName));
108880         -          cnt++;
       109092  +          aRoot[cnt++] = pIdx->tnum;
108881 109093           }
108882 109094         }
       109095  +      aRoot[cnt] = 0;
108883 109096   
108884 109097         /* Make sure sufficient number of registers have been allocated */
108885         -      pParse->nMem = MAX( pParse->nMem, cnt+8 );
       109098  +      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
108886 109099   
108887 109100         /* Do the b-tree integrity checks */
108888         -      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
       109101  +      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
108889 109102         sqlite3VdbeChangeP5(v, (u8)i);
108890 109103         addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
108891 109104         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
108892 109105            sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
108893 109106            P4_DYNAMIC);
108894 109107         sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
108895 109108         sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
................................................................................
108915 109128           sqlite3ExprCacheClear(pParse);
108916 109129           sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
108917 109130                                      1, 0, &iDataCur, &iIdxCur);
108918 109131           sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
108919 109132           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
108920 109133             sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
108921 109134           }
108922         -        pParse->nMem = MAX(pParse->nMem, 8+j);
       109135  +        assert( pParse->nMem>=8+j );
       109136  +        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
108923 109137           sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
108924 109138           loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
108925 109139           /* Verify that all NOT NULL columns really are NOT NULL */
108926 109140           for(j=0; j<pTab->nCol; j++){
108927 109141             char *zErr;
108928 109142             int jmp2, jmp3;
108929 109143             if( j==pTab->iPKey ) continue;
................................................................................
109107 109321     /*
109108 109322     **   PRAGMA [schema.]schema_version
109109 109323     **   PRAGMA [schema.]schema_version = <integer>
109110 109324     **
109111 109325     **   PRAGMA [schema.]user_version
109112 109326     **   PRAGMA [schema.]user_version = <integer>
109113 109327     **
109114         -  **   PRAGMA [schema.]freelist_count = <integer>
       109328  +  **   PRAGMA [schema.]freelist_count
       109329  +  **
       109330  +  **   PRAGMA [schema.]data_version
109115 109331     **
109116 109332     **   PRAGMA [schema.]application_id
109117 109333     **   PRAGMA [schema.]application_id = <integer>
109118 109334     **
109119 109335     ** The pragma's schema_version and user_version are used to set or get
109120 109336     ** the value of the schema-version and user-version, respectively. Both
109121 109337     ** the schema-version and the user-version are 32-bit signed integers
................................................................................
109163 109379         aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
109164 109380         if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
109165 109381         aOp[0].p1 = iDb;
109166 109382         aOp[1].p1 = iDb;
109167 109383         aOp[1].p3 = iCookie;
109168 109384         sqlite3VdbeSetNumCols(v, 1);
109169 109385         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
       109386  +      sqlite3VdbeReusable(v);
109170 109387       }
109171 109388     }
109172 109389     break;
109173 109390   #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
109174 109391   
109175 109392   #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
109176 109393     /*
................................................................................
109184 109401       const char *zOpt;
109185 109402       pParse->nMem = 1;
109186 109403       setOneColumnName(v, "compile_option");
109187 109404       while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
109188 109405         sqlite3VdbeLoadString(v, 1, zOpt);
109189 109406         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
109190 109407       }
       109408  +    sqlite3VdbeReusable(v);
109191 109409     }
109192 109410     break;
109193 109411   #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
109194 109412   
109195 109413   #ifndef SQLITE_OMIT_WAL
109196 109414     /*
109197 109415     **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
................................................................................
109423 109641       char *z;
109424 109642       if( zObj==0 ) zObj = "?";
109425 109643       z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
109426 109644       if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
109427 109645       sqlite3DbFree(db, *pData->pzErrMsg);
109428 109646       *pData->pzErrMsg = z;
109429 109647     }
109430         -  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
       109648  +  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
109431 109649   }
109432 109650   
109433 109651   /*
109434 109652   ** This is the callback routine for the code that initializes the
109435 109653   ** database.  See sqlite3Init() below for additional information.
109436 109654   ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
109437 109655   **
................................................................................
109697 109915   #ifndef SQLITE_OMIT_ANALYZE
109698 109916       if( rc==SQLITE_OK ){
109699 109917         sqlite3AnalysisLoad(db, iDb);
109700 109918       }
109701 109919   #endif
109702 109920     }
109703 109921     if( db->mallocFailed ){
109704         -    rc = SQLITE_NOMEM;
       109922  +    rc = SQLITE_NOMEM_BKPT;
109705 109923       sqlite3ResetAllSchemasOfConnection(db);
109706 109924     }
109707 109925     if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
109708 109926       /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
109709 109927       ** the schema loaded, even if errors occurred. In this situation the 
109710 109928       ** current sqlite3_prepare() operation will fail, but the following one
109711 109929       ** will attempt to compile the supplied statement against whatever subset
................................................................................
109914 110132     char *zErrMsg = 0;        /* Error message */
109915 110133     int rc = SQLITE_OK;       /* Result code */
109916 110134     int i;                    /* Loop counter */
109917 110135   
109918 110136     /* Allocate the parsing context */
109919 110137     pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
109920 110138     if( pParse==0 ){
109921         -    rc = SQLITE_NOMEM;
       110139  +    rc = SQLITE_NOMEM_BKPT;
109922 110140       goto end_prepare;
109923 110141     }
109924 110142     pParse->pReprepare = pReprepare;
109925 110143     assert( ppStmt && *ppStmt==0 );
109926 110144     /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
109927 110145     assert( sqlite3_mutex_held(db->mutex) );
109928 110146   
................................................................................
109991 110209     assert( 0==pParse->nQueryLoop );
109992 110210   
109993 110211     if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
109994 110212     if( pParse->checkSchema ){
109995 110213       schemaIsValid(pParse);
109996 110214     }
109997 110215     if( db->mallocFailed ){
109998         -    pParse->rc = SQLITE_NOMEM;
       110216  +    pParse->rc = SQLITE_NOMEM_BKPT;
109999 110217     }
110000 110218     if( pzTail ){
110001 110219       *pzTail = pParse->zTail;
110002 110220     }
110003 110221     rc = pParse->rc;
110004 110222   
110005 110223   #ifndef SQLITE_OMIT_EXPLAIN
................................................................................
110354 110572     Parse *pParse,        /* Parsing context */
110355 110573     ExprList *pEList,     /* which columns to include in the result */
110356 110574     SrcList *pSrc,        /* the FROM clause -- which tables to scan */
110357 110575     Expr *pWhere,         /* the WHERE clause */
110358 110576     ExprList *pGroupBy,   /* the GROUP BY clause */
110359 110577     Expr *pHaving,        /* the HAVING clause */
110360 110578     ExprList *pOrderBy,   /* the ORDER BY clause */
110361         -  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
       110579  +  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
110362 110580     Expr *pLimit,         /* LIMIT value.  NULL means not used */
110363 110581     Expr *pOffset         /* OFFSET value.  NULL means no offset */
110364 110582   ){
110365 110583     Select *pNew;
110366 110584     Select standin;
110367 110585     sqlite3 *db = pParse->db;
110368 110586     pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
................................................................................
111678 111896           if( iCol<0 ) iCol = pTab->iPKey;
111679 111897           assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
111680 111898   #ifdef SQLITE_ENABLE_COLUMN_METADATA
111681 111899           if( iCol<0 ){
111682 111900             zType = "INTEGER";
111683 111901             zOrigCol = "rowid";
111684 111902           }else{
111685         -          zType = pTab->aCol[iCol].zType;
111686 111903             zOrigCol = pTab->aCol[iCol].zName;
       111904  +          zType = sqlite3StrNext(zOrigCol);
111687 111905             estWidth = pTab->aCol[iCol].szEst;
111688 111906           }
111689 111907           zOrigTab = pTab->zName;
111690 111908           if( pNC->pParse ){
111691 111909             int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
111692 111910             zOrigDb = pNC->pParse->db->aDb[iDb].zName;
111693 111911           }
111694 111912   #else
111695 111913           if( iCol<0 ){
111696 111914             zType = "INTEGER";
111697 111915           }else{
111698         -          zType = pTab->aCol[iCol].zType;
       111916  +          zType = sqlite3StrNext(pTab->aCol[iCol].zName);
111699 111917             estWidth = pTab->aCol[iCol].szEst;
111700 111918           }
111701 111919   #endif
111702 111920         }
111703 111921         break;
111704 111922       }
111705 111923   #ifndef SQLITE_OMIT_SUBQUERY
................................................................................
111937 112155     if( db->mallocFailed ){
111938 112156       for(j=0; j<i; j++){
111939 112157         sqlite3DbFree(db, aCol[j].zName);
111940 112158       }
111941 112159       sqlite3DbFree(db, aCol);
111942 112160       *paCol = 0;
111943 112161       *pnCol = 0;
111944         -    return SQLITE_NOMEM;
       112162  +    return SQLITE_NOMEM_BKPT;
111945 112163     }
111946 112164     return SQLITE_OK;
111947 112165   }
111948 112166   
111949 112167   /*
111950 112168   ** Add type and collation information to a column list based on
111951 112169   ** a SELECT statement.
................................................................................
111976 112194     assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
111977 112195     if( db->mallocFailed ) return;
111978 112196     memset(&sNC, 0, sizeof(sNC));
111979 112197     sNC.pSrcList = pSelect->pSrc;
111980 112198     a = pSelect->pEList->a;
111981 112199     for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
111982 112200       p = a[i].pExpr;
111983         -    if( pCol->zType==0 ){
111984         -      pCol->zType = sqlite3DbStrDup(db, 
111985         -                        columnType(&sNC, p,0,0,0, &pCol->szEst));
111986         -    }
       112201  +    columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
111987 112202       szAll += pCol->szEst;
111988 112203       pCol->affinity = sqlite3ExprAffinity(p);
111989 112204       if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
111990 112205       pColl = sqlite3ExprCollSeq(pParse, p);
111991 112206       if( pColl && pCol->zColl==0 ){
111992 112207         pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
111993 112208       }
................................................................................
112094 112309       v = sqlite3GetVdbe(pParse);
112095 112310       assert( v!=0 );
112096 112311       if( sqlite3ExprIsInteger(p->pLimit, &n) ){
112097 112312         sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
112098 112313         VdbeComment((v, "LIMIT counter"));
112099 112314         if( n==0 ){
112100 112315           sqlite3VdbeGoto(v, iBreak);
112101         -      }else if( n>=0 && p->nSelectRow>(u64)n ){
112102         -        p->nSelectRow = n;
       112316  +      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
       112317  +        p->nSelectRow = sqlite3LogEst((u64)n);
       112318  +        p->selFlags |= SF_FixedLimit;
112103 112319         }
112104 112320       }else{
112105 112321         sqlite3ExprCode(pParse, p->pLimit, iLimit);
112106 112322         sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
112107 112323         VdbeComment((v, "LIMIT counter"));
112108 112324         sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
112109 112325       }
................................................................................
112473 112689     assert( v!=0 );  /* The VDBE already created by calling function */
112474 112690   
112475 112691     /* Create the destination temporary table if necessary
112476 112692     */
112477 112693     if( dest.eDest==SRT_EphemTab ){
112478 112694       assert( p->pEList );
112479 112695       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
112480         -    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
112481 112696       dest.eDest = SRT_Table;
112482 112697     }
112483 112698   
112484 112699     /* Special handling for a compound-select that originates as a VALUES clause.
112485 112700     */
112486 112701     if( p->selFlags & SF_MultiValue ){
112487 112702       rc = multiSelectValues(pParse, p, &dest);
................................................................................
112536 112751           }
112537 112752         }
112538 112753         explainSetInteger(iSub2, pParse->iNextSelectId);
112539 112754         rc = sqlite3Select(pParse, p, &dest);
112540 112755         testcase( rc!=SQLITE_OK );
112541 112756         pDelete = p->pPrior;
112542 112757         p->pPrior = pPrior;
112543         -      p->nSelectRow += pPrior->nSelectRow;
       112758  +      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
112544 112759         if( pPrior->pLimit
112545 112760          && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
112546         -       && nLimit>0 && p->nSelectRow > (u64)nLimit 
       112761  +       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
112547 112762         ){
112548         -        p->nSelectRow = nLimit;
       112763  +        p->nSelectRow = sqlite3LogEst((u64)nLimit);
112549 112764         }
112550 112765         if( addr ){
112551 112766           sqlite3VdbeJumpHere(v, addr);
112552 112767         }
112553 112768         break;
112554 112769       }
112555 112770       case TK_EXCEPT:
................................................................................
112613 112828         testcase( rc!=SQLITE_OK );
112614 112829         /* Query flattening in sqlite3Select() might refill p->pOrderBy.
112615 112830         ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
112616 112831         sqlite3ExprListDelete(db, p->pOrderBy);
112617 112832         pDelete = p->pPrior;
112618 112833         p->pPrior = pPrior;
112619 112834         p->pOrderBy = 0;
112620         -      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
       112835  +      if( p->op==TK_UNION ){
       112836  +        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
       112837  +      }
112621 112838         sqlite3ExprDelete(db, p->pLimit);
112622 112839         p->pLimit = pLimit;
112623 112840         p->pOffset = pOffset;
112624 112841         p->iLimit = 0;
112625 112842         p->iOffset = 0;
112626 112843   
112627 112844         /* Convert the data in the temporary table into whatever form
................................................................................
112748 112965       CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
112749 112966       int nCol;                     /* Number of columns in result set */
112750 112967   
112751 112968       assert( p->pNext==0 );
112752 112969       nCol = p->pEList->nExpr;
112753 112970       pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
112754 112971       if( !pKeyInfo ){
112755         -      rc = SQLITE_NOMEM;
       112972  +      rc = SQLITE_NOMEM_BKPT;
112756 112973         goto multi_select_end;
112757 112974       }
112758 112975       for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
112759 112976         *apColl = multiSelectCollSeq(pParse, p, i);
112760 112977         if( 0==*apColl ){
112761 112978           *apColl = db->pDfltColl;
112762 112979         }
................................................................................
113103 113320         struct ExprList_item *pItem;
113104 113321         for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
113105 113322           assert( pItem->u.x.iOrderByCol>0 );
113106 113323           if( pItem->u.x.iOrderByCol==i ) break;
113107 113324         }
113108 113325         if( j==nOrderBy ){
113109 113326           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
113110         -        if( pNew==0 ) return SQLITE_NOMEM;
       113327  +        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
113111 113328           pNew->flags |= EP_IntValue;
113112 113329           pNew->u.iValue = i;
113113 113330           pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
113114 113331           if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
113115 113332         }
113116 113333       }
113117 113334     }
................................................................................
113250 113467       addrEofA_noB = addrEofA = labelEnd;
113251 113468     }else{  
113252 113469       VdbeNoopComment((v, "eof-A subroutine"));
113253 113470       addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
113254 113471       addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
113255 113472                                        VdbeCoverage(v);
113256 113473       sqlite3VdbeGoto(v, addrEofA);
113257         -    p->nSelectRow += pPrior->nSelectRow;
       113474  +    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
113258 113475     }
113259 113476   
113260 113477     /* Generate a subroutine to run when the results from select B
113261 113478     ** are exhausted and only data in select A remains.
113262 113479     */
113263 113480     if( op==TK_INTERSECT ){
113264 113481       addrEofB = addrEofA;
................................................................................
114340 114557       if( pTab==0 ) return WRC_Abort;
114341 114558       pTab->nRef = 1;
114342 114559       pTab->zName = sqlite3DbStrDup(db, pCte->zName);
114343 114560       pTab->iPKey = -1;
114344 114561       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
114345 114562       pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
114346 114563       pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
114347         -    if( db->mallocFailed ) return SQLITE_NOMEM;
       114564  +    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
114348 114565       assert( pFrom->pSelect );
114349 114566   
114350 114567       /* Check if this is a recursive CTE. */
114351 114568       pSel = pFrom->pSelect;
114352 114569       bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
114353 114570       if( bMayRecursive ){
114354 114571         int i;
................................................................................
115220 115437           SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
115221 115438           sqlite3TreeViewSelect(0, p, 0);
115222 115439         }
115223 115440   #endif
115224 115441       }
115225 115442   
115226 115443       /* Generate code to implement the subquery
       115444  +    **
       115445  +    ** The subquery is implemented as a co-routine if all of these are true:
       115446  +    **   (1)  The subquery is guaranteed to be the outer loop (so that it
       115447  +    **        does not need to be computed more than once)
       115448  +    **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
       115449  +    **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
       115450  +    **        the use of co-routines.)
       115451  +    **   (3)  Co-routines are not disabled using sqlite3_test_control()
       115452  +    **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
       115453  +    **
       115454  +    ** TODO: Are there other reasons beside (1) to use a co-routine
       115455  +    ** implementation?
115227 115456       */
115228         -    if( pTabList->nSrc==1
115229         -     && (p->selFlags & SF_All)==0
115230         -     && OptimizationEnabled(db, SQLITE_SubqCoroutine)
       115457  +    if( i==0
       115458  +     && (pTabList->nSrc==1
       115459  +            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
       115460  +     && (p->selFlags & SF_All)==0                                   /* (2) */
       115461  +     && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
115231 115462       ){
115232 115463         /* Implement a co-routine that will return a single row of the result
115233 115464         ** set on each invocation.
115234 115465         */
115235 115466         int addrTop = sqlite3VdbeCurrentAddr(v)+1;
115236 115467         pItem->regReturn = ++pParse->nMem;
115237 115468         sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
115238 115469         VdbeComment((v, "%s", pItem->pTab->zName));
115239 115470         pItem->addrFillSub = addrTop;
115240 115471         sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
115241 115472         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
115242 115473         sqlite3Select(pParse, pSub, &dest);
115243         -      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
       115474  +      pItem->pTab->nRowLogEst = pSub->nSelectRow;
115244 115475         pItem->fg.viaCoroutine = 1;
115245 115476         pItem->regResult = dest.iSdst;
115246 115477         sqlite3VdbeEndCoroutine(v, pItem->regReturn);
115247 115478         sqlite3VdbeJumpHere(v, addrTop-1);
115248 115479         sqlite3ClearTempRegCache(pParse);
115249 115480       }else{
115250 115481         /* Generate a subroutine that will fill an ephemeral table with
................................................................................
115267 115498           VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
115268 115499         }else{
115269 115500           VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
115270 115501         }
115271 115502         sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
115272 115503         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
115273 115504         sqlite3Select(pParse, pSub, &dest);
115274         -      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
       115505  +      pItem->pTab->nRowLogEst = pSub->nSelectRow;
115275 115506         if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
115276 115507         retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
115277 115508         VdbeComment((v, "end %s", pItem->pTab->zName));
115278 115509         sqlite3VdbeChangeP1(v, topAddr, retAddr);
115279 115510         sqlite3ClearTempRegCache(pParse);
115280 115511       }
115281 115512       if( db->mallocFailed ) goto select_end;
................................................................................
115350 115581     if( pDest->eDest==SRT_EphemTab ){
115351 115582       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
115352 115583     }
115353 115584   
115354 115585     /* Set the limiter.
115355 115586     */
115356 115587     iEnd = sqlite3VdbeMakeLabel(v);
115357         -  p->nSelectRow = LARGEST_INT64;
       115588  +  p->nSelectRow = 320;  /* 4 billion rows */
115358 115589     computeLimitRegisters(pParse, p, iEnd);
115359 115590     if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
115360 115591       sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
115361 115592       sSort.sortFlags |= SORTFLAG_UseSorter;
115362 115593     }
115363 115594   
115364 115595     /* Open an ephemeral index to use for the distinct set.
................................................................................
115374 115605     }else{
115375 115606       sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
115376 115607     }
115377 115608   
115378 115609     if( !isAgg && pGroupBy==0 ){
115379 115610       /* No aggregate functions and no GROUP BY clause */
115380 115611       u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
       115612  +    assert( WHERE_USE_LIMIT==SF_FixedLimit );
       115613  +    wctrlFlags |= p->selFlags & SF_FixedLimit;
115381 115614   
115382 115615       /* Begin the database scan. */
115383 115616       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
115384         -                               p->pEList, wctrlFlags, 0);
       115617  +                               p->pEList, wctrlFlags, p->nSelectRow);
115385 115618       if( pWInfo==0 ) goto select_end;
115386 115619       if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
115387 115620         p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
115388 115621       }
115389 115622       if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
115390 115623         sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
115391 115624       }
................................................................................
115437 115670   
115438 115671         for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
115439 115672           pItem->u.x.iAlias = 0;
115440 115673         }
115441 115674         for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
115442 115675           pItem->u.x.iAlias = 0;
115443 115676         }
115444         -      if( p->nSelectRow>100 ) p->nSelectRow = 100;
       115677  +      assert( 66==sqlite3LogEst(100) );
       115678  +      if( p->nSelectRow>66 ) p->nSelectRow = 66;
115445 115679       }else{
115446         -      p->nSelectRow = 1;
       115680  +      assert( 0==sqlite3LogEst(1) );
       115681  +      p->nSelectRow = 0;
115447 115682       }
115448 115683   
115449 115684       /* If there is both a GROUP BY and an ORDER BY clause and they are
115450 115685       ** identical, then it may be possible to disable the ORDER BY clause 
115451 115686       ** on the grounds that the GROUP BY will cause elements to come out 
115452 115687       ** in the correct order. It also may not - the GROUP BY might use a
115453 115688       ** database index that causes rows to be grouped together as required
................................................................................
115996 116231         p->azResult[p->nData++] = z;
115997 116232       }
115998 116233       p->nRow++;
115999 116234     }
116000 116235     return 0;
116001 116236   
116002 116237   malloc_failed:
116003         -  p->rc = SQLITE_NOMEM;
       116238  +  p->rc = SQLITE_NOMEM_BKPT;
116004 116239     return 1;
116005 116240   }
116006 116241   
116007 116242   /*
116008 116243   ** Query the database.  But instead of invoking a callback for each row,
116009 116244   ** malloc() for space to hold the result and return the entire results
116010 116245   ** at the conclusion of the call.
................................................................................
116037 116272     res.nColumn = 0;
116038 116273     res.nData = 1;
116039 116274     res.nAlloc = 20;
116040 116275     res.rc = SQLITE_OK;
116041 116276     res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
116042 116277     if( res.azResult==0 ){
116043 116278        db->errCode = SQLITE_NOMEM;
116044         -     return SQLITE_NOMEM;
       116279  +     return SQLITE_NOMEM_BKPT;
116045 116280     }
116046 116281     res.azResult[0] = 0;
116047 116282     rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
116048 116283     assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
116049 116284     res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
116050 116285     if( (rc&0xff)==SQLITE_ABORT ){
116051 116286       sqlite3_free_table(&res.azResult[1]);
................................................................................
116066 116301     }
116067 116302     if( res.nAlloc>res.nData ){
116068 116303       char **azNew;
116069 116304       azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
116070 116305       if( azNew==0 ){
116071 116306         sqlite3_free_table(&res.azResult[1]);
116072 116307         db->errCode = SQLITE_NOMEM;
116073         -      return SQLITE_NOMEM;
       116308  +      return SQLITE_NOMEM_BKPT;
116074 116309       }
116075 116310       res.azResult = azNew;
116076 116311     }
116077 116312     *pazResult = &res.azResult[1];
116078 116313     if( pnColumn ) *pnColumn = res.nColumn;
116079 116314     if( pnRow ) *pnRow = res.nRow;
116080 116315     return rc;
................................................................................
117468 117703     chngKey = chngRowid + chngPk;
117469 117704   
117470 117705     /* The SET expressions are not actually used inside the WHERE loop.  
117471 117706     ** So reset the colUsed mask. Unless this is a virtual table. In that
117472 117707     ** case, set all bits of the colUsed mask (to ensure that the virtual
117473 117708     ** table implementation makes all columns available).
117474 117709     */
117475         -  pTabList->a[0].colUsed = IsVirtual(pTab) ? (Bitmask)-1 : 0;
       117710  +  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
117476 117711   
117477 117712     hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
117478 117713   
117479 117714     /* There is one entry in the aRegIdx[] array for each index on the table
117480 117715     ** being updated.  Fill in aRegIdx[] with a register number that will hold
117481 117716     ** the key for accessing each index.
117482 117717     **
................................................................................
118051 118286   /*
118052 118287   ** Execute zSql on database db. Return an error code.
118053 118288   */
118054 118289   static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
118055 118290     sqlite3_stmt *pStmt;
118056 118291     VVA_ONLY( int rc; )
118057 118292     if( !zSql ){
118058         -    return SQLITE_NOMEM;
       118293  +    return SQLITE_NOMEM_BKPT;
118059 118294     }
118060 118295     if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
118061 118296       sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
118062 118297       return sqlite3_errcode(db);
118063 118298     }
118064 118299     VVA_ONLY( rc = ) sqlite3_step(pStmt);
118065 118300     assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
................................................................................
118232 118467       db->nextPagesize = 0;
118233 118468     }
118234 118469   
118235 118470     if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
118236 118471      || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
118237 118472      || NEVER(db->mallocFailed)
118238 118473     ){
118239         -    rc = SQLITE_NOMEM;
       118474  +    rc = SQLITE_NOMEM_BKPT;
118240 118475       goto end_of_vacuum;
118241 118476     }
118242 118477   
118243 118478   #ifndef SQLITE_OMIT_AUTOVACUUM
118244 118479     sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
118245 118480                                              sqlite3BtreeGetAutoVacuum(pMain));
118246 118481   #endif
................................................................................
118895 119130         );
118896 119131         return SQLITE_LOCKED;
118897 119132       }
118898 119133     }
118899 119134   
118900 119135     zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
118901 119136     if( !zModuleName ){
118902         -    return SQLITE_NOMEM;
       119137  +    return SQLITE_NOMEM_BKPT;
118903 119138     }
118904 119139   
118905 119140     pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
118906 119141     if( !pVTable ){
118907 119142       sqlite3DbFree(db, zModuleName);
118908         -    return SQLITE_NOMEM;
       119143  +    return SQLITE_NOMEM_BKPT;
118909 119144     }
118910 119145     pVTable->db = db;
118911 119146     pVTable->pMod = pMod;
118912 119147   
118913 119148     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118914 119149     pTab->azModuleArg[1] = db->aDb[iDb].zName;
118915 119150   
................................................................................
118953 119188         ** columns of the table to see if any of them contain the token "hidden".
118954 119189         ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
118955 119190         ** the type string.  */
118956 119191         pVTable->pNext = pTab->pVTable;
118957 119192         pTab->pVTable = pVTable;
118958 119193   
118959 119194         for(iCol=0; iCol<pTab->nCol; iCol++){
118960         -        char *zType = pTab->aCol[iCol].zType;
       119195  +        char *zType = (char*)sqlite3StrNext(pTab->aCol[iCol].zName);
118961 119196           int nType;
118962 119197           int i = 0;
118963         -        if( !zType ){
       119198  +        if( !zType[0] ){
118964 119199             pTab->tabFlags |= oooHidden;
118965 119200             continue;
118966 119201           }
118967 119202           nType = sqlite3Strlen30(zType);
118968 119203           if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
118969 119204             for(i=0; i<nType; i++){
118970 119205               if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
................................................................................
119044 119279   
119045 119280     /* Grow the sqlite3.aVTrans array if required */
119046 119281     if( (db->nVTrans%ARRAY_INCR)==0 ){
119047 119282       VTable **aVTrans;
119048 119283       int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
119049 119284       aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
119050 119285       if( !aVTrans ){
119051         -      return SQLITE_NOMEM;
       119286  +      return SQLITE_NOMEM_BKPT;
119052 119287       }
119053 119288       memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
119054 119289       db->aVTrans = aVTrans;
119055 119290     }
119056 119291   
119057 119292     return SQLITE_OK;
119058 119293   }
................................................................................
119136 119371       return SQLITE_MISUSE_BKPT;
119137 119372     }
119138 119373     pTab = pCtx->pTab;
119139 119374     assert( (pTab->tabFlags & TF_Virtual)!=0 );
119140 119375   
119141 119376     pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
119142 119377     if( pParse==0 ){
119143         -    rc = SQLITE_NOMEM;
       119378  +    rc = SQLITE_NOMEM_BKPT;
119144 119379     }else{
119145 119380       pParse->declareVtab = 1;
119146 119381       pParse->db = db;
119147 119382       pParse->nQueryLoop = 1;
119148 119383     
119149 119384       if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
119150 119385        && pParse->pNewTable
................................................................................
119448 119683     ** function */
119449 119684     pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
119450 119685                                + sqlite3Strlen30(pDef->zName) + 1);
119451 119686     if( pNew==0 ){
119452 119687       return pDef;
119453 119688     }
119454 119689     *pNew = *pDef;
119455         -  pNew->zName = (char *)&pNew[1];
119456         -  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
       119690  +  pNew->zName = (const char*)&pNew[1];
       119691  +  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
119457 119692     pNew->xSFunc = xSFunc;
119458 119693     pNew->pUserData = pArg;
119459 119694     pNew->funcFlags |= SQLITE_FUNC_EPHEM;
119460 119695     return pNew;
119461 119696   }
119462 119697   
119463 119698   /*
................................................................................
120038 120273     Parse *pParse;            /* Parsing and code generating context */
120039 120274     SrcList *pTabList;        /* List of tables in the join */
120040 120275     ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
120041 120276     ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
120042 120277     WhereLoop *pLoops;        /* List of all WhereLoop objects */
120043 120278     Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
120044 120279     LogEst nRowOut;           /* Estimated number of output rows */
       120280  +  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
120045 120281     u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
120046 120282     i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
120047 120283     u8 sorted;                /* True if really sorted (not just grouped) */
120048 120284     u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
120049 120285     u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
120050 120286     u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
120051 120287     u8 nLevel;                /* Number of nested loop */
................................................................................
121017 121253     if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
121018 121254       /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
121019 121255       **          to access the data.
121020 121256       */
121021 121257       int iReg;   /* P3 Value for OP_VFilter */
121022 121258       int addrNotFound;
121023 121259       int nConstraint = pLoop->nLTerm;
       121260  +    int iIn;    /* Counter for IN constraints */
121024 121261   
121025 121262       sqlite3ExprCachePush(pParse);
121026 121263       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
121027 121264       addrNotFound = pLevel->addrBrk;
121028 121265       for(j=0; j<nConstraint; j++){
121029 121266         int iTarget = iReg+j+2;
121030 121267         pTerm = pLoop->aLTerm[j];
121031         -      if( pTerm==0 ) continue;
       121268  +      if( NEVER(pTerm==0) ) continue;
121032 121269         if( pTerm->eOperator & WO_IN ){
121033 121270           codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
121034 121271           addrNotFound = pLevel->addrNxt;
121035 121272         }else{
121036 121273           sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
121037 121274         }
121038 121275       }
................................................................................
121039 121276       sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
121040 121277       sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
121041 121278       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
121042 121279                         pLoop->u.vtab.idxStr,
121043 121280                         pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
121044 121281       VdbeCoverage(v);
121045 121282       pLoop->u.vtab.needFree = 0;
121046         -    for(j=0; j<nConstraint && j<16; j++){
121047         -      if( (pLoop->u.vtab.omitMask>>j)&1 ){
121048         -        disableTerm(pLevel, pLoop->aLTerm[j]);
121049         -      }
121050         -    }
121051 121283       pLevel->p1 = iCur;
121052 121284       pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
121053 121285       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
       121286  +    iIn = pLevel->u.in.nIn;
       121287  +    for(j=nConstraint-1; j>=0; j--){
       121288  +      pTerm = pLoop->aLTerm[j];
       121289  +      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
       121290  +        disableTerm(pLevel, pTerm);
       121291  +      }else if( (pTerm->eOperator & WO_IN)!=0 ){
       121292  +        Expr *pCompare;  /* The comparison operator */
       121293  +        Expr *pRight;    /* RHS of the comparison */
       121294  +        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
       121295  +
       121296  +        /* Reload the constraint value into reg[iReg+j+2].  The same value
       121297  +        ** was loaded into the same register prior to the OP_VFilter, but
       121298  +        ** the xFilter implementation might have changed the datatype or
       121299  +        ** encoding of the value in the register, so it *must* be reloaded. */
       121300  +        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
       121301  +        if( !db->mallocFailed ){
       121302  +          assert( iIn>0 );
       121303  +          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
       121304  +          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
       121305  +          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
       121306  +          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
       121307  +          testcase( pOp->opcode==OP_Rowid );
       121308  +          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
       121309  +        }
       121310  +
       121311  +        /* Generate code that will continue to the next row if 
       121312  +        ** the IN constraint is not satisfied */
       121313  +        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
       121314  +        assert( pCompare!=0 || db->mallocFailed );
       121315  +        if( pCompare ){
       121316  +          pCompare->pLeft = pTerm->pExpr->pLeft;
       121317  +          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
       121318  +          if( pRight ){
       121319  +            pRight->iTable = iReg+j+2;
       121320  +            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
       121321  +          }
       121322  +          pCompare->pLeft = 0;
       121323  +          sqlite3ExprDelete(db, pCompare);
       121324  +        }
       121325  +      }
       121326  +    }
121054 121327       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
121055 121328       sqlite3ExprCachePop(pParse);
121056 121329     }else
121057 121330   #endif /* SQLITE_OMIT_VIRTUALTABLE */
121058 121331   
121059 121332     if( (pLoop->wsFlags & WHERE_IPK)!=0
121060 121333      && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
................................................................................
121355 121628       }else if( bSeekPastNull ){
121356 121629         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
121357 121630         nConstraint++;
121358 121631         startEq = 0;
121359 121632         start_constraints = 1;
121360 121633       }
121361 121634       codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
121362         -    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
121363         -    assert( op!=0 );
121364         -    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
121365         -    VdbeCoverage(v);
121366         -    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
121367         -    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
121368         -    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
121369         -    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
121370         -    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
121371         -    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
       121635  +    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
       121636  +      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
       121637  +      ** above has already left the cursor sitting on the correct row,
       121638  +      ** so no further seeking is needed */
       121639  +    }else{
       121640  +      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
       121641  +      assert( op!=0 );
       121642  +      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
       121643  +      VdbeCoverage(v);
       121644  +      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
       121645  +      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
       121646  +      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
       121647  +      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
       121648  +      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
       121649  +      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
       121650  +    }
121372 121651   
121373 121652       /* Load the value for the inequality constraint at the end of the
121374 121653       ** range (if any).
121375 121654       */
121376 121655       nConstraint = nEq;
121377 121656       if( pRangeEnd ){
121378 121657         Expr *pRight = pRangeEnd->pExpr->pRight;
................................................................................
122401 122680     */
122402 122681     assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
122403 122682     assert( pExpr->op==TK_OR );
122404 122683     pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
122405 122684     if( pOrInfo==0 ) return;
122406 122685     pTerm->wtFlags |= TERM_ORINFO;
122407 122686     pOrWc = &pOrInfo->wc;
       122687  +  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
122408 122688     sqlite3WhereClauseInit(pOrWc, pWInfo);
122409 122689     sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
122410 122690     sqlite3WhereExprAnalyze(pSrc, pOrWc);
122411 122691     if( db->mallocFailed ) return;
122412 122692     assert( pOrWc->nTerm>=2 );
122413 122693   
122414 122694     /*
................................................................................
122427 122707           WhereTerm *pAndTerm;
122428 122708           int j;
122429 122709           Bitmask b = 0;
122430 122710           pOrTerm->u.pAndInfo = pAndInfo;
122431 122711           pOrTerm->wtFlags |= TERM_ANDINFO;
122432 122712           pOrTerm->eOperator = WO_AND;
122433 122713           pAndWC = &pAndInfo->wc;
       122714  +        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
122434 122715           sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
122435 122716           sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
122436 122717           sqlite3WhereExprAnalyze(pSrc, pAndWC);
122437 122718           pAndWC->pOuter = pWC;
122438 122719           if( !db->mallocFailed ){
122439 122720             for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
122440 122721               assert( pAndTerm->pExpr );
................................................................................
123261 123542   /***/ int sqlite3WhereTrace = 0;
123262 123543   #endif
123263 123544   
123264 123545   
123265 123546   /*
123266 123547   ** Return the estimated number of output rows from a WHERE clause
123267 123548   */
123268         -SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
123269         -  return sqlite3LogEstToInt(pWInfo->nRowOut);
       123549  +SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
       123550  +  return pWInfo->nRowOut;
123270 123551   }
123271 123552   
123272 123553   /*
123273 123554   ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
123274 123555   ** WHERE clause returns outputs for DISTINCT processing.
123275 123556   */
123276 123557   SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
................................................................................
123519 123800     pScan->pOrigWC = pWC;
123520 123801     pScan->pWC = pWC;
123521 123802     pScan->pIdxExpr = 0;
123522 123803     if( pIdx ){
123523 123804       j = iColumn;
123524 123805       iColumn = pIdx->aiColumn[j];
123525 123806       if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
       123807  +    if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
123526 123808     }
123527 123809     if( pIdx && iColumn>=0 ){
123528 123810       pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
123529 123811       pScan->zCollName = pIdx->azColl[j];
123530 123812     }else{
123531 123813       pScan->idxaff = 0;
123532 123814       pScan->zCollName = 0;
................................................................................
124164 124446   **
124165 124447   ** Whether or not an error is returned, it is the responsibility of the
124166 124448   ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
124167 124449   ** that this is required.
124168 124450   */
124169 124451   static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
124170 124452     sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
124171         -  int i;
124172 124453     int rc;
124173 124454   
124174 124455     TRACE_IDX_INPUTS(p);
124175 124456     rc = pVtab->pModule->xBestIndex(pVtab, p);
124176 124457     TRACE_IDX_OUTPUTS(p);
124177 124458   
124178 124459     if( rc!=SQLITE_OK ){
................................................................................
124183 124464       }else{
124184 124465         sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
124185 124466       }
124186 124467     }
124187 124468     sqlite3_free(pVtab->zErrMsg);
124188 124469     pVtab->zErrMsg = 0;
124189 124470   
       124471  +#if 0
       124472  +  /* This error is now caught by the caller.
       124473  +  ** Search for "xBestIndex malfunction" below */
124190 124474     for(i=0; i<p->nConstraint; i++){
124191 124475       if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
124192 124476         sqlite3ErrorMsg(pParse, 
124193 124477             "table %s: xBestIndex returned an invalid plan", pTab->zName);
124194 124478       }
124195 124479     }
       124480  +#endif
124196 124481   
124197 124482     return pParse->nErr;
124198 124483   }
124199 124484   #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
124200 124485   
124201 124486   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124202 124487   /*
................................................................................
124791 125076     rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
124792 125077     pBuilder->pRec = pRec;
124793 125078     if( rc!=SQLITE_OK ) return rc;
124794 125079     if( bOk==0 ) return SQLITE_NOTFOUND;
124795 125080     pBuilder->nRecValid = nEq;
124796 125081   
124797 125082     whereKeyStats(pParse, p, pRec, 0, a);
124798         -  WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
       125083  +  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
       125084  +                   p->zName, nEq-1, (int)a[1]));
124799 125085     *pnRow = a[1];
124800 125086     
124801 125087     return rc;
124802 125088   }
124803 125089   #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
124804 125090   
124805 125091   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
................................................................................
124966 125252   ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
124967 125253   */
124968 125254   static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
124969 125255     WhereTerm **paNew;
124970 125256     if( p->nLSlot>=n ) return SQLITE_OK;
124971 125257     n = (n+7)&~7;
124972 125258     paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
124973         -  if( paNew==0 ) return SQLITE_NOMEM;
       125259  +  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
124974 125260     memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
124975 125261     if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
124976 125262     p->aLTerm = paNew;
124977 125263     p->nLSlot = n;
124978 125264     return SQLITE_OK;
124979 125265   }
124980 125266   
................................................................................
124981 125267   /*
124982 125268   ** Transfer content from the second pLoop into the first.
124983 125269   */
124984 125270   static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
124985 125271     whereLoopClearUnion(db, pTo);
124986 125272     if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
124987 125273       memset(&pTo->u, 0, sizeof(pTo->u));
124988         -    return SQLITE_NOMEM;
       125274  +    return SQLITE_NOMEM_BKPT;
124989 125275     }
124990 125276     memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
124991 125277     memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
124992 125278     if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
124993 125279       pFrom->u.vtab.needFree = 0;
124994 125280     }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
124995 125281       pFrom->u.btree.pIndex = 0;
................................................................................
125205 125491   **    (3)  The template has same or fewer dependencies than the current loop
125206 125492   **    (4)  The template has the same or lower cost than the current loop
125207 125493   */
125208 125494   static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
125209 125495     WhereLoop **ppPrev, *p;
125210 125496     WhereInfo *pWInfo = pBuilder->pWInfo;
125211 125497     sqlite3 *db = pWInfo->pParse->db;
       125498  +  int rc;
125212 125499   
125213 125500     /* If pBuilder->pOrSet is defined, then only keep track of the costs
125214 125501     ** and prereqs.
125215 125502     */
125216 125503     if( pBuilder->pOrSet!=0 ){
125217 125504       if( pTemplate->nLTerm ){
125218 125505   #if WHERETRACE_ENABLED
................................................................................
125263 125550       sqlite3DebugPrintf("    add: ");
125264 125551       whereLoopPrint(pTemplate, pBuilder->pWC);
125265 125552     }
125266 125553   #endif
125267 125554     if( p==0 ){
125268 125555       /* Allocate a new WhereLoop to add to the end of the list */
125269 125556       *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
125270         -    if( p==0 ) return SQLITE_NOMEM;
       125557  +    if( p==0 ) return SQLITE_NOMEM_BKPT;
125271 125558       whereLoopInit(p);
125272 125559       p->pNextLoop = 0;
125273 125560     }else{
125274 125561       /* We will be overwriting WhereLoop p[].  But before we do, first
125275 125562       ** go through the rest of the list and delete any other entries besides
125276 125563       ** p[] that are also supplated by pTemplate */
125277 125564       WhereLoop **ppTail = &p->pNextLoop;
................................................................................
125287 125574           sqlite3DebugPrintf(" delete: ");
125288 125575           whereLoopPrint(pToDel, pBuilder->pWC);
125289 125576         }
125290 125577   #endif
125291 125578         whereLoopDelete(db, pToDel);
125292 125579       }
125293 125580     }
125294         -  whereLoopXfer(db, p, pTemplate);
       125581  +  rc = whereLoopXfer(db, p, pTemplate);
125295 125582     if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
125296 125583       Index *pIndex = p->u.btree.pIndex;
125297 125584       if( pIndex && pIndex->tnum==0 ){
125298 125585         p->u.btree.pIndex = 0;
125299 125586       }
125300 125587     }
125301         -  return SQLITE_OK;
       125588  +  return rc;
125302 125589   }
125303 125590   
125304 125591   /*
125305 125592   ** Adjust the WhereLoop.nOut value downward to account for terms of the
125306 1