/ Check-in [601c3354]
Login

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

Overview
Comment:Many small changes to ensure memory is not leaked after malloc() fails. (CVS 2808)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 601c335463aaabc2e9918e4b9298cff6161be5c4
User & Date: danielk1977 2005-12-09 14:25:08
Context
2005-12-09
14:39
Define the sqliteMalloc() macro differently to avoid a compiler warning. (CVS 2809) check-in: 3d177bde user: danielk1977 tags: trunk
14:25
Many small changes to ensure memory is not leaked after malloc() fails. (CVS 2808) check-in: 601c3354 user: danielk1977 tags: trunk
02:35
Add more stress testing to autovacuum in an (unsuccessful) attempt to reproduce a reported problem. Even though these tests did not uncover anything amiss, extra tests never hurt... (CVS 2807) check-in: d8a8933f user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/attach.c.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the ATTACH and DETACH commands.
    13     13   **
    14         -** $Id: attach.c,v 1.36 2005/12/06 17:19:11 danielk1977 Exp $
           14  +** $Id: attach.c,v 1.37 2005/12/09 14:25:08 danielk1977 Exp $
    15     15   */
    16     16   #include "sqliteInt.h"
    17     17   
    18     18   /*
    19     19   ** Resolve an expression that was part of an ATTACH or DETACH statement. This
    20     20   ** is slightly different from resolving a normal SQL expression, because simple
    21     21   ** identifiers are treated as strings, not possible column names or aliases.
................................................................................
   257    257     int rc;
   258    258     NameContext sName;
   259    259     Vdbe *v;
   260    260     FuncDef *pFunc;
   261    261     sqlite3* db = pParse->db;
   262    262   
   263    263   #ifndef SQLITE_OMIT_AUTHORIZATION
   264         -  char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
   265         -  if( !zAuthArg ){
   266         -    goto attach_end;
   267         -  }
   268         -  if( sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0)!=SQLITE_OK ){
   269         -    goto attach_end;
          264  +  assert( sqlite3Tsd()->mallocFailed || pAuthArg );
          265  +  if( pAuthArg ){
          266  +    char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
          267  +    if( !zAuthArg ){
          268  +      goto attach_end;
          269  +    }
          270  +    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
          271  +    sqliteFree(zAuthArg);
          272  +    if(rc!=SQLITE_OK ){
          273  +      goto attach_end;
          274  +    }
   270    275     }
   271    276   #endif /* SQLITE_OMIT_AUTHORIZATION */
   272    277   
   273    278     memset(&sName, 0, sizeof(NameContext));
   274    279     sName.pParse = pParse;
   275    280   
   276    281     if( 
................................................................................
   300    305       sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
   301    306     }
   302    307     
   303    308   attach_end:
   304    309     sqlite3ExprDelete(pFilename);
   305    310     sqlite3ExprDelete(pDbname);
   306    311     sqlite3ExprDelete(pKey);
   307         -  sqliteFree(zAuthArg);
   308    312   }
   309    313   
   310    314   /*
   311    315   ** Called by the parser to compile a DETACH statement.
   312    316   **
   313    317   **     DETACH pDbname
   314    318   */

Changes to src/os_unix.c.

   629    629   ** On success, write the file handle into *id and return SQLITE_OK.
   630    630   **
   631    631   ** On failure, return SQLITE_CANTOPEN.
   632    632   */
   633    633   static int unixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
   634    634     int rc;
   635    635     unixFile f;
          636  +  int fd;
   636    637   
   637    638     assert( 0==*pId );
   638    639     if( access(zFilename, 0)==0 ){
   639    640       return SQLITE_CANTOPEN;
   640    641     }
   641    642     SET_THREADID(&f);
   642    643     f.dirfd = -1;
................................................................................
  1481   1482   ** OsFile.  If we run out of memory, close the file and return NULL.
  1482   1483   */
  1483   1484   static int allocateUnixFile(unixFile *pInit, OsFile **pId){
  1484   1485     unixFile *pNew;
  1485   1486     pNew = sqliteMalloc( sizeof(unixFile) );
  1486   1487     if( pNew==0 ){
  1487   1488       close(pInit->h);
         1489  +    releaseLockInfo(pInit->pLock);
         1490  +    releaseOpenCnt(pInit->pOpen);
  1488   1491       *pId = 0;
  1489   1492       return SQLITE_NOMEM;
  1490   1493     }else{
  1491   1494       *pNew = *pInit;
  1492   1495       pNew->pMethod = &sqlite3UnixIoMethod;
  1493   1496       *pId = (OsFile*)pNew;
  1494   1497       OpenCounter(+1);

Changes to src/prepare.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains the implementation of the sqlite3_prepare()
    13     13   ** interface, and routines that contribute to loading the database schema
    14     14   ** from disk.
    15     15   **
    16         -** $Id: prepare.c,v 1.5 2005/12/06 12:52:59 danielk1977 Exp $
           16  +** $Id: prepare.c,v 1.6 2005/12/09 14:25:08 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "os.h"
    20     20   #include <ctype.h>
    21     21   
    22     22   /*
    23     23   ** Fill the InitData structure with an error message that indicates
................................................................................
   499    499     ** inside of the sqlite3Error() call above or something.
   500    500     */
   501    501     if( sqlite3Tsd()->mallocFailed ){
   502    502       rc = SQLITE_NOMEM;
   503    503       sqlite3Error(db, rc, 0);
   504    504     }
   505    505   
   506         -  sqlite3ClearMallocFailed();
          506  +  sqlite3MallocClearFailed();
   507    507     return rc;
   508    508   }
   509    509   
   510    510   #ifndef SQLITE_OMIT_UTF16
   511    511   /*
   512    512   ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   513    513   */

Changes to src/shell.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code to implement the "sqlite" command line
    13     13   ** utility for accessing SQLite databases.
    14     14   **
    15         -** $Id: shell.c,v 1.128 2005/09/11 02:03:04 drh Exp $
           15  +** $Id: shell.c,v 1.129 2005/12/09 14:25:08 danielk1977 Exp $
    16     16   */
    17     17   #include <stdlib.h>
    18     18   #include <string.h>
    19     19   #include <stdio.h>
    20     20   #include <assert.h>
    21     21   #include "sqlite3.h"
    22     22   #include <ctype.h>
................................................................................
    77     77   static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
    78     78   static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
    79     79   
    80     80   
    81     81   /*
    82     82   ** Determines if a string is a number of not.
    83     83   */
    84         -static int isNumber(const unsigned char *z, int *realnum){
           84  +static int isNumber(const char *z, int *realnum){
    85     85     if( *z=='-' || *z=='+' ) z++;
    86     86     if( !isdigit(*z) ){
    87     87       return 0;
    88     88     }
    89     89     z++;
    90     90     if( realnum ) *realnum = 0;
    91     91     while( isdigit(*z) ){ z++; }
................................................................................
   686    686       zTmp = appendText(zTmp, zTable, '"');
   687    687       if( zTmp ){
   688    688         zSelect = appendText(zSelect, zTmp, '\'');
   689    689       }
   690    690       zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
   691    691       rc = sqlite3_step(pTableInfo);
   692    692       while( rc==SQLITE_ROW ){
          693  +      const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
   693    694         zSelect = appendText(zSelect, "quote(", 0);
   694         -      zSelect = appendText(zSelect, sqlite3_column_text(pTableInfo, 1), '"');
          695  +      zSelect = appendText(zSelect, zText, '"');
   695    696         rc = sqlite3_step(pTableInfo);
   696    697         if( rc==SQLITE_ROW ){
   697    698           zSelect = appendText(zSelect, ") || ', ' || ", 0);
   698    699         }else{
   699    700           zSelect = appendText(zSelect, ") ", 0);
   700    701         }
   701    702       }

Changes to src/sqliteInt.h.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Internal interface definitions for SQLite.
    13     13   **
    14         -** @(#) $Id: sqliteInt.h,v 1.430 2005/12/06 17:19:11 danielk1977 Exp $
           14  +** @(#) $Id: sqliteInt.h,v 1.431 2005/12/09 14:25:08 danielk1977 Exp $
    15     15   */
    16     16   #ifndef _SQLITEINT_H_
    17     17   #define _SQLITEINT_H_
    18     18   
    19     19   /*
    20     20   ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    21     21   ** Setting NDEBUG makes the code smaller and run faster.  So the following
................................................................................
   229    229   
   230    230   /*
   231    231   ** This macro casts a pointer to an integer.  Useful for doing
   232    232   ** pointer arithmetic.
   233    233   */
   234    234   #define Addr(X)  ((uptr)X)
   235    235   
   236         -/*
   237         -** If memory allocation problems are found, recompile with
   238         -**
   239         -**      -DSQLITE_DEBUG=1
   240         -**
   241         -** to enable some sanity checking on malloc() and free().  To
   242         -** check for memory leaks, recompile with
   243         -**
   244         -**      -DSQLITE_DEBUG=2
   245         -**
   246         -** and a line of text will be written to standard error for
   247         -** each malloc() and free().  This output can be analyzed
   248         -** by an AWK script to determine if there are any leaks.
   249         -*/
   250    236   #ifdef SQLITE_MEMDEBUG
   251         -# define sqliteMalloc(X)    sqlite3Malloc_(X,1,__FILE__,__LINE__)
   252         -# define sqliteMallocRaw(X) sqlite3Malloc_(X,0,__FILE__,__LINE__)
   253         -# define sqliteFree(X)      sqlite3Free_(X,__FILE__,__LINE__)
   254         -# define sqliteRealloc(X,Y) sqlite3Realloc_(X,Y,__FILE__,__LINE__)
   255         -# define sqliteStrDup(X)    sqlite3StrDup_(X,__FILE__,__LINE__)
   256         -# define sqliteStrNDup(X,Y) sqlite3StrNDup_(X,Y,__FILE__,__LINE__)
   257         -#else
   258         -# define sqliteFree          sqlite3FreeX
   259         -# define sqliteMalloc        sqlite3Malloc
   260         -# define sqliteMallocRaw     sqlite3MallocRaw
   261         -# define sqliteRealloc       sqlite3Realloc
   262         -# define sqliteStrDup        sqlite3StrDup
   263         -# define sqliteStrNDup       sqlite3StrNDup
   264         -#endif
   265         -
   266    237   /*
   267    238   ** The following global variables are used for testing and debugging
   268    239   ** only.  They only work if SQLITE_DEBUG is defined.
   269    240   */
   270         -#ifdef SQLITE_MEMDEBUG
   271    241   extern int sqlite3_nMalloc;      /* Number of sqliteMalloc() calls */
   272    242   extern int sqlite3_nFree;        /* Number of sqliteFree() calls */
   273    243   extern int sqlite3_iMallocFail;  /* Fail sqliteMalloc() after this many calls */
   274    244   extern int sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */
          245  +#define ENTER_MALLOC (\
          246  +  sqlite3Tsd()->zFile = __FILE__, sqlite3Tsd()->iLine = __LINE__ \
          247  +)
          248  +#else
          249  +#define ENTER_MALLOC 0
   275    250   #endif
          251  +
          252  +#define sqliteFree(x)          sqlite3FreeX(x)
          253  +#define sqliteMalloc(x)        (ENTER_MALLOC, sqlite3Malloc(x))
          254  +#define sqliteMallocRaw(x)     (ENTER_MALLOC, sqlite3MallocRaw(x))
          255  +#define sqliteRealloc(x,y)     (ENTER_MALLOC, sqlite3Realloc(x,y))
          256  +#define sqliteStrDup(x)        (ENTER_MALLOC, sqlite3StrDup(x))
          257  +#define sqliteStrNDup(x,y)     (ENTER_MALLOC, sqlite3StrNDup(x,y))
          258  +
          259  +/*
          260  +** An instance of this structure is allocated for each thread that uses SQLite.
          261  +*/
          262  +typedef struct SqliteTsd SqliteTsd;
          263  +struct SqliteTsd {
          264  +  int mallocFailed;               /* True after a malloc() has failed */
          265  +#ifndef NDEBUG
          266  +  int mallocAllowed;              /* assert() in sqlite3Malloc() if not set */
          267  +#endif
          268  +#ifdef SQLITE_MEMDEBUG
          269  +  int isFail;              /* True if all malloc() calls should fail */
          270  +  const char *zFile;       /* Filename to associate debugging info with */
          271  +  int iLine;               /* Line number to associate debugging info with */
          272  +  void *pFirst;            /* Pointer to linked list of allocations */
          273  +#endif
          274  +};
   276    275   
   277    276   /*
   278    277   ** Name of the master database table.  The master database table
   279    278   ** is a special table that holds the names and attributes of all
   280    279   ** user tables and indices.
   281    280   */
   282    281   #define MASTER_NAME       "sqlite_master"
................................................................................
  1375   1374   ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  1376   1375   */
  1377   1376   typedef struct {
  1378   1377     sqlite3 *db;        /* The database being initialized */
  1379   1378     char **pzErrMsg;    /* Error message stored here */
  1380   1379   } InitData;
  1381   1380   
  1382         -/*
  1383         -** An instance of this structure is allocated for each thread that uses SQLite.
  1384         -*/
  1385         -typedef struct SqliteTsd SqliteTsd;
  1386         -struct SqliteTsd {
  1387         -  int mallocFailed;               /* True after a malloc() has failed */
  1388         -};
  1389         -
  1390   1381   /*
  1391   1382    * This global flag is set for performance testing of triggers. When it is set
  1392   1383    * SQLite will perform the overhead of building new and old trigger references 
  1393   1384    * even when no triggers exist
  1394   1385    */
  1395   1386   extern int sqlite3_always_code_trigger_setup;
  1396   1387   
................................................................................
  1413   1404   int sqlite3StrICmp(const char *, const char *);
  1414   1405   int sqlite3StrNICmp(const char *, const char *, int);
  1415   1406   int sqlite3HashNoCase(const char *, int);
  1416   1407   int sqlite3IsNumber(const char*, int*, u8);
  1417   1408   int sqlite3Compare(const char *, const char *);
  1418   1409   int sqlite3SortCompare(const char *, const char *);
  1419   1410   void sqlite3RealToSortable(double r, char *);
  1420         -#ifdef SQLITE_MEMDEBUG
  1421         -  void *sqlite3Malloc_(int,int,char*,int);
  1422         -  void sqlite3Free_(void*,char*,int);
  1423         -  void *sqlite3Realloc_(void*,int,char*,int);
  1424         -  char *sqlite3StrDup_(const char*,char*,int);
  1425         -  char *sqlite3StrNDup_(const char*, int,char*,int);
  1426         -  void sqlite3CheckMemory(void*,int);
  1427         -#else
  1428         -  void *sqlite3Malloc(int);
  1429         -  void *sqlite3MallocRaw(int);
  1430         -  void sqlite3Free(void*);
  1431         -  void *sqlite3Realloc(void*,int);
  1432         -  char *sqlite3StrDup(const char*);
  1433         -  char *sqlite3StrNDup(const char*, int);
         1411  +
         1412  +void *sqlite3Malloc(int);
         1413  +void *sqlite3MallocRaw(int);
         1414  +void sqlite3Free(void*);
         1415  +void *sqlite3Realloc(void*,int);
         1416  +char *sqlite3StrDup(const char*);
         1417  +char *sqlite3StrNDup(const char*, int);
  1434   1418   # define sqlite3CheckMemory(a,b)
  1435         -# define sqlite3MallocX sqlite3Malloc
  1436         -#endif
  1437   1419   void sqlite3ReallocOrFree(void**,int);
  1438   1420   void sqlite3FreeX(void*);
  1439   1421   void *sqlite3MallocX(int);
         1422  +
  1440   1423   char *sqlite3MPrintf(const char*, ...);
  1441   1424   char *sqlite3VMPrintf(const char*, va_list);
  1442   1425   void sqlite3DebugPrintf(const char*, ...);
  1443   1426   void *sqlite3TextToPtr(const char*);
  1444   1427   void sqlite3SetString(char **, ...);
  1445   1428   void sqlite3ErrorMsg(Parse*, const char*, ...);
  1446   1429   void sqlite3Dequote(char*);
................................................................................
  1673   1656   int sqlite3InvokeBusyHandler(BusyHandler*);
  1674   1657   int sqlite3FindDb(sqlite3*, Token*);
  1675   1658   void sqlite3AnalysisLoad(sqlite3*,int iDB);
  1676   1659   void sqlite3DefaultRowEst(Index*);
  1677   1660   void sqlite3RegisterLikeFunctions(sqlite3*, int);
  1678   1661   int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  1679   1662   SqliteTsd *sqlite3Tsd();
  1680         -void sqlite3ClearMallocFailed();
  1681   1663   void sqlite3AttachFunctions(sqlite3 *);
         1664  +
         1665  +void sqlite3MallocClearFailed();
         1666  +#ifdef NDEBUG
         1667  +  #define sqlite3MallocDisallow()
         1668  +  #define sqlite3MallocAllow()
         1669  +#else
         1670  +  void sqlite3MallocDisallow();
         1671  +  void sqlite3MallocAllow();
         1672  +#endif
  1682   1673   
  1683   1674   #ifdef SQLITE_SSE
  1684   1675   #include "sseInt.h"
  1685   1676   #endif
  1686   1677   
  1687   1678   #endif

Changes to src/test1.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing the printf() interface to SQLite.  This code
    13     13   ** is not included in the SQLite library.  It is used for automated
    14     14   ** testing of the SQLite library.
    15     15   **
    16         -** $Id: test1.c,v 1.171 2005/12/06 12:53:00 danielk1977 Exp $
           16  +** $Id: test1.c,v 1.172 2005/12/09 14:25:08 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "tcl.h"
    20     20   #include "os.h"
    21     21   #include <stdlib.h>
    22     22   #include <string.h>
    23     23   
................................................................................
   828    828     char **argv            /* Text of each argument */
   829    829   ){
   830    830     char zBuf[200];
   831    831     sprintf(zBuf, "%d %d %d", sqlite3_nMalloc, sqlite3_nFree, sqlite3_iMallocFail);
   832    832     Tcl_AppendResult(interp, zBuf, 0);
   833    833     return TCL_OK;
   834    834   }
          835  +static int sqlite_malloc_outstanding(
          836  +  void *NotUsed,
          837  +  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
          838  +  int argc,              /* Number of arguments */
          839  +  char **argv            /* Text of each argument */
          840  +){
          841  +  extern int sqlite3OutstandingMallocs(Tcl_Interp *interp);
          842  +  return sqlite3OutstandingMallocs(interp);
          843  +}
   835    844   #endif
   836    845   
   837    846   /*
   838    847   ** Usage:  sqlite_abort
   839    848   **
   840    849   ** Shutdown the process immediately.  This is not a clean shutdown.
   841    850   ** This command is used to test the recoverability of a database in
................................................................................
  3078   3087        { "sqlite3_create_function",       (Tcl_CmdProc*)test_create_function  },
  3079   3088        { "sqlite3_create_aggregate",      (Tcl_CmdProc*)test_create_aggregate },
  3080   3089        { "sqlite_register_test_function", (Tcl_CmdProc*)test_register_func    },
  3081   3090        { "sqlite_abort",                  (Tcl_CmdProc*)sqlite_abort          },
  3082   3091   #ifdef SQLITE_MEMDEBUG
  3083   3092        { "sqlite_malloc_fail",            (Tcl_CmdProc*)sqlite_malloc_fail    },
  3084   3093        { "sqlite_malloc_stat",            (Tcl_CmdProc*)sqlite_malloc_stat    },
         3094  +     { "sqlite_malloc_outstanding",   (Tcl_CmdProc*)sqlite_malloc_outstanding},
  3085   3095   #endif
  3086   3096        { "sqlite_bind",                   (Tcl_CmdProc*)test_bind             },
  3087   3097        { "breakpoint",                    (Tcl_CmdProc*)test_breakpoint       },
  3088   3098        { "sqlite3_key",                   (Tcl_CmdProc*)test_key              },
  3089   3099        { "sqlite3_rekey",                 (Tcl_CmdProc*)test_rekey            },
  3090   3100        { "sqlite_set_magic",              (Tcl_CmdProc*)sqlite_set_magic      },
  3091   3101        { "sqlite3_interrupt",             (Tcl_CmdProc*)test_interrupt        },
................................................................................
  3172   3182     static int bitmask_size = sizeof(Bitmask)*8;
  3173   3183     int i;
  3174   3184     extern int sqlite3_os_trace;
  3175   3185     extern int sqlite3_where_trace;
  3176   3186     extern int sqlite3_sync_count, sqlite3_fullsync_count;
  3177   3187     extern int sqlite3_opentemp_count;
  3178   3188     extern int sqlite3_memUsed;
         3189  +  extern int sqlite3_malloc_id;
  3179   3190     extern int sqlite3_memMax;
  3180   3191     extern int sqlite3_like_count;
  3181   3192   #if OS_WIN
  3182   3193     extern int sqlite3_os_type;
  3183   3194   #endif
  3184   3195   #ifdef SQLITE_DEBUG
  3185   3196     extern int sqlite3_vdbe_addop_trace;
................................................................................
  3206   3217         (char*)&sqlite3_interrupt_count, TCL_LINK_INT);
  3207   3218     Tcl_LinkVar(interp, "sqlite_open_file_count", 
  3208   3219         (char*)&sqlite3_open_file_count, TCL_LINK_INT);
  3209   3220     Tcl_LinkVar(interp, "sqlite_current_time", 
  3210   3221         (char*)&sqlite3_current_time, TCL_LINK_INT);
  3211   3222     Tcl_LinkVar(interp, "sqlite_os_trace",
  3212   3223         (char*)&sqlite3_os_trace, TCL_LINK_INT);
         3224  +  Tcl_LinkVar(interp, "sqlite_malloc_id",
         3225  +      (char*)&sqlite3_malloc_id, TCL_LINK_STRING);
  3213   3226   #if OS_WIN
  3214   3227     Tcl_LinkVar(interp, "sqlite_os_type",
  3215   3228         (char*)&sqlite3_os_type, TCL_LINK_INT);
  3216   3229   #endif
  3217   3230   #ifdef SQLITE_TEST
  3218   3231     Tcl_LinkVar(interp, "sqlite_query_plan",
  3219   3232         (char*)&query_plan, TCL_LINK_STRING|TCL_LINK_READ_ONLY);

Changes to src/trigger.c.

   195    195   ){
   196    196     Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
   197    197     sqlite3 *db = pParse->db;  /* The database */
   198    198     DbFixer sFix;
   199    199   
   200    200     pTrig = pParse->pNewTrigger;
   201    201     pParse->pNewTrigger = 0;
   202         -  if( pParse->nErr || pTrig==0 ) goto triggerfinish_cleanup;
          202  +  if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
   203    203     pTrig->step_list = pStepList;
   204    204     while( pStepList ){
   205    205       pStepList->pTrig = pTrig;
   206    206       pStepList = pStepList->pNext;
   207    207     }
   208    208     if( sqlite3FixInit(&sFix, pParse, pTrig->iDb, "trigger", &pTrig->nameToken) 
   209    209             && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
................................................................................
   308    308   ** a trigger step.  Return a pointer to a TriggerStep structure.
   309    309   **
   310    310   ** The parser calls this routine when it finds a SELECT statement in
   311    311   ** body of a TRIGGER.  
   312    312   */
   313    313   TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
   314    314     TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
   315         -  if( pTriggerStep==0 ) return 0;
          315  +  if( pTriggerStep==0 ) {
          316  +    sqlite3SelectDelete(pSelect);
          317  +    return 0;
          318  +  }
   316    319   
   317    320     pTriggerStep->op = TK_SELECT;
   318    321     pTriggerStep->pSelect = pSelect;
   319    322     pTriggerStep->orconf = OE_Default;
   320    323     sqlitePersistTriggerStep(pTriggerStep);
   321    324   
   322    325     return pTriggerStep;

Changes to src/util.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Utility functions used throughout sqlite.
    13     13   **
    14     14   ** This file contains functions for allocating memory, comparing
    15     15   ** strings, and stuff like that.
    16     16   **
    17         -** $Id: util.c,v 1.149 2005/12/06 12:53:01 danielk1977 Exp $
           17  +** $Id: util.c,v 1.150 2005/12/09 14:25:09 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include <stdarg.h>
    21     21   #include <ctype.h>
    22     22   
    23         -#if SQLITE_MEMDEBUG>2 && defined(__GLIBC__)
    24         -#include <execinfo.h>
    25         -void print_stack_trace(){
    26         -  void *bt[30];
    27         -  int i;
    28         -  int n = backtrace(bt, 30);
    29         -
    30         -  fprintf(stderr, "STACK: ");
    31         -  for(i=0; i<n;i++){
    32         -    fprintf(stderr, "%p ", bt[i]);
    33         -  }
    34         -  fprintf(stderr, "\n");
    35         -}
           23  +/*
           24  +** MALLOC WRAPPER ARCHITECTURE
           25  +**
           26  +** The sqlite code accesses dynamic memory allocation/deallocation by invoking
           27  +** the following four APIs (which may be implemented as macros).
           28  +**
           29  +**     sqlite3Malloc()
           30  +**     sqlite3MallocRaw()
           31  +**     sqlite3Realloc()
           32  +**     sqlite3ReallocOrFree()
           33  +**     sqlite3Free()
           34  +**
           35  +** The function sqlite3FreeX performs the same task as sqlite3Free and is
           36  +** guaranteed to be a real function.
           37  +**
           38  +** The above APIs are implemented in terms of the functions provided at the Os
           39  +** level (not in this file). The Os level interface is never accessed directly
           40  +** by code outside of this file.
           41  +**
           42  +**     sqlite3OsMalloc()
           43  +**     sqlite3OsRealloc()
           44  +**     sqlite3OsFree()
           45  +**     sqlite3OsAllocationSize()
           46  +**
           47  +** Functions sqlite3MallocRaw() and sqlite3Realloc() may invoke 
           48  +** sqlite3_release_memory() if a call to sqlite3OsMalloc() or
           49  +** sqlite3OsRealloc() fails. Function sqlite3Malloc() usually invokes
           50  +** sqlite3MallocRaw().
           51  +**
           52  +** MALLOC TEST WRAPPER ARCHITECTURE
           53  +**
           54  +** The test wrapper provides extra test facilities to ensure the library 
           55  +** does not leak memory and handles the failure of the underlying (Os level)
           56  +** allocation system correctly. It is only present if the library is 
           57  +** compiled with the SQLITE_MEMDEBUG macro set.
           58  +**
           59  +**     * Guardposts to detect overwrites.
           60  +**     * Ability to cause a specific Malloc() or Realloc() to fail.
           61  +**     * Audit outstanding memory allocations (i.e check for leaks).
           62  +*/
           63  +
           64  +/*
           65  +** sqlite3OsMalloc
           66  +** sqlite3OsRealloc
           67  +** sqlite3OsOsFree
           68  +** sqlite3OsAllocationSize
           69  +**
           70  +** Implementation of the os level dynamic memory allocation interface in terms
           71  +** of the standard malloc(), realloc() and free() found in many operating
           72  +** systems. No rocket science here.
           73  +*/
           74  +void *sqlite3OsMalloc(int n){
           75  +  char *p = (char *)malloc(n+8);
           76  +  assert(n>0);
           77  +  assert(sizeof(int)<=8);
           78  +  if( p ){
           79  +    *(int *)p = n;
           80  +  }
           81  +  return (void *)(p + 8);
           82  +}
           83  +void *sqlite3OsRealloc(void *p, int n){
           84  +  char *p2 = ((char *)p - 8);
           85  +  assert(n>0);
           86  +  p2 = realloc(p2, n+8);
           87  +  if( p2 ){
           88  +    *(int *)p2 = n;
           89  +  }
           90  +  return (void *)((char *)p2 + 8);
           91  +}
           92  +void sqlite3OsFree(void *p){
           93  +  assert(p);
           94  +  free((void *)((char *)p - 8));
           95  +}
           96  +int sqlite3OsAllocationSize(void *p){
           97  +  return *(int *)((char *)p - 8);
           98  +}
           99  +
          100  +/*
          101  +** TODO!
          102  +*/
          103  +#define sqlite3_release_memory(x) 0
          104  +
          105  +#ifdef SQLITE_MEMDEBUG
          106  +/*--------------------------------------------------------------------------
          107  +** Begin code for memory allocation system test layer.
          108  +**
          109  +** Memory debugging is turned on by defining the SQLITE_MEMDEBUG macro.
          110  +*/
          111  +
          112  +/* Figure out whether or not to store backtrace() information for each malloc.
          113  +** The backtrace() function is only used if SQLITE_MEMDEBUG is set to 2 or 
          114  +** greater and glibc is in use. If we don't want to use backtrace(), then just
          115  +** define it as an empty macro and set the amount of space reserved to 0.
          116  +*/
          117  +#if defined(__GLIBC__) && SQLITE_MEMDEBUG>1
          118  +  extern int backtrace(void **, int);
          119  +  #define TESTALLOC_STACKSIZE 128
          120  +  #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
    36    121   #else
    37         -#define print_stack_trace()
    38         -#endif
    39         -
    40         -#if 0
    41         -/*
    42         -** If malloc() ever fails, this global variable gets set to 1.
    43         -** This causes the library to abort and never again function.
    44         -*/
    45         -int sqlite3Tsd()->mallocFailed = 0;
          122  +  #define backtrace(x, y) 0
          123  +  #define TESTALLOC_STACKSIZE 0
          124  +  #define TESTALLOC_STACKFRAMES 0
    46    125   #endif
    47    126   
    48    127   /*
    49         -** If SQLITE_MEMDEBUG is defined, then use versions of malloc() and
    50         -** free() that track memory usage and check for buffer overruns.
          128  +** Number of 32-bit guard words.  This should probably be a multiple of
          129  +** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
          130  +** to be 8-byte aligned.
    51    131   */
    52         -#ifdef SQLITE_MEMDEBUG
          132  +#define TESTALLOC_NGUARD 2
          133  +
          134  +/*
          135  +** Size reserved for storing file-name along with each malloc()ed blob.
          136  +*/
          137  +#define TESTALLOC_FILESIZE 64
          138  +
          139  +/*
          140  +** Size reserved for storing the user string.
          141  +*/
          142  +#define TESTALLOC_USERSIZE 64
          143  +const char *sqlite3_malloc_id = 0;
          144  +
          145  +/*
          146  +** Blocks used by the test layer have the following format:
          147  +**
          148  +**        <sizeof(void *) pNext pointer>
          149  +**        <sizeof(void *) pPrev pointer>
          150  +**        <TESTALLOC_NGUARD 32-bit guard words>
          151  +**            <The application level allocation>
          152  +**        <TESTALLOC_NGUARD 32-bit guard words>
          153  +**        <32-bit line number>
          154  +**        <TESTALLOC_FILESIZE bytes containing null-terminated file name>
          155  +**        <TESTALLOC_STACKSIZE bytes of backtrace() output>
          156  +*/ 
          157  +
          158  +#define TESTALLOC_OFFSET_GUARD1(p)    (sizeof(void *) * 2)
          159  +#define TESTALLOC_OFFSET_DATA(p) ( \
          160  +  TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
          161  +)
          162  +#define TESTALLOC_OFFSET_GUARD2(p) ( \
          163  +  TESTALLOC_OFFSET_DATA(p) + sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
          164  +)
          165  +#define TESTALLOC_OFFSET_LINENUMBER(p) ( \
          166  +  TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
          167  +)
          168  +#define TESTALLOC_OFFSET_FILENAME(p) ( \
          169  +  TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
          170  +)
          171  +#define TESTALLOC_OFFSET_USER(p) ( \
          172  +  TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
          173  +)
          174  +#define TESTALLOC_OFFSET_STACK(p) ( \
          175  +  TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
          176  +  (TESTALLOC_OFFSET_USER(p) % 8) \
          177  +)
          178  +
          179  +#define TESTALLOC_OVERHEAD ( \
          180  +  sizeof(void *)*2 +                   /* pPrev and pNext pointers */   \
          181  +  TESTALLOC_NGUARD*sizeof(u32)*2 +              /* Guard words */       \
          182  +  sizeof(u32) + TESTALLOC_FILESIZE +   /* File and line number */       \
          183  +  TESTALLOC_USERSIZE +                 /* User string */                \
          184  +  TESTALLOC_STACKSIZE                  /* backtrace() stack */          \
          185  +)
    53    186   
    54    187   /*
    55    188   ** For keeping track of the number of mallocs and frees.   This
    56    189   ** is used to check for memory leaks.  The iMallocFail and iMallocReset
    57    190   ** values are used to simulate malloc() failures during testing in 
    58    191   ** order to verify that the library correctly handles an out-of-memory
    59    192   ** condition.
    60    193   */
    61    194   int sqlite3_nMalloc;         /* Number of sqliteMalloc() calls */
    62    195   int sqlite3_nFree;           /* Number of sqliteFree() calls */
    63         -int sqlite3_memUsed;         /* Total memory obtained from malloc */
    64         -int sqlite3_memMax;          /* Mem usage high-water mark */
          196  +int sqlite3_memUsed;         /* TODO Total memory obtained from malloc */
          197  +int sqlite3_memMax;          /* TODO Mem usage high-water mark */
    65    198   int sqlite3_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
    66    199   int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
    67         -#if SQLITE_MEMDEBUG>1
    68         -static int memcnt = 0;
    69         -#endif
    70         -
    71         -/*
    72         -** Number of 32-bit guard words.  This should probably be a multiple of
    73         -** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
    74         -** to be 8-byte aligned.
    75         -*/
    76         -#define N_GUARD 2
    77    200   
    78    201   /*
    79    202   ** Check for a simulated memory allocation failure.  Return true if
    80    203   ** the failure should be simulated.  Return false to proceed as normal.
    81    204   */
    82         -static int simulatedMallocFailure(int n, char *zFile, int line){
          205  +static int failMalloc(){
          206  +  SqliteTsd *pTsd = sqlite3Tsd();
          207  +  if( pTsd->isFail ){
          208  +    return 1;
          209  +  }
    83    210     if( sqlite3_iMallocFail>=0 ){
    84    211       sqlite3_iMallocFail--;
    85    212       if( sqlite3_iMallocFail==0 ){
    86         -      sqlite3Tsd()->mallocFailed++;
    87         -#if SQLITE_MEMDEBUG>1
    88         -      fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
    89         -              n, zFile,line);
    90         -#endif
    91    213         sqlite3_iMallocFail = sqlite3_iMallocReset;
          214  +      pTsd->isFail = 1;
    92    215         return 1;
    93    216       }
    94    217     }
    95    218     return 0;
    96    219   }
    97    220   
    98    221   /*
    99         -** Allocate new memory and set it to zero.  Return NULL if
   100         -** no memory is available.
   101         -*/
   102         -void *sqlite3Malloc_(int n, int bZero, char *zFile, int line){
   103         -  void *p;
   104         -  int *pi;
   105         -  int i, k;
   106         -
   107         -  /* Any malloc() calls between a malloc() failure and clearing the
   108         -  ** mallocFailed flag (done before returning control to the user)
   109         -  ** automatically fail. Although this restriction may have to be relaxed in
   110         -  ** the future, for now it makes the system easier to test.
   111         -  **
   112         -  ** TODO: This will eventually be done as part of the same wrapper that may
   113         -  ** call sqlite3_release_memory(). Above the sqlite3OsMalloc() level.
   114         -  */
   115         -  if( sqlite3Tsd()->mallocFailed ){
   116         -    return 0;
   117         -  }
   118         -
   119         -  if( n==0 ){
   120         -    return 0;
   121         -  }
   122         -  if( simulatedMallocFailure(n, zFile, line) ){
   123         -    return 0;
   124         -  }
   125         -  sqlite3_memUsed += n;
   126         -  if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
   127         -  k = (n+sizeof(int)-1)/sizeof(int);
   128         -  pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
   129         -  if( pi==0 ){
   130         -    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   131         -    return 0;
   132         -  }
   133         -  sqlite3_nMalloc++;
   134         -  for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
   135         -  pi[N_GUARD] = n;
   136         -  for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
   137         -  p = &pi[N_GUARD+1];
   138         -  memset(p, bZero==0, n);
   139         -#if SQLITE_MEMDEBUG>1
   140         -  print_stack_trace();
   141         -  fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
   142         -      ++memcnt, n, (int)p, zFile,line);
   143         -#endif
   144         -  return p;
   145         -}
   146         -
   147         -/*
   148         -** This version of malloc is always a real function, never a macro
   149         -*/
   150         -void *sqlite3MallocX(int n){
   151         -  return sqlite3Malloc_(n, 0, __FILE__, __LINE__);
   152         -}
   153         -
   154         -/*
   155         -** Check to see if the given pointer was obtained from sqliteMalloc()
   156         -** and is able to hold at least N bytes.  Raise an exception if this
   157         -** is not the case.
   158         -**
   159         -** This routine is used for testing purposes only.
   160         -*/
   161         -void sqlite3CheckMemory(void *p, int N){
   162         -  int *pi = p;
   163         -  int n, i, k;
   164         -  pi -= N_GUARD+1;
   165         -  for(i=0; i<N_GUARD; i++){
   166         -    assert( pi[i]==0xdead1122 );
   167         -  }
   168         -  n = pi[N_GUARD];
   169         -  assert( N>=0 && N<n );
   170         -  k = (n+sizeof(int)-1)/sizeof(int);
   171         -  for(i=0; i<N_GUARD; i++){
   172         -    assert( pi[k+N_GUARD+1+i]==0xdead3344 );
   173         -  }
   174         -}
   175         -
   176         -/*
   177         -** Free memory previously obtained from sqliteMalloc()
   178         -*/
   179         -void sqlite3Free_(void *p, char *zFile, int line){
   180         -  if( p ){
   181         -    int *pi, i, k, n;
   182         -    pi = p;
   183         -    pi -= N_GUARD+1;
   184         -    sqlite3_nFree++;
   185         -    for(i=0; i<N_GUARD; i++){
   186         -      if( pi[i]!=0xdead1122 ){
   187         -        fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
   188         -        return;
   189         -      }
          222  +** The argument is a pointer returned by sqlite3OsMalloc() or Realloc().
          223  +** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
          224  +** values set by the applyGuards() function.
          225  +*/
          226  +static void checkGuards(u32 *p)
          227  +{
          228  +  int i;
          229  +  char *zAlloc = (char *)p;
          230  +  char *z;
          231  +
          232  +  /* First set of guard words */
          233  +  z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
          234  +  for(i=0; i<TESTALLOC_NGUARD; i++){
          235  +    assert(((u32 *)z)[i]==0xdead1122);
          236  +  }
          237  +
          238  +  /* Second set of guard words */
          239  +  z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
          240  +  for(i=0; i<TESTALLOC_NGUARD; i++){
          241  +    u32 guard = 0;
          242  +    memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
          243  +    assert(guard==0xdead3344);
          244  +  }
          245  +}
          246  +
          247  +/*
          248  +** The argument is a pointer returned by sqlite3OsMalloc() or Realloc(). The
          249  +** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as 
          250  +** guard-posts.
          251  +*/
          252  +static void applyGuards(u32 *p)
          253  +{
          254  +  int i;
          255  +  char *z;
          256  +  char *zAlloc = (char *)p;
          257  +
          258  +  /* First set of guard words */
          259  +  z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
          260  +  for(i=0; i<TESTALLOC_NGUARD; i++){
          261  +    ((u32 *)z)[i] = 0xdead1122;
          262  +  }
          263  +
          264  +  /* Second set of guard words */
          265  +  z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
          266  +  for(i=0; i<TESTALLOC_NGUARD; i++){
          267  +    static const int guard = 0xdead3344;
          268  +    memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
          269  +  }
          270  +
          271  +  /* Line number */
          272  +  z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)];             /* Guard words */
          273  +  z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
          274  +  memcpy(z, &sqlite3Tsd()->iLine, sizeof(u32));
          275  +
          276  +  /* File name */
          277  +  z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
          278  +  strncpy(z, sqlite3Tsd()->zFile, TESTALLOC_FILESIZE);
          279  +  z[TESTALLOC_FILESIZE - 1] = '\0';
          280  +
          281  +  /* User string */
          282  +  z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
          283  +  z[0] = 0;
          284  +  if( sqlite3_malloc_id ){
          285  +    strncpy(z, sqlite3_malloc_id, TESTALLOC_USERSIZE);
          286  +    z[TESTALLOC_USERSIZE-1] = 0;
          287  +  }
          288  +
          289  +  /* backtrace() stack */
          290  +  z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
          291  +  backtrace((void **)z, TESTALLOC_STACKFRAMES);
          292  +
          293  +  /* Sanity check to make sure checkGuards() is working */
          294  +  checkGuards(p);
          295  +}
          296  +
          297  +static void *getOsPointer(void *p)
          298  +{
          299  +  char *z = (char *)p;
          300  +  return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
          301  +}
          302  +
          303  +/*
          304  +** The argument points to an Os level allocation. Link it into the threads list
          305  +** of allocations.
          306  +*/
          307  +static void linkAlloc(void *p){
          308  +  SqliteTsd *pTsd = sqlite3Tsd();
          309  +  void **pp = (void **)p;
          310  +  pp[0] = 0;
          311  +  pp[1] = pTsd->pFirst;
          312  +  if( pTsd->pFirst ){
          313  +    ((void **)pTsd->pFirst)[0] = p;
          314  +  }
          315  +  pTsd->pFirst = p;
          316  +}
          317  +
          318  +/*
          319  +** The argument points to an Os level allocation. Unlinke it from the threads
          320  +** list of allocations.
          321  +*/
          322  +static void unlinkAlloc(void *p)
          323  +{
          324  +  SqliteTsd *pTsd = sqlite3Tsd();
          325  +  void **pp = (void **)p;
          326  +  if( p==pTsd->pFirst ){
          327  +    assert(!pp[0]);
          328  +    assert(!pp[1] || ((void **)(pp[1]))[0]==p);
          329  +    pTsd->pFirst = pp[1];
          330  +    if( pTsd->pFirst ){
          331  +      ((void **)pTsd->pFirst)[0] = 0;
          332  +    }
          333  +  }else{
          334  +    void **pprev = pp[0];
          335  +    void **pnext = pp[1];
          336  +    assert(pprev);
          337  +    assert(pprev[1]==p);
          338  +    pprev[1] = (void *)pnext;
          339  +    if( pnext ){
          340  +      assert(pnext[0]==p);
          341  +      pnext[0] = (void *)pprev;
   190    342       }
   191         -    n = pi[N_GUARD];
   192         -    sqlite3_memUsed -= n;
   193         -    k = (n+sizeof(int)-1)/sizeof(int);
   194         -    for(i=0; i<N_GUARD; i++){
   195         -      if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
   196         -        fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
   197         -        return;
   198         -      }
   199         -    }
   200         -    memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
   201         -#if SQLITE_MEMDEBUG>1
   202         -    fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
   203         -         ++memcnt, n, (int)p, zFile,line);
   204         -#endif
   205         -    free(pi);
   206         -  }
   207         -}
   208         -
   209         -/*
   210         -** Resize a prior allocation.  If p==0, then this routine
   211         -** works just like sqliteMalloc().  If n==0, then this routine
   212         -** works just like sqliteFree().
   213         -*/
   214         -void *sqlite3Realloc_(void *oldP, int n, char *zFile, int line){
   215         -  int *oldPi, *pi, i, k, oldN, oldK;
          343  +  }
          344  +}
          345  +
          346  +/*
          347  +** Pointer p is a pointer to an OS level allocation that has just been
          348  +** realloc()ed. Set the list pointers that point to this entry to it's new
          349  +** location.
          350  +*/
          351  +static void relinkAlloc(void *p)
          352  +{
          353  +  void **pp = (void **)p;
          354  +  if( pp[0] ){
          355  +    ((void **)(pp[0]))[1] = p;
          356  +  }else{
          357  +    SqliteTsd *pTsd = sqlite3Tsd();
          358  +    pTsd->pFirst = p;
          359  +  }
          360  +  if( pp[1] ){
          361  +    ((void **)(pp[1]))[0] = p;
          362  +  }
          363  +}
          364  +
          365  +/*
          366  +** This function sets the result of the Tcl interpreter passed as an argument
          367  +** to a list containing an entry for each currently outstanding call made to
          368  +** sqliteMalloc and friends by the current thread.
          369  +**
          370  +** Todo: We could have a version of this function that outputs to stdout, 
          371  +** to debug memory leaks when Tcl is not available.
          372  +*/
          373  +#ifdef TCLSH
          374  +#include <tcl.h>
          375  +int sqlite3OutstandingMallocs(Tcl_Interp *interp){
   216    376     void *p;
   217         -  if( oldP==0 ){
   218         -    return sqlite3Malloc_(n,1,zFile,line);
   219         -  }
   220         -  if( n==0 ){
   221         -    sqlite3Free_(oldP,zFile,line);
   222         -    return 0;
   223         -  }
   224         -  if( simulatedMallocFailure(n, zFile, line) ){
   225         -    return 0;
   226         -  }
   227         -  oldPi = oldP;
   228         -  oldPi -= N_GUARD+1;
   229         -  if( oldPi[0]!=0xdead1122 ){
   230         -    fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
   231         -    return 0;
   232         -  }
   233         -  oldN = oldPi[N_GUARD];
   234         -  sqlite3_memUsed -= oldN;
   235         -  oldK = (oldN+sizeof(int)-1)/sizeof(int);
   236         -  for(i=0; i<N_GUARD; i++){
   237         -    if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
   238         -      fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
   239         -              (int)oldP);
   240         -      return 0;
          377  +  SqliteTsd *pTsd = sqlite3Tsd();
          378  +  Tcl_Obj *pRes = Tcl_NewObj();
          379  +  Tcl_IncrRefCount(pRes);
          380  +
          381  +  for(p=pTsd->pFirst; p; p=((void **)p)[1]){
          382  +    Tcl_Obj *pEntry = Tcl_NewObj();
          383  +    Tcl_Obj *pStack = Tcl_NewObj();
          384  +    char *z;
          385  +    u32 iLine;
          386  +    int nBytes = sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
          387  +    char *zAlloc = (char *)p;
          388  +    int i;
          389  +
          390  +    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));
          391  +
          392  +    z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
          393  +    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
          394  +
          395  +    z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
          396  +    memcpy(&iLine, z, sizeof(u32));
          397  +    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));
          398  +
          399  +    z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
          400  +    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
          401  +
          402  +    z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
          403  +    for(i=0; i<TESTALLOC_STACKFRAMES; i++){
          404  +      char zHex[128];
          405  +      sprintf(zHex, "%p", ((void **)z)[i]);
          406  +      Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
          407  +    }
          408  +
          409  +    Tcl_ListObjAppendElement(0, pEntry, pStack);
          410  +    Tcl_ListObjAppendElement(0, pRes, pEntry);
          411  +  }
          412  +
          413  +  Tcl_ResetResult(interp);
          414  +  Tcl_SetObjResult(interp, pRes);
          415  +  Tcl_DecrRefCount(pRes);
          416  +  return TCL_OK;
          417  +}
          418  +#endif
          419  +
          420  +/*
          421  +** This is the test layer's wrapper around sqlite3OsMalloc().
          422  +*/
          423  +static void * OSMALLOC(int n){
          424  +  if( !failMalloc() ){
          425  +    u32 *p;
          426  +    p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
          427  +    assert(p);
          428  +    sqlite3_nMalloc++;
          429  +    applyGuards(p);
          430  +    linkAlloc(p);
          431  +    return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
          432  +  }
          433  +  return 0;
          434  +}
          435  +
          436  +/*
          437  +** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
          438  +** pointer to the space allocated for the application to use.
          439  +*/
          440  +void OSFREE(void *pFree){
          441  +  u32 *p = (u32 *)getOsPointer(pFree);   /* p points to Os level allocation */
          442  +  checkGuards(p);
          443  +  unlinkAlloc(p);
          444  +  sqlite3OsFree(p);
          445  +  sqlite3_nFree++;
          446  +}
          447  +
          448  +/*
          449  +** This is the test layer's wrapper around sqlite3OsRealloc().
          450  +*/
          451  +void * OSREALLOC(void *pRealloc, int n){
          452  +  if( !failMalloc() ){
          453  +    u32 *p = (u32 *)getOsPointer(pRealloc);
          454  +    checkGuards(p);
          455  +    p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
          456  +    applyGuards(p);
          457  +    relinkAlloc(p);
          458  +    return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
          459  +  }
          460  +  return 0;
          461  +}
          462  +
          463  +void OSMALLOC_FAILED(){
          464  +  sqlite3Tsd()->isFail = 0;
          465  +}
          466  +
          467  +#else
          468  +#define OSMALLOC(x) sqlite3OsMalloc(x)
          469  +#define OSREALLOC(x,y) sqlite3OsRealloc(x,y)
          470  +#define OSFREE(x) sqlite3OsFree(x)
          471  +#define OSMALLOC_FAILED()
          472  +#endif
          473  +/*
          474  +** End code for memory allocation system test layer.
          475  +**--------------------------------------------------------------------------*/
          476  +
          477  +/*
          478  +** Allocate and return N bytes of uninitialised memory by calling
          479  +** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory 
          480  +** by calling sqlite3_release_memory().
          481  +*/
          482  +void *sqlite3MallocRaw(int n){
          483  +  SqliteTsd *pTsd = sqlite3Tsd();
          484  +  void *p = 0;
          485  +
          486  +  if( n>0 && !pTsd->mallocFailed ){
          487  +    while( !(p = OSMALLOC(n)) && sqlite3_release_memory(n) );
          488  +    if( !p ){
          489  +      sqlite3Tsd()->mallocFailed = 1;
          490  +      OSMALLOC_FAILED();
   241    491       }
   242    492     }
   243         -  k = (n + sizeof(int) - 1)/sizeof(int);
   244         -  pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
   245         -  if( pi==0 ){
   246         -    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   247         -    return 0;
   248         -  }
   249         -  for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
   250         -  pi[N_GUARD] = n;
   251         -  sqlite3_memUsed += n;
   252         -  if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
   253         -  for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
   254         -  p = &pi[N_GUARD+1];
   255         -  memcpy(p, oldP, n>oldN ? oldN : n);
   256         -  if( n>oldN ){
   257         -    memset(&((char*)p)[oldN], 0x55, n-oldN);
   258         -  }
   259         -  memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
   260         -  free(oldPi);
   261         -#if SQLITE_MEMDEBUG>1
   262         -  print_stack_trace();
   263         -  fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
   264         -    ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
   265         -#endif
   266    493     return p;
   267    494   }
   268    495   
   269    496   /*
   270         -** Make a copy of a string in memory obtained from sqliteMalloc()
   271         -*/
   272         -char *sqlite3StrDup_(const char *z, char *zFile, int line){
   273         -  char *zNew;
   274         -  if( z==0 ) return 0;
   275         -  zNew = sqlite3Malloc_(strlen(z)+1, 0, zFile, line);
   276         -  if( zNew ) strcpy(zNew, z);
   277         -  return zNew;
   278         -}
   279         -char *sqlite3StrNDup_(const char *z, int n, char *zFile, int line){
   280         -  char *zNew;
   281         -  if( z==0 ) return 0;
   282         -  zNew = sqlite3Malloc_(n+1, 0, zFile, line);
   283         -  if( zNew ){
   284         -    memcpy(zNew, z, n);
   285         -    zNew[n] = 0;
   286         -  }
   287         -  return zNew;
   288         -}
   289         -
   290         -/*
   291         -** A version of sqliteFree that is always a function, not a macro.
          497  +** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
          498  +** pointer to the new allocation is returned.  If the Realloc() call fails,
          499  +** attempt to free memory by calling sqlite3_release_memory().
          500  +*/
          501  +void *sqlite3Realloc(void *p, int n){
          502  +  SqliteTsd *pTsd = sqlite3Tsd();
          503  +  if( pTsd->mallocFailed ){
          504  +    return 0;
          505  +  }
          506  +
          507  +  if( !p ){
          508  +    return sqlite3Malloc(n);
          509  +  }else{
          510  +    void *np = 0;
          511  +    while( !(np = OSREALLOC(p, n)) && sqlite3_release_memory(n) );
          512  +    if( !np ){
          513  +      pTsd->mallocFailed = 1;
          514  +      OSMALLOC_FAILED();
          515  +    }
          516  +    return np;
          517  +  }
          518  +}
          519  +
          520  +/*
          521  +** Free the memory pointed to by p. p must be either a NULL pointer or a 
          522  +** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
   292    523   */
   293    524   void sqlite3FreeX(void *p){
   294         -  sqliteFree(p);
          525  +  if( p ){
          526  +    OSFREE(p);
          527  +  }
   295    528   }
   296         -#endif /* SQLITE_MEMDEBUG */
   297    529   
   298    530   /*
   299         -** The following versions of malloc() and free() are for use in a
   300         -** normal build.
          531  +** A version of sqliteMalloc() that is always a function, not a macro.
          532  +** Currently, this is used only to alloc only used drawback.
   301    533   */
   302         -#if !defined(SQLITE_MEMDEBUG)
          534  +void *sqlite3MallocX(int n){
          535  +  return sqliteMalloc(n);
          536  +}
   303    537   
   304    538   /*
   305         -** Allocate new memory and set it to zero.  Return NULL if
   306         -** no memory is available.  See also sqliteMallocRaw().
   307         -*/
          539  +** sqlite3Malloc
          540  +** sqlite3ReallocOrFree
          541  +**
          542  +** These two are implemented as wrappers around sqlite3MallocRaw(), 
          543  +** sqlite3Realloc() and sqlite3Free().
          544  +*/ 
   308    545   void *sqlite3Malloc(int n){
   309         -  void *p;
   310         -  if( n==0 ) return 0;
   311         -  if( (p = malloc(n))==0 ){
   312         -    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   313         -  }else{
          546  +  void *p = sqlite3MallocRaw(n);
          547  +  if( p ){
   314    548       memset(p, 0, n);
   315    549     }
   316    550     return p;
   317    551   }
   318         -
   319         -/*
   320         -** Allocate new memory but do not set it to zero.  Return NULL if
   321         -** no memory is available.  See also sqliteMalloc().
   322         -*/
   323         -void *sqlite3MallocRaw(int n){
   324         -  void *p;
   325         -  if( n==0 ) return 0;
   326         -  if( (p = malloc(n))==0 ){
   327         -    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   328         -  }
   329         -  return p;
   330         -}
   331         -
   332         -/*
   333         -** Free memory previously obtained from sqliteMalloc()
   334         -*/
   335         -void sqlite3FreeX(void *p){
   336         -  if( p ){
   337         -    free(p);
   338         -  }
   339         -}
   340         -
   341         -/*
   342         -** Resize a prior allocation.  If p==0, then this routine
   343         -** works just like sqliteMalloc().  If n==0, then this routine
   344         -** works just like sqliteFree().
   345         -*/
   346         -void *sqlite3Realloc(void *p, int n){
   347         -  void *p2;
   348         -  if( p==0 ){
   349         -    return sqliteMalloc(n);
   350         -  }
   351         -  if( n==0 ){
   352         -    sqliteFree(p);
   353         -    return 0;
   354         -  }
   355         -  p2 = realloc(p, n);
   356         -  if( p2==0 ){
   357         -    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   358         -  }
   359         -  return p2;
   360         -}
   361         -
   362         -/*
   363         -** Make a copy of a string in memory obtained from sqliteMalloc()
          552  +void sqlite3ReallocOrFree(void **pp, int n){
          553  +  void *p = sqlite3Realloc(*pp, n);
          554  +  if( !p ){
          555  +    sqlite3FreeX(*pp);
          556  +  }
          557  +  *pp = p;
          558  +}
          559  +
          560  +/*
          561  +** Make a copy of a string in memory obtained from sqliteMalloc(). These 
          562  +** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
          563  +** is because when memory debugging is turned on, these two functions are 
          564  +** called via macros that record the current file and line number in the
          565  +** SqliteTsd structure.
   364    566   */
   365    567   char *sqlite3StrDup(const char *z){
   366    568     char *zNew;
   367    569     if( z==0 ) return 0;
   368         -  zNew = sqliteMallocRaw(strlen(z)+1);
          570  +  zNew = sqlite3MallocRaw(strlen(z)+1);
   369    571     if( zNew ) strcpy(zNew, z);
   370    572     return zNew;
   371    573   }
   372    574   char *sqlite3StrNDup(const char *z, int n){
   373    575     char *zNew;
   374    576     if( z==0 ) return 0;
   375         -  zNew = sqliteMallocRaw(n+1);
          577  +  zNew = sqlite3MallocRaw(n+1);
   376    578     if( zNew ){
   377    579       memcpy(zNew, z, n);
   378    580       zNew[n] = 0;
   379    581     }
   380    582     return zNew;
   381    583   }
   382         -#endif /* !defined(SQLITE_MEMDEBUG) */
   383         -
   384         -/*
   385         -** Reallocate a buffer to a different size.  This is similar to
   386         -** sqliteRealloc() except that if the allocation fails the buffer
   387         -** is freed.
   388         -*/
   389         -void sqlite3ReallocOrFree(void **ppBuf, int newSize){
   390         -  void *pNew = sqliteRealloc(*ppBuf, newSize);
   391         -  if( pNew==0 ){
   392         -    sqliteFree(*ppBuf);
   393         -  }
   394         -  *ppBuf = pNew;
   395         -}
   396    584   
   397    585   /*
   398    586   ** Create a string from the 2nd and subsequent arguments (up to the
   399    587   ** first NULL argument), store the string in memory obtained from
   400    588   ** sqliteMalloc() and make the pointer indicated by the 1st argument
   401    589   ** point to that string.  The 1st argument must either be NULL or 
   402    590   ** point to memory obtained from sqliteMalloc().
................................................................................
   422    610     *zResult = 0;
   423    611     va_start(ap, pz);
   424    612     while( (z = va_arg(ap, const char*))!=0 ){
   425    613       strcpy(zResult, z);
   426    614       zResult += strlen(zResult);
   427    615     }
   428    616     va_end(ap);
   429         -#ifdef SQLITE_MEMDEBUG
   430         -#if SQLITE_MEMDEBUG>1
   431         -  fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
   432         -#endif
   433         -#endif
   434    617   }
   435    618   
   436    619   /*
   437    620   ** Set the most recent error code and error string for the sqlite
   438    621   ** handle "db". The error code is set to "err_code".
   439    622   **
   440    623   ** If it is not NULL, string zFormat specifies the format of the
................................................................................
  1022   1205     return p;
  1023   1206   }
  1024   1207   #endif
  1025   1208   
  1026   1209   /*
  1027   1210   ** Return a pointer to the SqliteTsd associated with the calling thread.
  1028   1211   */
  1029         -static SqliteTsd tsd = { 0 };
         1212  +static SqliteTsd tsd = {
         1213  +  0                    /* mallocFailed flag */
         1214  +#ifndef NDEBUG
         1215  +  , 1                  /* mallocAllowed flag */
         1216  +#endif
         1217  +#ifndef SQLITE_MEMDEBUG
         1218  +  , 0
         1219  +  , 0
         1220  +  , 0
         1221  +  , 0
         1222  +#endif
         1223  +};
  1030   1224   SqliteTsd *sqlite3Tsd(){
  1031   1225     return &tsd;
  1032   1226   }
  1033   1227   
  1034         -void sqlite3ClearMallocFailed(){
         1228  +void sqlite3MallocClearFailed(){
  1035   1229     sqlite3Tsd()->mallocFailed = 0;
  1036   1230   }
  1037   1231   
         1232  +#ifndef NDEBUG
         1233  +/*
         1234  +** This function sets a flag in the thread-specific-data structure that will
         1235  +** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
         1236  +*/
         1237  +void sqlite3MallocDisallow(){
         1238  +  assert(sqlite3Tsd()->mallocAllowed);
         1239  +  sqlite3Tsd()->mallocAllowed = 0;
         1240  +}
         1241  +
         1242  +/*
         1243  +** This function clears the flag set in the thread-specific-data structure set
         1244  +** by sqlite3MallocDisallow().
         1245  +*/
         1246  +void sqlite3MallocAllow(){
         1247  +  assert(!sqlite3Tsd()->mallocAllowed);
         1248  +  sqlite3Tsd()->mallocAllowed = 1;
         1249  +}
         1250  +#endif
  1038   1251   
  1039   1252   

Changes to src/vacuum.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the VACUUM command.
    13     13   **
    14     14   ** Most of the code in this file may be omitted by defining the
    15     15   ** SQLITE_OMIT_VACUUM macro.
    16     16   **
    17         -** $Id: vacuum.c,v 1.51 2005/12/06 17:48:32 danielk1977 Exp $
           17  +** $Id: vacuum.c,v 1.52 2005/12/09 14:25:09 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "vdbeInt.h"
    21     21   #include "os.h"
    22     22   
    23     23   #ifndef SQLITE_OMIT_VACUUM
    24     24   /*
................................................................................
   307    307     ** by manually setting the autoCommit flag to true and detaching the
   308    308     ** vacuum database. The vacuum_db journal file is deleted when the pager
   309    309     ** is closed by the DETACH.
   310    310     */
   311    311     db->autoCommit = 1;
   312    312   
   313    313     if( pDetach ){
          314  +    int mf = sqlite3Tsd()->mallocFailed;
          315  +    sqlite3Tsd()->mallocFailed = 0;
          316  +    sqlite3MallocDisallow();
   314    317       ((Vdbe *)pDetach)->expired = 0;
   315    318       sqlite3_step(pDetach);
   316    319       rc2 = sqlite3_finalize(pDetach);
   317    320       if( rc==SQLITE_OK ){
   318    321         rc = rc2;
   319    322       }
          323  +    sqlite3MallocAllow();
          324  +    sqlite3Tsd()->mallocFailed = mf;
   320    325     }
   321    326   
   322    327     /* If one of the execSql() calls above returned SQLITE_NOMEM, then the
   323    328     ** mallocFailed flag will be clear (because execSql() calls sqlite3_exec()).
   324    329     ** Fix this so the flag and return code match.
   325    330     */
   326    331     if( rc==SQLITE_NOMEM ){

Changes to src/vdbe.c.

    39     39   **
    40     40   ** Various scripts scan this source file in order to generate HTML
    41     41   ** documentation, headers files, or other derived files.  The formatting
    42     42   ** of the code in this file is, therefore, important.  See other comments
    43     43   ** in this file for details.  If in doubt, do not deviate from existing
    44     44   ** commenting and indentation practices when changing or adding code.
    45     45   **
    46         -** $Id: vdbe.c,v 1.502 2005/12/06 12:53:01 danielk1977 Exp $
           46  +** $Id: vdbe.c,v 1.503 2005/12/09 14:25:09 danielk1977 Exp $
    47     47   */
    48     48   #include "sqliteInt.h"
    49     49   #include "os.h"
    50     50   #include <ctype.h>
    51     51   #include "vdbeInt.h"
    52     52   
    53     53   /*
................................................................................
   386    386   #endif
   387    387   #ifndef NDEBUG
   388    388     Mem *pStackLimit;
   389    389   #endif
   390    390   
   391    391     if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
   392    392     assert( db->magic==SQLITE_MAGIC_BUSY );
          393  +  pTos = p->pTos;
          394  +  if( p->rc==SQLITE_NOMEM ){
          395  +    /* This happens if a malloc() inside a call to sqlite3_column_text() or
          396  +    ** sqlite3_column_text16() failed.  */
          397  +    goto no_mem;
          398  +  }
   393    399     assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   394    400     p->rc = SQLITE_OK;
   395    401     assert( p->explain==0 );
   396         -  pTos = p->pTos;
   397         -  if( sqlite3Tsd()->mallocFailed ) goto no_mem;
   398    402     if( p->popStack ){
   399    403       popStack(&pTos, p->popStack);
   400    404       p->popStack = 0;
   401    405     }
   402    406     p->resOnStack = 0;
   403    407     db->busyHandler.nBusy = 0;
   404    408     CHECK_FOR_INTERRUPT;
................................................................................
  3894   3898        pOp->p1, db->aDb[iDb].zName, zMaster, pOp->p3);
  3895   3899     if( zSql==0 ) goto no_mem;
  3896   3900     sqlite3SafetyOff(db);
  3897   3901     assert( db->init.busy==0 );
  3898   3902     db->init.busy = 1;
  3899   3903     assert(0==sqlite3Tsd()->mallocFailed);
  3900   3904     rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
         3905  +  sqliteFree(zSql);
  3901   3906     db->init.busy = 0;
  3902   3907     sqlite3SafetyOn(db);
  3903   3908     if( rc==SQLITE_NOMEM ){
  3904   3909       sqlite3Tsd()->mallocFailed = 1;
  3905   3910       goto no_mem;
  3906   3911     }
  3907         -  sqliteFree(zSql);
  3908   3912     break;  
  3909   3913   }
  3910   3914   
  3911   3915   #ifndef SQLITE_OMIT_ANALYZE
  3912   3916   /* Opcode: LoadAnalysis P1 * *
  3913   3917   **
  3914   3918   ** Read the sqlite_stat1 table for database P1 and load the content

Changes to src/vdbeapi.c.

   237    237       assert( p->aOp[p->nOp-1].p3!=0 );
   238    238       assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
   239    239       db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
   240    240     }
   241    241   #endif
   242    242   
   243    243     sqlite3Error(p->db, rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
   244         -  sqlite3ClearMallocFailed();
          244  +  sqlite3MallocClearFailed();
   245    245     return rc;
   246    246   }
   247    247   
   248    248   /*
   249    249   ** Extract the user data from a sqlite3_context structure and return a
   250    250   ** pointer to it.
   251    251   */
................................................................................
   373    373       static Mem nullMem;
   374    374       if( nullMem.flags==0 ){ nullMem.flags = MEM_Null; }
   375    375       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   376    376       return &nullMem;
   377    377     }
   378    378     return &pVm->pTos[(1-vals)+i];
   379    379   }
          380  +
          381  +/*
          382  +** This function is called after invoking an sqlite3_value_XXX function on a 
          383  +** column value (i.e. a value returned by evaluating an SQL expression in the
          384  +** select list of a SELECT statement) that may cause a malloc() failure. If 
          385  +** malloc() has failed, the threads mallocFailed flag is cleared and the result
          386  +** code of statement pStmt set to SQLITE_NOMEM.
          387  +**
          388  +** Specificly, this is called from within:
          389  +**
          390  +**     sqlite3_column_int()
          391  +**     sqlite3_column_int64()
          392  +**     sqlite3_column_text()
          393  +**     sqlite3_column_text16()
          394  +**     sqlite3_column_real()
          395  +**     sqlite3_column_bytes()
          396  +**     sqlite3_column_bytes16()
          397  +**
          398  +** But not for sqlite3_column_blob(), which never calls malloc().
          399  +*/
          400  +static void columnMallocFailure(sqlite3_stmt *pStmt)
          401  +{
          402  +  /* If malloc() failed during an encoding conversion within an
          403  +  ** sqlite3_column_XXX API, then set the return code of the statement to
          404  +  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
          405  +  ** and _finalize() will return NOMEM.
          406  +  */
          407  +  if( sqlite3Tsd()->mallocFailed ){
          408  +    ((Vdbe *)pStmt)->rc = SQLITE_NOMEM;
          409  +    sqlite3MallocClearFailed();
          410  +  }
          411  +}
   380    412   
   381    413   /**************************** sqlite3_column_  *******************************
   382    414   ** The following routines are used to access elements of the current row
   383    415   ** in the result set.
   384    416   */
   385    417   const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   386         -  return sqlite3_value_blob( columnMem(pStmt,i) );
          418  +  const void *val;
          419  +  sqlite3MallocDisallow();
          420  +  val = sqlite3_value_blob( columnMem(pStmt,i) );
          421  +  sqlite3MallocAllow();
          422  +  return val;
   387    423   }
   388    424   int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   389         -  return sqlite3_value_bytes( columnMem(pStmt,i) );
          425  +  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
          426  +  columnMallocFailure(pStmt);
          427  +  return val;
   390    428   }
   391    429   int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   392         -  return sqlite3_value_bytes16( columnMem(pStmt,i) );
          430  +  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
          431  +  columnMallocFailure(pStmt);
          432  +  return val;
   393    433   }
   394    434   double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   395         -  return sqlite3_value_double( columnMem(pStmt,i) );
          435  +  double val = sqlite3_value_double( columnMem(pStmt,i) );
          436  +  columnMallocFailure(pStmt);
          437  +  return val;
   396    438   }
   397    439   int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   398         -  return sqlite3_value_int( columnMem(pStmt,i) );
          440  +  int val = sqlite3_value_int( columnMem(pStmt,i) );
          441  +  columnMallocFailure(pStmt);
          442  +  return val;
   399    443   }
   400    444   sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   401         -  return sqlite3_value_int64( columnMem(pStmt,i) );
          445  +  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
          446  +  columnMallocFailure(pStmt);
          447  +  return val;
   402    448   }
   403    449   const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   404         -  return sqlite3_value_text( columnMem(pStmt,i) );
          450  +  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
          451  +  columnMallocFailure(pStmt);
          452  +  return val;
   405    453   }
   406    454   #if 0
   407    455   sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   408    456     return columnMem(pStmt, i);
   409    457   }
   410    458   #endif
   411    459   #ifndef SQLITE_OMIT_UTF16
   412    460   const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   413         -  return sqlite3_value_text16( columnMem(pStmt,i) );
          461  +  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
          462  +  columnMallocFailure(pStmt);
          463  +  return val;
   414    464   }
   415    465   #endif /* SQLITE_OMIT_UTF16 */
   416    466   int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   417    467     return sqlite3_value_type( columnMem(pStmt,i) );
   418    468   }
   419    469   
   420    470   /*
................................................................................
   448    498     }
   449    499     N += useType*n;
   450    500     ret = xFunc(&p->aColName[N]);
   451    501   
   452    502     /* A malloc may have failed inside of the xFunc() call. If this is the case,
   453    503     ** clear the mallocFailed flag and return NULL.
   454    504     */
   455         -  sqlite3ClearMallocFailed();
          505  +  sqlite3MallocClearFailed();
   456    506     return ret;
   457    507   }
   458         -
   459    508   
   460    509   /*
   461    510   ** Return the name of the Nth column of the result set returned by SQL
   462    511   ** statement pStmt.
   463    512   */
   464    513   const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   465    514     return columnName(pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, 0);

Changes to src/vdbeaux.c.

   411    411   ** the Vdbe. In these cases we can just copy the pointer.
   412    412   **
   413    413   ** If addr<0 then change P3 on the most recently inserted instruction.
   414    414   */
   415    415   void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
   416    416     Op *pOp;
   417    417     assert( p->magic==VDBE_MAGIC_INIT );
   418         -  if( p==0 || p->aOp==0 ){
          418  +  if( p==0 || p->aOp==0 || sqlite3Tsd()->mallocFailed ){
   419    419       if (n != P3_KEYINFO) {
   420    420         freeP3(n, (void*)*(char**)&zP3);
   421    421       }
   422    422       return;
   423    423     }
   424    424     if( addr<0 || addr>=p->nOp ){
   425    425       addr = p->nOp - 1;
................................................................................
   466    466   /*
   467    467   ** Replace the P3 field of the most recently coded instruction with
   468    468   ** comment text.
   469    469   */
   470    470   void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   471    471     va_list ap;
   472    472     assert( p->nOp>0 );
   473         -  assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 );
          473  +  assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || sqlite3Tsd()->mallocFailed );
   474    474     va_start(ap, zFormat);
   475    475     sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
   476    476     va_end(ap);
   477    477   }
   478    478   #endif
   479    479   
   480    480   /*

Changes to test/malloc3.test.

     9      9   #
    10     10   #***********************************************************************
    11     11   #
    12     12   # This file contains tests to ensure that the library handles malloc() failures
    13     13   # correctly. The emphasis of these tests are the _prepare(), _step() and
    14     14   # _finalize() calls.
    15     15   #
    16         -# $Id: malloc3.test,v 1.3 2005/12/07 06:27:45 danielk1977 Exp $
           16  +# $Id: malloc3.test,v 1.4 2005/12/09 14:25:12 danielk1977 Exp $
    17     17   
    18     18   set testdir [file dirname $argv0]
    19     19   source $testdir/tester.tcl
    20     20   
    21     21   # Only run these tests if memory debugging is turned on.
    22     22   if {[info command sqlite_malloc_stat]==""} {
    23     23      puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
................................................................................
   576    576   # puts "PREP $iterid $v"
   577    577           db eval $v
   578    578           incr pc
   579    579         }
   580    580   
   581    581         default { error "Unknown switch: $k" }
   582    582       }
          583  +# if {$iFail > ($iFailStart+1)} return
   583    584     }
   584    585   }
   585    586   
   586    587   # Turn of the Tcl interface's prepared statement caching facility.
   587    588   db cache size 0
   588    589   
   589         -#run_test $::run_test_script 59 97 
   590         -run_test $::run_test_script
          590  +run_test $::run_test_script 
          591  +# run_test [lrange $::run_test_script 0 3] 0 63
   591    592   sqlite_malloc_fail 0
          593  +db close
          594  +
          595  +pp_check_for_leaks
          596  +
   592    597   finish_test
   593    598   

Changes to test/malloc4.test.

     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   #
    12     12   # This file contains tests to ensure that the library handles malloc() failures
    13     13   # correctly. The emphasis in this file is on sqlite3_column_XXX() APIs.
    14     14   #
    15         -# $Id: malloc4.test,v 1.1 2005/12/07 06:27:45 danielk1977 Exp $
           15  +# $Id: malloc4.test,v 1.2 2005/12/09 14:25:12 danielk1977 Exp $
    16     16   
    17     17   #---------------------------------------------------------------------------
    18     18   # NOTES ON EXPECTED BEHAVIOUR
           19  +#
           20  +# [193] When a memory allocation failure occurs during sqlite3_column_name(),
           21  +#       sqlite3_column_name16(), sqlite3_column_decltype(), or
           22  +#       sqlite3_column_decltype16() the function shall return NULL.
    19     23   #
    20     24   #---------------------------------------------------------------------------
    21     25   
    22     26   set testdir [file dirname $argv0]
    23     27   source $testdir/tester.tcl
    24     28   
    25     29   # Only run these tests if memory debugging is turned on.
    26     30   if {[info command sqlite_malloc_stat]==""} {
    27     31      puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
    28     32      finish_test
    29     33      return
    30     34   }
    31         -
    32     35   
    33     36   proc do_stmt_test {id sql} {
    34     37     set ::sql $sql
    35     38     set go 1
    36     39     for {set n 1} {$go} {incr n} {
    37     40       set testid "malloc4-$id.(iFail $n)"
    38     41   
................................................................................
    44     47   
    45     48       # Set the Nth malloc() to fail.
    46     49       sqlite_malloc_fail $n
    47     50   
    48     51       # Test malloc failure in the _name(), _name16(), decltype() and
    49     52       # decltype16() APIs. Calls that occur after the malloc() failure should
    50     53       # return NULL. No error is raised though.
           54  +    #
           55  +    # ${testid}.2.1 - Call _name()
           56  +    # ${testid}.2.2 - Call _name16()
           57  +    # ${testid}.2.3 - Call _name()
           58  +    # ${testid}.2.4 - Check that the return values of the above three calls are
           59  +    #                 consistent with each other and with the simulated
           60  +    #                 malloc() failures.
           61  +    #
           62  +    # Because the code that implements the _decltype() and _decltype16() APIs
           63  +    # is the same as the _name() and _name16() implementations, we don't worry
           64  +    # about explicitly testing them.
           65  +    #
    51     66       do_test ${testid}.2.1 {
    52     67         set mf1 [expr [lindex [sqlite_malloc_stat] 2] <= 0]
    53     68         set ::name8  [sqlite3_column_name $::STMT 0]
    54     69         set mf2 [expr [lindex [sqlite_malloc_stat] 2] <= 0]
    55     70         expr {$mf1 == $mf2 || $::name8 == ""}
    56     71       } {1}
    57     72       do_test ${testid}.2.2 {
................................................................................
    74     89           $::name8 == $::name8_2 && $::name16 == $::name8 && !$::mallocFailed ||
    75     90           $::name8 == $::name8_2 && $::name16 == "" &&        $::mallocFailed ||
    76     91           $::name8 == $::name16 && $::name8_2 == "" &&        $::mallocFailed ||
    77     92           $::name8_2 == $::name16 && $::name8 == "" &&        $::mallocFailed
    78     93         }
    79     94       } {1}
    80     95   
    81         -    if {$::mallocFailed == 0} {
           96  +    # Step the statement so that we can call _text() and _text16().  Before
           97  +    # running sqlite3_step(), make sure that malloc() is not about to fail.
           98  +    # Memory allocation failures that occur within sqlite3_step() are tested
           99  +    # elsewhere.
          100  +    set mf [lindex [sqlite_malloc_stat] 2]
          101  +    sqlite_malloc_fail 0
          102  +    do_test ${testid}.3 {
          103  +      sqlite3_step $::STMT
          104  +    } {SQLITE_ROW}
          105  +    sqlite_malloc_fail $mf
          106  +
          107  +    # Test for malloc() failures within _text() and _text16().
          108  +    #
          109  +    do_test ${testid}.4.1 {
          110  +      set ::text8 [sqlite3_column_text $::STMT 0]
          111  +      set mf [expr [lindex [sqlite_malloc_stat] 2] <= 0 && !$::mallocFailed]
          112  +      expr {$mf==0 || $::text8 == ""}
          113  +    } {1}
          114  +    do_test ${testid}.4.2 {
          115  +      set ::text16 [sqlite3_column_text16 $::STMT 0]
          116  +      set ::text16 [encoding convertfrom unicode $::text16]
          117  +      set ::text16 [string range $::text16 0 end-1]
          118  +      set mf [expr [lindex [sqlite_malloc_stat] 2] <= 0 && !$::mallocFailed]
          119  +      expr {$mf==0 || $::text16 == ""}
          120  +    } {1}
          121  +    do_test ${testid}.4.3 {
          122  +      set ::text8_2 [sqlite3_column_text $::STMT 0]
          123  +      set mf [expr [lindex [sqlite_malloc_stat] 2] <= 0 && !$::mallocFailed]
          124  +      expr {$mf==0 || $::text8_2 == "" || ($::text16 == "" && $::text8 != "")}
          125  +    } {1}
          126  +
          127  +    # Test for malloc() failures within _int(), _int64() and _real(). The only
          128  +    # way this can occur is if the string has to be translated from UTF-16 to
          129  +    # UTF-8 before being converted to a numeric value.
          130  +    do_test ${testid}.4.4.1 {
          131  +      set mf [lindex [sqlite_malloc_stat] 2]
          132  +      sqlite_malloc_fail 0
          133  +      sqlite3_column_text16 $::STMT 0
          134  +      sqlite_malloc_fail $mf
          135  +      sqlite3_column_int $::STMT 0
          136  +    } {0}
          137  +    do_test ${testid}.4.5 {
          138  +      set mf [lindex [sqlite_malloc_stat] 2]
          139  +      sqlite_malloc_fail 0
          140  +      sqlite3_column_text16 $::STMT 0
          141  +      sqlite_malloc_fail $mf
          142  +      sqlite3_column_int64 $::STMT 0
          143  +    } {0}
          144  +
          145  +    do_test ${testid}.4.6 {
          146  +      set mf [lindex [sqlite_malloc_stat] 2]
          147  +      sqlite_malloc_fail 0
          148  +      sqlite3_column_text16 $::STMT 0
          149  +      sqlite_malloc_fail $mf
          150  +      sqlite3_column_double $::STMT 0
          151  +    } {0.0}
          152  +
          153  +    set mallocFailedAfterStep [expr \
          154  +      [lindex [sqlite_malloc_stat] 2] <= 0 && !$::mallocFailed
          155  +    ]
          156  +
          157  +    sqlite_malloc_fail 0
          158  +    # Test that if a malloc() failed the next call to sqlite3_step() returns
          159  +    # SQLITE_ERROR. If malloc() did not fail, it should return SQLITE_DONE.
          160  +    #
          161  +    do_test ${testid}.5 {
          162  +      sqlite3_step $::STMT
          163  +    } [expr {$mallocFailedAfterStep ? "SQLITE_ERROR" : "SQLITE_DONE"}]
          164  +
          165  +    do_test ${testid}.6 {
          166  +      sqlite3_finalize $::STMT
          167  +    } [expr {$mallocFailedAfterStep ? "SQLITE_NOMEM" : "SQLITE_OK"}]
          168  +
          169  +    if {$::mallocFailed == 0 && $mallocFailedAfterStep == 0} {
    82    170         sqlite_malloc_fail 0
    83    171         set go 0
    84    172       }
    85         -
    86         -if 0 {
    87         -    # Test that if a malloc() failed the next call to sqlite3_step() returns
    88         -    # SQLITE_ERROR. If malloc() did not fail, it should return SQLITE_ROW.
    89         -    #
    90         -    # Before running sqlite3_step(), make sure that malloc() is not about to
    91         -    # fail. Memory allocation failures that occur within sqlite3_step() are
    92         -    # tested elsewhere.
    93         -    do_test ${testid}.3 {
    94         -      set rc [sqlite3_step $::STMT]
    95         -      list [expr $rc=="SQLITE_ERROR"] [expr $rc=="SQLITE_ROW"]
    96         -    } [list $mallocFailed [expr !$mallocFailed]]
    97         -}
    98         -
    99         -    do_test ${testid}.4 {
   100         -      sqlite3_finalize $::STMT
   101         -    } {SQLITE_OK}
   102    173     }
   103    174   }
   104    175   
   105    176   execsql {
   106    177     CREATE TABLE tbl(
   107    178       the_first_reasonably_long_column_name that_also_has_quite_a_lengthy_type
   108    179     );
          180  +  INSERT INTO tbl VALUES(
          181  +    'An extra long string. Far too long to be stored in NBFS bytes.'
          182  +  );
   109    183   }
          184  +
   110    185   do_stmt_test 1 "SELECT * FROM tbl"
   111    186   
   112    187   sqlite_malloc_fail 0
   113    188   finish_test
   114    189   

Changes to test/select1.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this file is testing the SELECT statement.
    13     13   #
    14         -# $Id: select1.test,v 1.43 2005/09/08 10:37:01 drh Exp $
           14  +# $Id: select1.test,v 1.44 2005/12/09 14:25:12 danielk1977 Exp $
    15     15   
    16     16   set testdir [file dirname $argv0]
    17     17   source $testdir/tester.tcl
    18     18   
    19     19   # Try to select on a non-existant table.
    20     20   #
    21     21   do_test select1-1.1 {
................................................................................
   794    794       execsql2 {
   795    795         SELECT z.x FROM (
   796    796           SELECT a,b FROM t3 UNION SELECT a AS 'x', b AS 'y' FROM t4 ORDER BY a,b
   797    797         ) AS 'z' ORDER BY x;
   798    798       }
   799    799     } {x 1 x 3}
   800    800   } ;# ifcapable compound
   801         -
   802    801   
   803    802   finish_test

Changes to test/tester.tcl.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements some common TCL routines used for regression
    12     12   # testing the SQLite library
    13     13   #
    14         -# $Id: tester.tcl,v 1.52 2005/11/26 00:25:04 drh Exp $
           14  +# $Id: tester.tcl,v 1.53 2005/12/09 14:25:12 danielk1977 Exp $
    15     15   
    16     16   # Make sure tclsqlite3 was compiled correctly.  Abort now with an
    17     17   # error message if not.
    18     18   #
    19     19   if {[sqlite3 -tcl-uses-utf]} {
    20     20     if {"\u1234"=="u1234"} {
    21     21       puts stderr "***** BUILD PROBLEM *****"
................................................................................
    79     79   set failList {}
    80     80   set maxErr 1000
    81     81   
    82     82   # Invoke the do_test procedure to run a single test 
    83     83   #
    84     84   proc do_test {name cmd expected} {
    85     85     global argv nErr nTest skip_test maxErr
           86  +  set ::sqlite_malloc_id $name
    86     87     if {$skip_test} {
    87     88       set skip_test 0
    88     89       return
    89     90     }
    90     91     if {[llength $argv]==0} { 
    91     92       set go 1
    92     93     } else {
................................................................................
   135    136   #
   136    137   proc finish_test {} {
   137    138     finalize_testing
   138    139   }
   139    140   proc finalize_testing {} {
   140    141     global nTest nErr nProb sqlite_open_file_count
   141    142     if {$nErr==0} memleak_check
          143  +
   142    144     catch {db close}
          145  +  catch {db2 close}
          146  +  catch {db3 close}
          147  +
          148  +pp_check_for_leaks
          149  +
   143    150     puts "$nErr errors out of $nTest tests"
   144    151     puts "Failures on these tests: $::failList"
   145    152     if {$nProb>0} {
   146    153       puts "$nProb probabilistic tests also failed, but this does"
   147    154       puts "not necessarily indicate a malfunction."
   148    155     }
   149    156     if 0 {
................................................................................
   418    425       set t [open $to w]
   419    426       fconfigure $t -translation binary
   420    427       puts -nonewline $t [read $f [file size $from]]
   421    428       close $t
   422    429       close $f
   423    430     }
   424    431   }
          432  +
          433  +# This command checks for outstanding calls to sqliteMalloc() from within
          434  +# the current thread. A list is returned with one entry for each outstanding
          435  +# malloc. Each list entry is itself a list of 5 items, as follows:
          436  +#
          437  +#     { <number-bytes> <file-name> <line-number> <test-case> <stack-dump> }
          438  +#
          439  +proc check_for_leaks {} {
          440  +  set ret [list]
          441  +  foreach alloc [sqlite_malloc_outstanding] {
          442  +    foreach {nBytes file iLine userstring backtrace} $alloc {}
          443  +    set stack [list]
          444  +    set skip 0
          445  +
          446  +    # The first command in this block will probably fail on windows. This
          447  +    # means there will be no stack dump available.
          448  +    catch {
          449  +      set stuff [eval "exec addr2line -e ./testfixture -f $backtrace"]
          450  +      foreach {func line} $stuff {
          451  +        if {$func != "??" || $line != "??:0"} {
          452  +          regexp {.*/(.*)} $line dummy line
          453  +          lappend stack "${func}() $line"
          454  +        } else {
          455  +          if {[lindex $stack end] != "..."} {
          456  +            lappend stack "..."
          457  +          }
          458  +        }
          459  +      }
          460  +    }
          461  +
          462  +    if {!$skip} {
          463  +      lappend ret [list $nBytes $file $iLine $userstring $stack]
          464  +    }
          465  +  }
          466  +  return $ret
          467  +}
          468  +
          469  +# Pretty print a report based on the return value of [check_for_leaks] to
          470  +# stdout.
          471  +proc pp_check_for_leaks {} {
          472  +  set l [check_for_leaks]
          473  +  set n 0
          474  +  foreach leak $l {
          475  +    foreach {nBytes file iLine userstring stack} $leak {}
          476  +    puts "$nBytes bytes leaked at $file:$iLine ($userstring)"
          477  +    foreach frame $stack {
          478  +      puts "        $frame"
          479  +    }
          480  +    incr n $nBytes
          481  +  }
          482  +  puts "Memory leaked: $n bytes in [llength $l] allocations"
          483  +  puts ""
          484  +}
   425    485   
   426    486   # If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
   427    487   # to non-zero, then set the global variable $AUTOVACUUM to 1.
   428    488   set AUTOVACUUM $sqlite_options(default_autovacuum)