/ Check-in [e38ef81b]
Login
SQLite training in Houston TX on 2019-11-05 (details)
Part of the 2019 Tcl Conference

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

Overview
Comment:Modifications to the malloc failure tests to test transient and persistent failures. (CVS 4321)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e38ef81b85feb5bff2ad8448f3438ff0ab36571e
User & Date: danielk1977 2007-08-29 12:31:26
Context
2007-08-29
13:45
Be careful to verify the schema cookie when running the xfer optimization on INSERT statements. (CVS 4322) check-in: d8ef7024 user: drh tags: trunk
12:31
Modifications to the malloc failure tests to test transient and persistent failures. (CVS 4321) check-in: e38ef81b user: danielk1977 tags: trunk
04:00
Better asserts(). But now some of the tests are busted again. (CVS 4320) check-in: e8060f85 user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/btree.c.

     5      5   ** a legal notice, here is a blessing:
     6      6   **
     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         -** $Id: btree.c,v 1.416 2007/08/29 04:00:58 drh Exp $
           12  +** $Id: btree.c,v 1.417 2007/08/29 12:31:26 danielk1977 Exp $
    13     13   **
    14     14   ** This file implements a external (disk-based) database using BTrees.
    15     15   ** See the header comment on "btreeInt.h" for additional information.
    16     16   ** Including a description of file format and an overview of operation.
    17     17   */
    18     18   #include "btreeInt.h"
    19     19   
................................................................................
  1208   1208       sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
  1209   1209       pBt->pCursor = 0;
  1210   1210       pBt->pPage1 = 0;
  1211   1211       pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
  1212   1212       pBt->pageSize = get2byte(&zDbHeader[16]);
  1213   1213       if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  1214   1214            || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  1215         -      pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, 0);
         1215  +      pBt->pageSize = 0;
         1216  +      sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  1216   1217         pBt->maxEmbedFrac = 64;   /* 25% */
  1217   1218         pBt->minEmbedFrac = 32;   /* 12.5% */
  1218   1219         pBt->minLeafFrac = 32;    /* 12.5% */
  1219   1220   #ifndef SQLITE_OMIT_AUTOVACUUM
  1220   1221         /* If the magic name ":memory:" will create an in-memory database, then
  1221   1222         ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  1222   1223         ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
................................................................................
  1238   1239   #ifndef SQLITE_OMIT_AUTOVACUUM
  1239   1240         pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  1240   1241         pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  1241   1242   #endif
  1242   1243       }
  1243   1244       pBt->usableSize = pBt->pageSize - nReserve;
  1244   1245       assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
  1245         -    sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);
         1246  +    sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  1246   1247      
  1247   1248   #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  1248   1249       /* Add the new BtShared object to the linked list sharable BtShareds.
  1249   1250       */
  1250   1251       if( p->sharable ){
  1251   1252         sqlite3_mutex *mutexShared;
  1252   1253         pBt->nRef = 1;
................................................................................
  1484   1485   ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  1485   1486   ** at the beginning of a page.
  1486   1487   **
  1487   1488   ** If parameter nReserve is less than zero, then the number of reserved
  1488   1489   ** bytes per page is left unchanged.
  1489   1490   */
  1490   1491   int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
         1492  +  int rc = SQLITE_OK;
  1491   1493     BtShared *pBt = p->pBt;
  1492   1494     sqlite3BtreeEnter(p);
  1493   1495     if( pBt->pageSizeFixed ){
  1494   1496       sqlite3BtreeLeave(p);
  1495   1497       return SQLITE_READONLY;
  1496   1498     }
  1497   1499     if( nReserve<0 ){
  1498   1500       nReserve = pBt->pageSize - pBt->usableSize;
  1499   1501     }
  1500   1502     if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  1501   1503           ((pageSize-1)&pageSize)==0 ){
  1502   1504       assert( (pageSize & 7)==0 );
  1503   1505       assert( !pBt->pPage1 && !pBt->pCursor );
  1504         -    pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
         1506  +    pBt->pageSize = pageSize;
         1507  +    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  1505   1508     }
  1506   1509     pBt->usableSize = pBt->pageSize - nReserve;
  1507   1510     sqlite3BtreeLeave(p);
  1508         -  return SQLITE_OK;
         1511  +  return rc;
  1509   1512   }
  1510   1513   
  1511   1514   /*
  1512   1515   ** Return the currently defined page size
  1513   1516   */
  1514   1517   int sqlite3BtreeGetPageSize(Btree *p){
  1515   1518     return p->pBt->pageSize;

Changes to src/build.c.

    18     18   **     CREATE INDEX
    19     19   **     DROP INDEX
    20     20   **     creating ID lists
    21     21   **     BEGIN TRANSACTION
    22     22   **     COMMIT
    23     23   **     ROLLBACK
    24     24   **
    25         -** $Id: build.c,v 1.440 2007/08/28 22:24:35 drh Exp $
           25  +** $Id: build.c,v 1.441 2007/08/29 12:31:26 danielk1977 Exp $
    26     26   */
    27     27   #include "sqliteInt.h"
    28     28   #include <ctype.h>
    29     29   
    30     30   /*
    31     31   ** This routine is called when a new SQL statement is beginning to
    32     32   ** be parsed.  Initialize the pParse structure as needed.
................................................................................
   237    237   
   238    238     if( pParse->nErr ) return;
   239    239     assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   240    240     va_start(ap, zFormat);
   241    241     zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
   242    242     va_end(ap);
   243    243     if( zSql==0 ){
          244  +    pParse->db->mallocFailed = 1;
   244    245       return;   /* A malloc must have failed */
   245    246     }
   246    247     pParse->nested++;
   247    248     memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   248    249     memset(&pParse->nVar, 0, SAVE_SZ);
   249    250     sqlite3RunParser(pParse, zSql, 0);
   250    251     sqlite3_free(zSql);
................................................................................
  1558   1559       if( pOld ){
  1559   1560         assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
  1560   1561         db->mallocFailed = 1;
  1561   1562         return;
  1562   1563       }
  1563   1564   #ifndef SQLITE_OMIT_FOREIGN_KEY
  1564   1565       for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
         1566  +      void *data;
  1565   1567         int nTo = strlen(pFKey->zTo) + 1;
  1566   1568         pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
  1567         -      sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
         1569  +      data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
         1570  +      if( data==(void *)pFKey ){
         1571  +        db->mallocFailed = 1;
         1572  +      }
  1568   1573       }
  1569   1574   #endif
  1570   1575       pParse->pNewTable = 0;
  1571   1576       db->nTable++;
  1572   1577       db->flags |= SQLITE_InternChanges;
  1573   1578   
  1574   1579   #ifndef SQLITE_OMIT_ALTERTABLE
................................................................................
  2379   2384       char zBuf[30];
  2380   2385       int n;
  2381   2386       Index *pLoop;
  2382   2387       for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  2383   2388       sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
  2384   2389       zName = 0;
  2385   2390       sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
  2386         -    if( zName==0 ) goto exit_create_index;
         2391  +    if( zName==0 ){
         2392  +      db->mallocFailed = 1;
         2393  +      goto exit_create_index;
         2394  +    }
  2387   2395     }
  2388   2396   
  2389   2397     /* Check for authorization to create an index.
  2390   2398     */
  2391   2399   #ifndef SQLITE_OMIT_AUTHORIZATION
  2392   2400     {
  2393   2401       const char *zDb = pDb->zName;

Changes to src/callback.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   **
    13     13   ** This file contains functions used to access the internal hash tables
    14     14   ** of user defined functions and collation sequences.
    15     15   **
    16         -** $Id: callback.c,v 1.22 2007/08/22 20:18:22 drh Exp $
           16  +** $Id: callback.c,v 1.23 2007/08/29 12:31:26 danielk1977 Exp $
    17     17   */
    18     18   
    19     19   #include "sqliteInt.h"
    20     20   
    21     21   /*
    22     22   ** Invoke the 'collation needed' callback to request a collation sequence
    23     23   ** in the database text encoding of name zName, length nName.
................................................................................
   357    357   /*
   358    358   ** Find and return the schema associated with a BTree.  Create
   359    359   ** a new one if necessary.
   360    360   */
   361    361   Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   362    362     Schema * p;
   363    363     if( pBt ){
   364         -    p = (Schema *)sqlite3BtreeSchema(pBt,sizeof(Schema),sqlite3SchemaFree);
          364  +    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
   365    365     }else{
   366         -    p = (Schema *)sqlite3DbMallocZero(db,sizeof(Schema));
          366  +    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
   367    367     }
   368         -  if( p && 0==p->file_format ){
          368  +  if( !p ){
          369  +    db->mallocFailed = 1;
          370  +  }else if ( 0==p->file_format ){
   369    371       sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
   370    372       sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
   371    373       sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
   372    374       sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
   373    375       p->enc = SQLITE_UTF8;
   374    376     }
   375    377     return p;
   376    378   }

Changes to src/expr.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 routines used for analyzing expressions and
    13     13   ** for generating VDBE code that evaluates expressions in SQLite.
    14     14   **
    15         -** $Id: expr.c,v 1.308 2007/08/22 20:18:22 drh Exp $
           15  +** $Id: expr.c,v 1.309 2007/08/29 12:31:26 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <ctype.h>
    19     19   
    20     20   /*
    21     21   ** Return the 'affinity' of the expression pExpr if any.
    22     22   **
................................................................................
   217    217   
   218    218   /*
   219    219   ** Construct a new expression node and return a pointer to it.  Memory
   220    220   ** for this node is obtained from sqlite3_malloc().  The calling function
   221    221   ** is responsible for making sure the node eventually gets freed.
   222    222   */
   223    223   Expr *sqlite3Expr(
          224  +  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   224    225     int op,                 /* Expression opcode */
   225    226     Expr *pLeft,            /* Left operand */
   226    227     Expr *pRight,           /* Right operand */
   227    228     const Token *pToken     /* Argument token */
   228    229   ){
   229    230     Expr *pNew;
   230         -  pNew = sqlite3MallocZero( sizeof(Expr) );
          231  +  pNew = sqlite3DbMallocZero(db, sizeof(Expr));
   231    232     if( pNew==0 ){
   232    233       /* When malloc fails, delete pLeft and pRight. Expressions passed to 
   233    234       ** this function must always be allocated with sqlite3Expr() for this 
   234    235       ** reason. 
   235    236       */
   236    237       sqlite3ExprDelete(pLeft);
   237    238       sqlite3ExprDelete(pRight);
................................................................................
   269    270   Expr *sqlite3PExpr(
   270    271     Parse *pParse,          /* Parsing context */
   271    272     int op,                 /* Expression opcode */
   272    273     Expr *pLeft,            /* Left operand */
   273    274     Expr *pRight,           /* Right operand */
   274    275     const Token *pToken     /* Argument token */
   275    276   ){
   276         -  Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
   277         -  if( pNew==0 ){
   278         -    pParse->db->mallocFailed = 1;
   279         -  }
   280         -  return pNew;
          277  +  return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
   281    278   }
   282    279   
   283    280   /*
   284    281   ** When doing a nested parse, you can include terms in an expression
   285    282   ** that look like this:   #0 #1 #2 ...  These terms refer to elements
   286    283   ** on the stack.  "#0" means the top of the stack.
   287    284   ** "#1" means the next down on the stack.  And so forth.
................................................................................
   293    290   */
   294    291   Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
   295    292     Vdbe *v = pParse->pVdbe;
   296    293     Expr *p;
   297    294     int depth;
   298    295     if( pParse->nested==0 ){
   299    296       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
   300         -    return sqlite3Expr(TK_NULL, 0, 0, 0);
          297  +    return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   301    298     }
   302    299     if( v==0 ) return 0;
   303         -  p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
          300  +  p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
   304    301     if( p==0 ){
   305         -    pParse->db->mallocFailed = 1;
   306    302       return 0;  /* Malloc failed */
   307    303     }
   308    304     depth = atoi((char*)&pToken->z[1]);
   309    305     p->iTable = pParse->nMem++;
   310    306     sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
   311    307     sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
   312    308     return p;
................................................................................
   318    314   */
   319    315   Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   320    316     if( pLeft==0 ){
   321    317       return pRight;
   322    318     }else if( pRight==0 ){
   323    319       return pLeft;
   324    320     }else{
   325         -    Expr *p = sqlite3Expr(TK_AND, pLeft, pRight, 0);
          321  +    Expr *p = sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
   326    322       if( p==0 ){
   327    323         db->mallocFailed = 1;
   328    324       }
   329    325       return p;
   330    326     }
   331    327   }
   332    328   
................................................................................
  1230   1226       if( zDb ){
  1231   1227         sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
  1232   1228       }else if( zTab ){
  1233   1229         sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
  1234   1230       }else{
  1235   1231         z = sqlite3StrDup(zCol);
  1236   1232       }
  1237         -    sqlite3ErrorMsg(pParse, zErr, z);
  1238         -    sqlite3_free(z);
  1239         -    pTopNC->nErr++;
         1233  +    if( z ){
         1234  +      sqlite3ErrorMsg(pParse, zErr, z);
         1235  +      sqlite3_free(z);
         1236  +      pTopNC->nErr++;
         1237  +    }else{
         1238  +      db->mallocFailed = 1;
         1239  +    }
  1240   1240     }
  1241   1241   
  1242   1242     /* If a column from a table in pSrcList is referenced, then record
  1243   1243     ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
  1244   1244     ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
  1245   1245     ** column number is greater than the number of bits in the bitmask
  1246   1246     ** then set the high-order bit of the bitmask.
................................................................................
  1664   1664           VdbeComment((v, "# Init subquery result"));
  1665   1665         }else{
  1666   1666           sop = SRT_Exists;
  1667   1667           sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
  1668   1668           VdbeComment((v, "# Init EXISTS result"));
  1669   1669         }
  1670   1670         sqlite3ExprDelete(pSel->pLimit);
  1671         -      pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
         1671  +      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
  1672   1672         if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
  1673   1673           return;
  1674   1674         }
  1675   1675         break;
  1676   1676       }
  1677   1677     }
  1678   1678   

Changes to src/func.c.

    12     12   ** This file contains the C functions that implement various SQL
    13     13   ** functions of SQLite.  
    14     14   **
    15     15   ** There is only one exported symbol in this file - the function
    16     16   ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
    17     17   ** All other code has file scope.
    18     18   **
    19         -** $Id: func.c,v 1.169 2007/08/23 02:47:53 drh Exp $
           19  +** $Id: func.c,v 1.170 2007/08/29 12:31:26 danielk1977 Exp $
    20     20   */
    21     21   #include "sqliteInt.h"
    22     22   #include <ctype.h>
    23     23   #include <stdlib.h>
    24     24   #include <assert.h>
    25     25   #include "vdbeInt.h"
    26     26   
................................................................................
   229    229     }
   230    230     if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   231    231     r = sqlite3_value_double(argv[0]);
   232    232     sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
   233    233     sqlite3AtoF(zBuf, &r);
   234    234     sqlite3_result_double(context, r);
   235    235   }
          236  +
          237  +static void *contextMalloc(sqlite3_context *context, int nByte){
          238  +  char *z = sqlite3_malloc(nByte);
          239  +  if( !z && nByte>0 ){
          240  +    sqlite3_result_error_nomem(context);
          241  +  }
          242  +  return z;
          243  +}
   236    244   
   237    245   /*
   238    246   ** Implementation of the upper() and lower() SQL functions.
   239    247   */
   240    248   static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   241    249     char *z1;
   242    250     const char *z2;
................................................................................
   243    251     int i, n;
   244    252     if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   245    253     z2 = (char*)sqlite3_value_text(argv[0]);
   246    254     n = sqlite3_value_bytes(argv[0]);
   247    255     /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   248    256     assert( z2==(char*)sqlite3_value_text(argv[0]) );
   249    257     if( z2 ){
   250         -    z1 = sqlite3_malloc(n+1);
          258  +    z1 = contextMalloc(context, n+1);
   251    259       if( z1 ){
   252    260         memcpy(z1, z2, n+1);
   253    261         for(i=0; z1[i]; i++){
   254    262           z1[i] = toupper(z1[i]);
   255    263         }
   256    264         sqlite3_result_text(context, z1, -1, sqlite3_free);
   257    265       }
................................................................................
   263    271     int i, n;
   264    272     if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   265    273     z2 = (char*)sqlite3_value_text(argv[0]);
   266    274     n = sqlite3_value_bytes(argv[0]);
   267    275     /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   268    276     assert( z2==(char*)sqlite3_value_text(argv[0]) );
   269    277     if( z2 ){
   270         -    z1 = sqlite3_malloc(n+1);
          278  +    z1 = contextMalloc(context, n+1);
   271    279       if( z1 ){
   272    280         memcpy(z1, z2, n+1);
   273    281         for(i=0; z1[i]; i++){
   274    282           z1[i] = tolower(z1[i]);
   275    283         }
   276    284         sqlite3_result_text(context, z1, -1, sqlite3_free);
   277    285       }
................................................................................
   328    336     if( n<1 ){
   329    337       n = 1;
   330    338     }
   331    339     if( n>SQLITE_MAX_LENGTH ){
   332    340       sqlite3_result_error_toobig(context);
   333    341       return;
   334    342     }
   335         -  p = sqlite3_malloc(n);
          343  +  p = contextMalloc(context, n);
   336    344     if( p ){
   337    345       sqlite3Randomness(n, p);
   338    346       sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   339    347     }
   340    348   }
   341    349   
   342    350   /*
................................................................................
   661    669         int nBlob = sqlite3_value_bytes(argv[0]);
   662    670         assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   663    671   
   664    672         if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
   665    673           sqlite3_result_error_toobig(context);
   666    674           return;
   667    675         }
   668         -      zText = (char *)sqlite3_malloc((2*nBlob)+4); 
   669         -      if( !zText ){
   670         -        sqlite3_result_error(context, "out of memory", -1);
   671         -      }else{
          676  +      zText = (char *)contextMalloc(context, (2*nBlob)+4); 
          677  +      if( zText ){
   672    678           int i;
   673    679           for(i=0; i<nBlob; i++){
   674    680             zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   675    681             zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   676    682           }
   677    683           zText[(nBlob*2)+2] = '\'';
   678    684           zText[(nBlob*2)+3] = '\0';
................................................................................
   691    697   
   692    698         if( zArg==0 ) return;
   693    699         for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   694    700         if( i+n+3>SQLITE_MAX_LENGTH ){
   695    701           sqlite3_result_error_toobig(context);
   696    702           return;
   697    703         }
   698         -      z = sqlite3_malloc( i+n+3 );
   699         -      if( z==0 ) return;
   700         -      z[0] = '\'';
   701         -      for(i=0, j=1; zArg[i]; i++){
   702         -        z[j++] = zArg[i];
   703         -        if( zArg[i]=='\'' ){
   704         -          z[j++] = '\'';
          704  +      z = contextMalloc(context, i+n+3);
          705  +      if( z ){
          706  +        z[0] = '\'';
          707  +        for(i=0, j=1; zArg[i]; i++){
          708  +          z[j++] = zArg[i];
          709  +          if( zArg[i]=='\'' ){
          710  +            z[j++] = '\'';
          711  +          }
   705    712           }
          713  +        z[j++] = '\'';
          714  +        z[j] = 0;
          715  +        sqlite3_result_text(context, z, j, sqlite3_free);
   706    716         }
   707         -      z[j++] = '\'';
   708         -      z[j] = 0;
   709         -      sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
   710         -      sqlite3_free(z);
   711    717       }
   712    718     }
   713    719   }
   714    720   
   715    721   /*
   716    722   ** The hex() function.  Interpret the argument as a blob.  Return
   717    723   ** a hexadecimal rendering as text.
................................................................................
   728    734     pBlob = sqlite3_value_blob(argv[0]);
   729    735     n = sqlite3_value_bytes(argv[0]);
   730    736     if( n*2+1>SQLITE_MAX_LENGTH ){
   731    737       sqlite3_result_error_toobig(context);
   732    738       return;
   733    739     }
   734    740     assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   735         -  z = zHex = sqlite3_malloc(n*2 + 1);
   736         -  if( zHex==0 ) return;
   737         -  for(i=0; i<n; i++, pBlob++){
   738         -    unsigned char c = *pBlob;
   739         -    *(z++) = hexdigits[(c>>4)&0xf];
   740         -    *(z++) = hexdigits[c&0xf];
          741  +  z = zHex = contextMalloc(context, n*2 + 1);
          742  +  if( zHex ){
          743  +    for(i=0; i<n; i++, pBlob++){
          744  +      unsigned char c = *pBlob;
          745  +      *(z++) = hexdigits[(c>>4)&0xf];
          746  +      *(z++) = hexdigits[c&0xf];
          747  +    }
          748  +    *z = 0;
          749  +    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   741    750     }
   742         -  *z = 0;
   743         -  sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   744    751   }
   745    752   
   746    753   /*
   747    754   ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   748    755   */
   749    756   static void zeroblobFunc(
   750    757     sqlite3_context *context,
................................................................................
   794    801     assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   795    802     zRep = sqlite3_value_text(argv[2]);
   796    803     if( zRep==0 ) return;
   797    804     nRep = sqlite3_value_bytes(argv[2]);
   798    805     assert( zRep==sqlite3_value_text(argv[2]) );
   799    806     nOut = nStr + 1;
   800    807     assert( nOut<SQLITE_MAX_LENGTH );
   801         -  zOut = sqlite3_malloc((int)nOut);
          808  +  zOut = contextMalloc(context, (int)nOut);
   802    809     if( zOut==0 ){
   803    810       return;
   804    811     }
   805    812     loopLimit = nStr - nPattern;  
   806    813     for(i=j=0; i<=loopLimit; i++){
   807    814       if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   808    815         zOut[j++] = zStr[i];
................................................................................
   813    820           sqlite3_result_error_toobig(context);
   814    821           sqlite3_free(zOut);
   815    822           return;
   816    823         }
   817    824         zOld = zOut;
   818    825         zOut = sqlite3_realloc(zOut, (int)nOut);
   819    826         if( zOut==0 ){
          827  +        sqlite3_result_error_nomem(context);
   820    828           sqlite3_free(zOld);
   821    829           return;
   822    830         }
   823    831         memcpy(&zOut[j], zRep, nRep);
   824    832         j += nRep;
   825    833         i += nPattern-1;
   826    834       }
................................................................................
   869    877       return;
   870    878     }else{
   871    879       const unsigned char *z;
   872    880       for(z=zCharSet, nChar=0; *z; nChar++){
   873    881         SQLITE_SKIP_UTF8(z);
   874    882       }
   875    883       if( nChar>0 ){
   876         -      azChar = sqlite3_malloc( nChar*(sizeof(char*)+1) );
          884  +      azChar = contextMalloc(context, nChar*(sizeof(char*)+1));
   877    885         if( azChar==0 ){
   878    886           return;
   879    887         }
   880    888         aLen = (unsigned char*)&azChar[nChar];
   881    889         for(z=zCharSet, nChar=0; *z; nChar++){
   882    890           azChar[nChar] = z;
   883    891           SQLITE_SKIP_UTF8(z);
................................................................................
  1106   1114   static void free_test_auxdata(void *p) {sqlite3_free(p);}
  1107   1115   static void test_auxdata(
  1108   1116     sqlite3_context *pCtx, 
  1109   1117     int nArg,
  1110   1118     sqlite3_value **argv
  1111   1119   ){
  1112   1120     int i;
  1113         -  char *zRet = sqlite3MallocZero(nArg*2);
         1121  +  char *zRet = contextMalloc(pCtx, nArg*2);
  1114   1122     if( !zRet ) return;
         1123  +  memset(zRet, 0, nArg*2);
  1115   1124     for(i=0; i<nArg; i++){
  1116   1125       char const *z = (char*)sqlite3_value_text(argv[i]);
  1117   1126       if( z ){
  1118   1127         char *zAux = sqlite3_get_auxdata(pCtx, i);
  1119   1128         if( zAux ){
  1120   1129           zRet[i*2] = '1';
  1121   1130           if( strcmp(zAux, z) ){
  1122   1131             free_test_auxdata((void *)zRet);
  1123   1132             sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
  1124   1133             return;
  1125   1134           }
  1126   1135         }else{
  1127   1136           zRet[i*2] = '0';
  1128         -        zAux = sqlite3StrDup(z);
  1129         -        sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
         1137  +        zAux = contextMalloc(pCtx, strlen(z)+1);
         1138  +        if( zAux ){
         1139  +          strcpy(zAux, z);
         1140  +          sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
         1141  +        }
  1130   1142         }
  1131   1143         zRet[i*2+1] = ' ';
  1132   1144       }
  1133   1145     }
  1134   1146     sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
  1135   1147   }
  1136   1148   #endif /* SQLITE_TEST */

Changes to src/hash.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 is the implementation of generic hash-tables
    13     13   ** used in SQLite.
    14     14   **
    15         -** $Id: hash.c,v 1.21 2007/08/16 10:09:03 danielk1977 Exp $
           15  +** $Id: hash.c,v 1.22 2007/08/29 12:31:26 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <assert.h>
    19     19   
    20     20   /* Turn bulk memory into a hash table object by initializing the
    21     21   ** fields of the Hash structure.
    22     22   **
................................................................................
   218    218   */
   219    219   static void rehash(Hash *pH, int new_size){
   220    220     struct _ht *new_ht;            /* The new hash table */
   221    221     HashElem *elem, *next_elem;    /* For looping over existing elements */
   222    222     int (*xHash)(const void*,int); /* The hash function */
   223    223   
   224    224     assert( (new_size & (new_size-1))==0 );
          225  +
          226  +  /* There is a call to sqlite3_malloc() inside rehash(). If there is
          227  +  ** already an allocation at pH->ht, then if this malloc() fails it
          228  +  ** is benign (since failing to resize a hash table is a performance
          229  +  ** hit only, not a fatal error).
          230  +  */
          231  +  sqlite3MallocBenignFailure(pH->htsize>0);
          232  +
   225    233     new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
   226    234     if( new_ht==0 ) return;
   227    235     if( pH->ht ) sqlite3_free(pH->ht);
   228    236     pH->ht = new_ht;
   229    237     pH->htsize = new_size;
   230    238     xHash = hashFunction(pH->keyClass);
   231    239     for(elem=pH->first, pH->first=0; elem; elem = next_elem){

Changes to src/legacy.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Main file for the SQLite library.  The routines in this file
    13     13   ** implement the programmer interface to the library.  Routines in
    14     14   ** other files are for internal use by SQLite and should not be
    15     15   ** accessed by users of the library.
    16     16   **
    17         -** $Id: legacy.c,v 1.21 2007/08/22 20:18:22 drh Exp $
           17  +** $Id: legacy.c,v 1.22 2007/08/29 12:31:26 danielk1977 Exp $
    18     18   */
    19     19   
    20     20   #include "sqliteInt.h"
    21     21   #include <ctype.h>
    22     22   
    23     23   /*
    24     24   ** Execute SQL code.  Return one of the SQLITE_ success/failure
................................................................................
    42     42     sqlite3_stmt *pStmt = 0;
    43     43     char **azCols = 0;
    44     44   
    45     45     int nRetry = 0;
    46     46     int nCallback;
    47     47   
    48     48     if( zSql==0 ) return SQLITE_OK;
           49  +
           50  +  sqlite3_mutex_enter(db->mutex);
    49     51     while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
    50     52       int nCol;
    51     53       char **azVals = 0;
    52     54   
    53     55       pStmt = 0;
    54     56       rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
    55     57       assert( rc==SQLITE_OK || pStmt==0 );
................................................................................
   123    125         memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   124    126       }
   125    127     }else if( pzErrMsg ){
   126    128       *pzErrMsg = 0;
   127    129     }
   128    130   
   129    131     assert( (rc&db->errMask)==rc );
          132  +  sqlite3_mutex_leave(db->mutex);
   130    133     return rc;
   131    134   }

Changes to src/malloc.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   ** Memory allocation functions used throughout sqlite.
    13     13   **
    14     14   **
    15         -** $Id: malloc.c,v 1.11 2007/08/24 03:51:34 drh Exp $
           15  +** $Id: malloc.c,v 1.12 2007/08/29 12:31:26 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <stdarg.h>
    19     19   #include <ctype.h>
    20     20   
    21     21   /*
    22     22   ** This routine runs when the memory allocator sees that the
................................................................................
    78     78   }
    79     79   
    80     80   /*
    81     81   ** Allocate and zero memory.  If the allocation fails, make
    82     82   ** the mallocFailed flag in the connection pointer.
    83     83   */
    84     84   void *sqlite3DbMallocZero(sqlite3 *db, unsigned n){
    85         -  void *p = sqlite3_malloc(n);
           85  +  void *p = sqlite3DbMallocRaw(db, n);
    86     86     if( p ){
    87     87       memset(p, 0, n);
    88         -  }else if( db ){
    89         -    db->mallocFailed = 1;
    90     88     }
    91     89     return p;
    92     90   }
    93     91   
    94     92   /*
    95     93   ** Allocate and zero memory.  If the allocation fails, make
    96     94   ** the mallocFailed flag in the connection pointer.
    97     95   */
    98     96   void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
    99         -  void *p = sqlite3_malloc(n);
   100         -  if( !p && db ){
   101         -    db->mallocFailed = 1;
           97  +  void *p = 0;
           98  +  if( !db || db->mallocFailed==0 ){
           99  +    p = sqlite3_malloc(n);
          100  +    if( !p && db ){
          101  +      db->mallocFailed = 1;
          102  +    }
   102    103     }
   103    104     return p;
   104    105   }
          106  +
          107  +void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
          108  +  void *pNew = 0;
          109  +  if( db->mallocFailed==0 ){
          110  +    pNew = sqlite3_realloc(p, n);
          111  +    if( !pNew ){
          112  +      db->mallocFailed = 1;
          113  +    }
          114  +  }
          115  +  return pNew;
          116  +}
   105    117   
   106    118   /*
   107    119   ** Attempt to reallocate p.  If the reallocation fails, then free p
   108    120   ** and set the mallocFailed flag in the database connection.
   109    121   */
   110    122   void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
   111    123     void *pNew;
   112         -  pNew = sqlite3_realloc(p, n);
          124  +  pNew = sqlite3DbRealloc(db, p, n);
   113    125     if( !pNew ){
   114    126       sqlite3_free(p);
   115         -    db->mallocFailed = 1;
   116    127     }
   117    128     return pNew;
   118    129   }
   119         -
   120    130   
   121    131   /*
   122    132   ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
   123    133   ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   124    134   ** is because when memory debugging is turned on, these two functions are 
   125    135   ** called via macros that record the current file and line number in the
   126    136   ** ThreadData structure.
................................................................................
   207    217   ** invocation SQLITE_NOMEM is returned instead. 
   208    218   **
   209    219   ** If the first argument, db, is not NULL and a malloc() error has occured,
   210    220   ** then the connection error-code (the value returned by sqlite3_errcode())
   211    221   ** is set to SQLITE_NOMEM.
   212    222   */
   213    223   int sqlite3ApiExit(sqlite3* db, int rc){
          224  +  /* If the db handle is not NULL, then we must hold the connection handle
          225  +  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
          226  +  ** is unsafe, as is the call to sqlite3Error().
          227  +  */
          228  +  assert( !db || sqlite3_mutex_held(db->mutex) );
   214    229     if( db && db->mallocFailed ){
   215    230       sqlite3Error(db, SQLITE_NOMEM, 0);
   216    231       db->mallocFailed = 0;
   217    232       rc = SQLITE_NOMEM;
   218    233     }
   219    234     return rc & (db ? db->errMask : 0xff);
   220    235   }
          236  + 

Changes to src/mem2.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 the C functions that implement a memory
    13     13   ** allocation subsystem for use by SQLite.  
    14     14   **
    15         -** $Id: mem2.c,v 1.10 2007/08/24 04:15:00 drh Exp $
           15  +** $Id: mem2.c,v 1.11 2007/08/29 12:31:26 danielk1977 Exp $
    16     16   */
    17     17   
    18     18   /*
    19     19   ** This version of the memory allocator is used only if the
    20     20   ** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION
    21     21   ** is not defined.
    22     22   */
................................................................................
   134    134     /*
   135    135     ** These values are used to simulate malloc failures.  When
   136    136     ** iFail is 1, simulate a malloc failures and reset the value
   137    137     ** to iReset.
   138    138     */
   139    139     int iFail;    /* Decrement and fail malloc when this is 1 */
   140    140     int iReset;   /* When malloc fails set iiFail to this value */
   141         -  int iFailCnt; /* Number of failures */
          141  +  int iFailCnt;         /* Number of failures */
          142  +  int iBenignFailCnt;   /* Number of benign failures */
          143  +  int iNextIsBenign;    /* True if the next call to malloc may fail benignly */
   142    144   
   143    145     /* 
   144    146     ** sqlite3MallocDisallow() increments the following counter.
   145    147     ** sqlite3MallocAllow() decrements it.
   146    148     */
   147    149     int disallow; /* Do not allow memory allocation */
   148    150     
................................................................................
   243    245   ** This routine is called once the first time a simulated memory
   244    246   ** failure occurs.  The sole purpose of this routine is to provide
   245    247   ** a convenient place to set a debugger breakpoint when debugging
   246    248   ** errors related to malloc() failures.
   247    249   */
   248    250   static void sqlite3MemsysFailed(void){
   249    251     mem.iFailCnt = 0;
          252  +  mem.iBenignFailCnt = 0;
   250    253   }
   251    254   
   252    255   /*
   253    256   ** Allocate nByte bytes of memory.
   254    257   */
   255    258   void *sqlite3_malloc(int nByte){
   256    259     struct MemBlockHdr *pHdr;
................................................................................
   257    260     void **pBt;
   258    261     char *z;
   259    262     int *pInt;
   260    263     void *p;
   261    264     int totalSize;
   262    265   
   263    266     if( nByte<=0 ){
          267  +    mem.iNextIsBenign = 0;
   264    268       return 0;
   265    269     }
   266    270     if( mem.mutex==0 ){
   267    271       mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
   268    272     }
   269    273     sqlite3_mutex_enter(mem.mutex);
   270    274     assert( mem.disallow==0 );
................................................................................
   278    282       if( mem.iFail==1 ){
   279    283         p = 0;
   280    284         mem.iFail = mem.iReset;
   281    285         if( mem.iFailCnt==0 ){
   282    286           sqlite3MemsysFailed();  /* A place to set a breakpoint */
   283    287         }
   284    288         mem.iFailCnt++;
          289  +      if( mem.iNextIsBenign ){
          290  +        mem.iBenignFailCnt++;
          291  +      }
   285    292       }else{
   286    293         p = malloc(totalSize);
   287    294         mem.iFail--;
   288    295       }
   289    296     }else{
   290    297       p = malloc(totalSize);
   291    298       if( p==0 ){
................................................................................
   325    332       mem.nowUsed += nByte;
   326    333       if( mem.nowUsed>mem.mxUsed ){
   327    334         mem.mxUsed = mem.nowUsed;
   328    335       }
   329    336       p = (void*)pInt;
   330    337     }
   331    338     sqlite3_mutex_leave(mem.mutex);
          339  +  mem.iNextIsBenign = 0;
   332    340     return p; 
   333    341   }
   334    342   
   335    343   /*
   336    344   ** Free memory.
   337    345   */
   338    346   void sqlite3_free(void *pPrior){
................................................................................
   471    479   **
   472    480   ** Each call to this routine overrides the previous.  To disable
   473    481   ** the simulated allocation failure mechanism, set iFail to -1.
   474    482   **
   475    483   ** This routine returns the number of simulated failures that have
   476    484   ** occurred since the previous call.
   477    485   */
   478         -int sqlite3_memdebug_fail(int iFail, int iRepeat){
          486  +int sqlite3_memdebug_fail(int iFail, int iRepeat, int *piBenign){
   479    487     int n = mem.iFailCnt;
          488  +  if( piBenign ){
          489  +    *piBenign = mem.iBenignFailCnt;
          490  +  }
   480    491     mem.iFail = iFail+1;
   481    492     if( iRepeat>=0 ){
   482    493       mem.iReset = iRepeat;
   483    494     }
   484    495     mem.iFailCnt = 0;
          496  +  mem.iBenignFailCnt = 0;
   485    497     return n;
   486    498   }
          499  +
          500  +void sqlite3MallocBenignFailure(int isBenign){
          501  +  if( isBenign ){
          502  +    mem.iNextIsBenign = 1;
          503  +  }
          504  +}
   487    505   
   488    506   /*
   489    507   ** The following two routines are used to assert that no memory
   490    508   ** allocations occur between one call and the next.  The use of
   491    509   ** these routines does not change the computed results in any way.
   492    510   ** These routines are like asserts.
   493    511   */

Changes to src/pager.c.

    14     14   ** The pager is used to access a database disk file.  It implements
    15     15   ** atomic commit and rollback through the use of a journal file that
    16     16   ** is separate from the database file.  The pager also implements file
    17     17   ** locking to prevent two processes from writing the same database
    18     18   ** file simultaneously, or one process from reading the database while
    19     19   ** another is writing.
    20     20   **
    21         -** @(#) $Id: pager.c,v 1.379 2007/08/28 22:24:35 drh Exp $
           21  +** @(#) $Id: pager.c,v 1.380 2007/08/29 12:31:27 danielk1977 Exp $
    22     22   */
    23     23   #ifndef SQLITE_OMIT_DISKIO
    24     24   #include "sqliteInt.h"
    25     25   #include <assert.h>
    26     26   #include <string.h>
    27     27   
    28     28   /*
................................................................................
   695    695   ** Change the size of the pager hash table to N.  N must be a power
   696    696   ** of two.
   697    697   */
   698    698   static void pager_resize_hash_table(Pager *pPager, int N){
   699    699     PgHdr **aHash, *pPg;
   700    700     assert( N>0 && (N&(N-1))==0 );
   701    701     pagerLeave(pPager);
          702  +  sqlite3MallocBenignFailure((int)pPager->aHash);
   702    703     aHash = sqlite3MallocZero( sizeof(aHash[0])*N );
   703    704     pagerEnter(pPager);
   704    705     if( aHash==0 ){
   705    706       /* Failure to rehash is not an error.  It is only a performance hit. */
   706    707       return;
   707    708     }
   708    709     sqlite3_free(pPager->aHash);
................................................................................
  2262   2263   ** page data.
  2263   2264   */
  2264   2265   void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
  2265   2266     pPager->xReiniter = xReinit;
  2266   2267   }
  2267   2268   
  2268   2269   /*
  2269         -** Set the page size.  Return the new size.  If the suggest new page
  2270         -** size is inappropriate, then an alternative page size is selected
  2271         -** and returned.
         2270  +** Set the page size to *pPageSize. If the suggest new page size is
         2271  +** inappropriate, then an alternative page size is set to that
         2272  +** value before returning.
  2272   2273   */
  2273         -int sqlite3PagerSetPagesize(Pager *pPager, int pageSize){
         2274  +int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
         2275  +  int rc = SQLITE_OK;
         2276  +  u16 pageSize = *pPageSize;
  2274   2277     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  2275         -  if( pageSize && !pPager->memDb && pPager->nRef==0 ){
  2276         -    pagerEnter(pPager);
  2277         -    pager_reset(pPager);
  2278         -    pPager->pageSize = pageSize;
  2279         -    setSectorSize(pPager);
  2280         -    pagerLeave(pPager);
  2281         -    sqlite3_free(pPager->pTmpSpace);
  2282         -    pPager->pTmpSpace = sqlite3_malloc(pageSize);
         2278  +  if( pageSize && pageSize!=pPager->pageSize 
         2279  +   && !pPager->memDb && pPager->nRef==0 
         2280  +  ){
         2281  +    char *pNew = (char *)sqlite3_malloc(pageSize);
         2282  +    if( !pNew ){
         2283  +      rc = SQLITE_NOMEM;
         2284  +    }else{
         2285  +      pagerEnter(pPager);
         2286  +      pager_reset(pPager);
         2287  +      pPager->pageSize = pageSize;
         2288  +      setSectorSize(pPager);
         2289  +      sqlite3_free(pPager->pTmpSpace);
         2290  +      pPager->pTmpSpace = pNew;
         2291  +      pagerLeave(pPager);
         2292  +    }
  2283   2293     }
  2284         -  return pPager->pageSize;
         2294  +  *pPageSize = pPager->pageSize;
         2295  +  return rc;
  2285   2296   }
  2286   2297   
  2287   2298   /*
  2288   2299   ** Attempt to set the maximum database page count if mxPage is positive. 
  2289   2300   ** Make no changes if mxPage is zero or negative.  And never reduce the
  2290   2301   ** maximum page count below the current size of the database.
  2291   2302   **
................................................................................
  3263   3274           ** a read/write file handle.
  3264   3275           */
  3265   3276           rc = SQLITE_BUSY;
  3266   3277           if( sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){
  3267   3278             int fout = 0;
  3268   3279             int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  3269   3280             assert( !pPager->tempFile );
  3270         -          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags,&fout);
         3281  +          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, &fout);
  3271   3282             assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
  3272   3283             if( fout&SQLITE_OPEN_READONLY ){
  3273   3284               rc = SQLITE_BUSY;
  3274   3285               sqlite3OsClose(pPager->jfd);
  3275   3286             }
  3276   3287           }
  3277   3288           if( rc!=SQLITE_OK ){
  3278   3289             pager_unlock(pPager);
  3279         -          return SQLITE_BUSY;
         3290  +          return (rc==SQLITE_NOMEM?rc:SQLITE_BUSY);
  3280   3291           }
  3281   3292           pPager->journalOpen = 1;
  3282   3293           pPager->journalStarted = 0;
  3283   3294           pPager->journalOff = 0;
  3284   3295           pPager->setMaster = 0;
  3285   3296           pPager->journalHdr = 0;
  3286   3297    

Changes to src/pager.h.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This header file defines the interface that the sqlite page cache
    13     13   ** subsystem.  The page cache subsystem reads and writes a file a page
    14     14   ** at a time and provides a journal for rollback.
    15     15   **
    16         -** @(#) $Id: pager.h,v 1.63 2007/08/28 22:24:35 drh Exp $
           16  +** @(#) $Id: pager.h,v 1.64 2007/08/29 12:31:27 danielk1977 Exp $
    17     17   */
    18     18   
    19     19   #ifndef _PAGER_H_
    20     20   #define _PAGER_H_
    21     21   
    22     22   /*
    23     23   ** The type used to represent a page number.  The first page in a file
................................................................................
    54     54   ** See source code comments for a detailed description of the following
    55     55   ** routines:
    56     56   */
    57     57   int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char *, int, int);
    58     58   void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
    59     59   void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
    60     60   void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
    61         -int sqlite3PagerSetPagesize(Pager*, int);
           61  +int sqlite3PagerSetPagesize(Pager*, u16*);
    62     62   int sqlite3PagerMaxPageCount(Pager*, int);
    63     63   int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
    64     64   void sqlite3PagerSetCachesize(Pager*, int);
    65     65   int sqlite3PagerClose(Pager *pPager);
    66     66   int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
    67     67   #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
    68     68   DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);

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.59 2007/08/29 00:33:07 drh Exp $
           16  +** $Id: prepare.c,v 1.60 2007/08/29 12:31:27 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include <ctype.h>
    20     20   
    21     21   /*
    22     22   ** Fill the InitData structure with an error message that indicates
    23     23   ** that the database is corrupt.
................................................................................
   178    178     azArg[3] = 0;
   179    179     initData.db = db;
   180    180     initData.iDb = iDb;
   181    181     initData.pzErrMsg = pzErrMsg;
   182    182     rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   183    183     if( rc ){
   184    184       sqlite3SafetyOn(db);
   185         -    return initData.rc;
          185  +    rc = initData.rc;
          186  +    goto error_out;
   186    187     }
   187    188     pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   188    189     if( pTab ){
   189    190       pTab->readOnly = 1;
   190    191     }
   191    192     sqlite3SafetyOn(db);
   192    193   
................................................................................
   200    201       return SQLITE_OK;
   201    202     }
   202    203     sqlite3BtreeEnter(pDb->pBt);
   203    204     rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
   204    205     if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
   205    206       sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
   206    207       sqlite3BtreeLeave(pDb->pBt);
   207         -    return rc;
          208  +    goto error_out;
   208    209     }
   209    210   
   210    211     /* Get the database meta information.
   211    212     **
   212    213     ** Meta values are as follows:
   213    214     **    meta[0]   Schema cookie.  Changes with each schema change.
   214    215     **    meta[1]   File format of schema layer.
................................................................................
   229    230       for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
   230    231         rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   231    232       }
   232    233       if( rc ){
   233    234         sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
   234    235         sqlite3BtreeCloseCursor(curMain);
   235    236         sqlite3BtreeLeave(pDb->pBt);
   236         -      return rc;
          237  +      goto error_out;
   237    238       }
   238    239     }else{
   239    240       memset(meta, 0, sizeof(meta));
   240    241     }
   241    242     pDb->pSchema->schema_cookie = meta[0];
   242    243   
   243    244     /* If opening a non-empty database, check the text encoding. For the
................................................................................
   325    326       ** purpose of this is to allow access to the sqlite_master table
   326    327       ** even when it's contents have been corrupted.
   327    328       */
   328    329       DbSetProperty(db, iDb, DB_SchemaLoaded);
   329    330       rc = SQLITE_OK;
   330    331     }
   331    332     sqlite3BtreeLeave(pDb->pBt);
          333  +
          334  +error_out:
          335  +  if( rc==SQLITE_NOMEM ){
          336  +    db->mallocFailed = 1;
          337  +  }
   332    338     return rc;
   333    339   }
   334    340   
   335    341   /*
   336    342   ** Initialize all database files - the main database file, the file
   337    343   ** used to store temporary tables, and any additional database files
   338    344   ** created using ATTACH statements.  Return a success code.  If an
................................................................................
   417    423       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
   418    424       if( rc==SQLITE_OK ){
   419    425         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
   420    426         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   421    427           allOk = 0;
   422    428         }
   423    429         sqlite3BtreeCloseCursor(curTemp);
          430  +    }
          431  +    if( rc==SQLITE_NOMEM ){
          432  +      db->mallocFailed = 1;
   424    433       }
   425    434     }
   426    435     return allOk;
   427    436   }
   428    437   
   429    438   /*
   430    439   ** Convert a schema pointer into the iDb index that indicates

Changes to src/printf.c.

   785    785     if( xRealloc ){
   786    786       if( sM.zText==sM.zBase ){
   787    787         sM.zText = xRealloc(0, sM.nChar+1);
   788    788         if( sM.zText ){
   789    789           memcpy(sM.zText, sM.zBase, sM.nChar+1);
   790    790         }
   791    791       }else if( sM.nAlloc>sM.nChar+10 ){
   792         -      char *zNew = xRealloc(sM.zText, sM.nChar+1);
          792  +      char *zNew;
          793  +      sqlite3MallocBenignFailure(1);
          794  +      zNew = xRealloc(sM.zText, sM.nChar+1);
   793    795         if( zNew ){
   794    796           sM.zText = zNew;
   795    797         }
   796    798       }
   797    799     }
   798    800     return sM.zText;
   799    801   }

Changes to src/select.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 C code routines that are called by the parser
    13     13   ** to handle SELECT statements in SQLite.
    14     14   **
    15         -** $Id: select.c,v 1.356 2007/08/16 10:09:03 danielk1977 Exp $
           15  +** $Id: select.c,v 1.357 2007/08/29 12:31:27 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   
    20     20   /*
    21     21   ** Delete all the content of a Select structure but do not deallocate
    22     22   ** the select structure itself.
................................................................................
    56     56     pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
    57     57     assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
    58     58     if( pNew==0 ){
    59     59       pNew = &standin;
    60     60       memset(pNew, 0, sizeof(*pNew));
    61     61     }
    62     62     if( pEList==0 ){
    63         -    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(TK_ALL,0,0,0), 0);
           63  +    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
    64     64     }
    65     65     pNew->pEList = pEList;
    66     66     pNew->pSrc = pSrc;
    67     67     pNew->pWhere = pWhere;
    68     68     pNew->pGroupBy = pGroupBy;
    69     69     pNew->pHaving = pHaving;
    70     70     pNew->pOrderBy = pOrderBy;
................................................................................
  1360   1360                 }
  1361   1361                 if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  1362   1362                   /* In a join with a USING clause, omit columns in the
  1363   1363                   ** using clause from the table on the right. */
  1364   1364                   continue;
  1365   1365                 }
  1366   1366               }
  1367         -            pRight = sqlite3Expr(TK_ID, 0, 0, 0);
         1367  +            pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1368   1368               if( pRight==0 ) break;
  1369   1369               setQuotedToken(pParse, &pRight->token, zName);
  1370   1370               if( zTabName && (longNames || pTabList->nSrc>1) ){
  1371         -              Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
  1372         -              pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
         1371  +              Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
         1372  +              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  1373   1373                 if( pExpr==0 ) break;
  1374   1374                 setQuotedToken(pParse, &pLeft->token, zTabName);
  1375   1375                 setToken(&pExpr->span, 
  1376   1376                     sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  1377   1377                 pExpr->span.dyn = 1;
  1378   1378                 pExpr->token.z = 0;
  1379   1379                 pExpr->token.n = 0;

Changes to src/sqlite.h.in.

    26     26   ** on how SQLite interfaces are suppose to operate.
    27     27   **
    28     28   ** The name of this file under configuration management is "sqlite.h.in".
    29     29   ** The makefile makes some minor changes to this file (such as inserting
    30     30   ** the version number) and changes its name to "sqlite3.h" as
    31     31   ** part of the build process.
    32     32   **
    33         -** @(#) $Id: sqlite.h.in,v 1.246 2007/08/28 15:47:45 drh Exp $
           33  +** @(#) $Id: sqlite.h.in,v 1.247 2007/08/29 12:31:28 danielk1977 Exp $
    34     34   */
    35     35   #ifndef _SQLITE3_H_
    36     36   #define _SQLITE3_H_
    37     37   #include <stdarg.h>     /* Needed for the definition of va_list */
    38     38   
    39     39   /*
    40     40   ** Make sure we can call this stuff from C++.
................................................................................
  2410   2410   ** the SQL function associated with the [sqlite3_context] pointer.
  2411   2411   */
  2412   2412   void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  2413   2413   void sqlite3_result_double(sqlite3_context*, double);
  2414   2414   void sqlite3_result_error(sqlite3_context*, const char*, int);
  2415   2415   void sqlite3_result_error16(sqlite3_context*, const void*, int);
  2416   2416   void sqlite3_result_error_toobig(sqlite3_context*);
         2417  +void sqlite3_result_error_nomem(sqlite3_context*);
  2417   2418   void sqlite3_result_int(sqlite3_context*, int);
  2418   2419   void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  2419   2420   void sqlite3_result_null(sqlite3_context*);
  2420   2421   void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  2421   2422   void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  2422   2423   void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  2423   2424   void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));

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.604 2007/08/28 16:34:43 drh Exp $
           14  +** @(#) $Id: sqliteInt.h,v 1.605 2007/08/29 12:31:28 danielk1977 Exp $
    15     15   */
    16     16   #ifndef _SQLITEINT_H_
    17     17   #define _SQLITEINT_H_
    18     18   #include "sqliteLimit.h"
    19     19   
    20     20   #define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
    21     21   
................................................................................
  1538   1538   void *sqlite3DbMallocZero(sqlite3*, unsigned);
  1539   1539   void *sqlite3DbMallocRaw(sqlite3*, unsigned);
  1540   1540   char *sqlite3StrDup(const char*);
  1541   1541   char *sqlite3StrNDup(const char*, int);
  1542   1542   char *sqlite3DbStrDup(sqlite3*,const char*);
  1543   1543   char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  1544   1544   void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
         1545  +void *sqlite3DbRealloc(sqlite3 *, void *, int);
  1545   1546   
  1546   1547   char *sqlite3MPrintf(sqlite3*,const char*, ...);
  1547   1548   char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  1548   1549   #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  1549   1550     void sqlite3DebugPrintf(const char*, ...);
  1550   1551     void *sqlite3TextToPtr(const char*);
  1551   1552   #endif
................................................................................
  1553   1554   void sqlite3ErrorMsg(Parse*, const char*, ...);
  1554   1555   void sqlite3ErrorClear(Parse*);
  1555   1556   void sqlite3Dequote(char*);
  1556   1557   void sqlite3DequoteExpr(sqlite3*, Expr*);
  1557   1558   int sqlite3KeywordCode(const unsigned char*, int);
  1558   1559   int sqlite3RunParser(Parse*, const char*, char **);
  1559   1560   void sqlite3FinishCoding(Parse*);
  1560         -Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
         1561  +Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
  1561   1562   Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  1562   1563   Expr *sqlite3RegisterExpr(Parse*,Token*);
  1563   1564   Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  1564   1565   void sqlite3ExprSpan(Expr*,Token*,Token*);
  1565   1566   Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  1566   1567   void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  1567   1568   void sqlite3ExprDelete(Expr*);
................................................................................
  1828   1829   ** The MallocDisallow() and MallocAllow() routines are like asserts.
  1829   1830   ** Call them around a section of code that you do not expect to do
  1830   1831   ** any memory allocation.
  1831   1832   */
  1832   1833   #ifdef SQLITE_MEMDEBUG
  1833   1834     void sqlite3MallocDisallow(void);
  1834   1835     void sqlite3MallocAllow(void);
         1836  +  void sqlite3MallocBenignFailure(int);
  1835   1837   #else
  1836   1838   # define sqlite3MallocDisallow()
  1837   1839   # define sqlite3MallocAllow()
         1840  +# define sqlite3MallocBenignFailure(x)
  1838   1841   #endif
  1839   1842   
  1840   1843   
  1841   1844   #ifdef SQLITE_OMIT_VIRTUALTABLE
  1842   1845   #  define sqlite3VtabClear(X)
  1843   1846   #  define sqlite3VtabSync(X,Y) (Y)
  1844   1847   #  define sqlite3VtabRollback(X)

Changes to src/test2.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing the pager.c module in 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: test2.c,v 1.50 2007/08/21 10:44:16 drh Exp $
           16  +** $Id: test2.c,v 1.51 2007/08/29 12:31:28 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "tcl.h"
    20     20   #include <stdlib.h>
    21     21   #include <string.h>
    22     22   
    23     23   /*
................................................................................
    62     62   */
    63     63   static int pager_open(
    64     64     void *NotUsed,
    65     65     Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
    66     66     int argc,              /* Number of arguments */
    67     67     const char **argv      /* Text of each argument */
    68     68   ){
           69  +  u16 pageSize;
    69     70     Pager *pPager;
    70     71     int nPage;
    71     72     int rc;
    72     73     char zBuf[100];
    73     74     if( argc!=3 ){
    74     75       Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
    75     76          " FILENAME N-PAGE\"", 0);
................................................................................
    78     79     if( Tcl_GetInt(interp, argv[2], &nPage) ) return TCL_ERROR;
    79     80     rc = sqlite3PagerOpen(sqlite3_vfs_find(0), &pPager, argv[1], 0, 0);
    80     81     if( rc!=SQLITE_OK ){
    81     82       Tcl_AppendResult(interp, errorName(rc), 0);
    82     83       return TCL_ERROR;
    83     84     }
    84     85     sqlite3PagerSetCachesize(pPager, nPage);
    85         -  sqlite3PagerSetPagesize(pPager, test_pagesize);
           86  +  pageSize = test_pagesize;
           87  +  sqlite3PagerSetPagesize(pPager, &pageSize);
    86     88     sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPager);
    87     89     Tcl_AppendResult(interp, zBuf, 0);
    88     90     return TCL_OK;
    89     91   }
    90     92   
    91     93   /*
    92     94   ** Usage:   pager_close ID

Changes to src/test3.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing the btree.c module in 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: test3.c,v 1.82 2007/08/24 16:08:29 drh Exp $
           16  +** $Id: test3.c,v 1.83 2007/08/29 12:31:28 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
           19  +#include "btreeInt.h"
    19     20   #include "tcl.h"
    20     21   #include <stdlib.h>
    21     22   #include <string.h>
    22     23   
    23     24   /*
    24     25   ** Interpret an SQLite error number
    25     26   */
................................................................................
   526    527   
   527    528     if( argc!=2 ){
   528    529       Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
   529    530          " ID\"", 0);
   530    531       return TCL_ERROR;
   531    532     }
   532    533     pBt = sqlite3TextToPtr(argv[1]);
          534  +  sqlite3_mutex_enter(pBt->pSqlite->mutex);
   533    535     sqlite3BtreeEnter(pBt);
   534    536     a = sqlite3PagerStats(sqlite3BtreePager(pBt));
   535    537     for(i=0; i<11; i++){
   536    538       static char *zName[] = {
   537    539         "ref", "page", "max", "size", "state", "err",
   538    540         "hit", "miss", "ovfl", "read", "write"
   539    541       };
   540    542       char zBuf[100];
   541    543       Tcl_AppendElement(interp, zName[i]);
   542    544       sqlite3_snprintf(sizeof(zBuf), zBuf,"%d",a[i]);
   543    545       Tcl_AppendElement(interp, zBuf);
   544    546     }
   545    547     sqlite3BtreeLeave(pBt);
          548  +  sqlite3_mutex_leave(pBt->pSqlite->mutex);
   546    549     return TCL_OK;
   547    550   }
   548    551   
   549    552   /*
   550    553   ** Usage:   btree_pager_ref_dump ID
   551    554   **
   552    555   ** Print out all outstanding pages.
................................................................................
  1489   1492     if( argc!=3 ){
  1490   1493       Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  1491   1494          " BT NCACHE\"", 0);
  1492   1495       return TCL_ERROR;
  1493   1496     }
  1494   1497     pBt = sqlite3TextToPtr(argv[1]);
  1495   1498     if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR;
         1499  +
         1500  +  sqlite3_mutex_enter(pBt->pSqlite->mutex);
  1496   1501     sqlite3BtreeSetCacheSize(pBt, nCache);
         1502  +  sqlite3_mutex_leave(pBt->pSqlite->mutex);
         1503  +
  1497   1504     return TCL_OK;
  1498   1505   }
  1499   1506   
  1500   1507   
  1501   1508   /*
  1502   1509   ** Register commands with the TCL interpreter.
  1503   1510   */

Changes to src/test8.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing the virtual table interfaces.  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: test8.c,v 1.54 2007/08/25 13:37:49 danielk1977 Exp $
           16  +** $Id: test8.c,v 1.55 2007/08/29 12:31:28 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "tcl.h"
    20     20   #include <stdlib.h>
    21     21   #include <string.h>
    22     22   
    23     23   #ifndef SQLITE_OMIT_VIRTUALTABLE
................................................................................
   357    357   static int echoConstructor(
   358    358     sqlite3 *db,
   359    359     void *pAux,
   360    360     int argc, const char *const*argv,
   361    361     sqlite3_vtab **ppVtab,
   362    362     char **pzErr
   363    363   ){
          364  +  int rc;
   364    365     int i;
   365    366     echo_vtab *pVtab;
   366    367   
   367    368     /* Allocate the sqlite3_vtab/echo_vtab structure itself */
   368    369     pVtab = sqlite3MallocZero( sizeof(*pVtab) );
   369    370     if( !pVtab ){
   370    371       return SQLITE_NOMEM;
................................................................................
   400    401       appendToEchoModule(pVtab->interp, argv[i]);
   401    402     }
   402    403   
   403    404     /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab
   404    405     ** structure. If an error occurs, delete the sqlite3_vtab structure and
   405    406     ** return an error code.
   406    407     */
   407         -  if( echoDeclareVtab(pVtab, db) ){
          408  +  rc = echoDeclareVtab(pVtab, db);
          409  +  if( rc!=SQLITE_OK ){
   408    410       echoDestructor((sqlite3_vtab *)pVtab);
   409         -    return SQLITE_ERROR;
          411  +    return rc;
   410    412     }
   411    413   
   412    414     /* Success. Set *ppVtab and return */
   413    415     *ppVtab = &pVtab->base;
   414    416     return SQLITE_OK;
   415    417   }
   416    418   
................................................................................
   642    644   ** string. The two strings are concatenated together and *pzStr
   643    645   ** set to point at the result. The initial buffer pointed to by *pzStr
   644    646   ** is deallocated via sqlite3_free().
   645    647   **
   646    648   ** If the third argument, doFree, is true, then sqlite3_free() is
   647    649   ** also called to free the buffer pointed to by zAppend.
   648    650   */
   649         -static void string_concat(char **pzStr, char *zAppend, int doFree){
          651  +static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){
   650    652     char *zIn = *pzStr;
   651         -  if( zIn ){
   652         -    char *zTemp = zIn;
   653         -    zIn = sqlite3_mprintf("%s%s", zIn, zAppend);
   654         -    sqlite3_free(zTemp);
          653  +  if( !zAppend && doFree && *pRc==SQLITE_OK ){
          654  +    *pRc = SQLITE_NOMEM;
          655  +  }
          656  +  if( *pRc!=SQLITE_OK ){
          657  +    sqlite3_free(zIn);
          658  +    zIn = 0;
   655    659     }else{
   656         -    zIn = sqlite3_mprintf("%s", zAppend);
          660  +    if( zIn ){
          661  +      char *zTemp = zIn;
          662  +      zIn = sqlite3_mprintf("%s%s", zIn, zAppend);
          663  +      sqlite3_free(zTemp);
          664  +    }else{
          665  +      zIn = sqlite3_mprintf("%s", zAppend);
          666  +    }
          667  +    if( !zIn ){
          668  +      *pRc = SQLITE_NOMEM;
          669  +    }
   657    670     }
   658    671     *pzStr = zIn;
   659    672     if( doFree ){
   660    673       sqlite3_free(zAppend);
   661    674     }
   662    675   }
   663    676   
................................................................................
   705    718     ** number of rows if the proposed scan uses an index.  
   706    719     */
   707    720     if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){
   708    721       cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY));
   709    722       useCost = 1;
   710    723     } else {
   711    724       zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName);
          725  +    if( !zQuery ){
          726  +      return SQLITE_NOMEM;
          727  +    }
   712    728       rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0);
   713    729       sqlite3_free(zQuery);
   714    730       if( rc!=SQLITE_OK ){
   715    731         return rc;
   716    732       }
   717    733       sqlite3_step(pStmt);
   718    734       nRow = sqlite3_column_int(pStmt, 0);
................................................................................
   719    735       rc = sqlite3_finalize(pStmt);
   720    736       if( rc!=SQLITE_OK ){
   721    737         return rc;
   722    738       }
   723    739     }
   724    740   
   725    741     zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName);
          742  +  if( !zQuery ){
          743  +    return SQLITE_NOMEM;
          744  +  }
   726    745     for(ii=0; ii<pIdxInfo->nConstraint; ii++){
   727    746       const struct sqlite3_index_constraint *pConstraint;
   728    747       struct sqlite3_index_constraint_usage *pUsage;
   729    748       int iCol;
   730    749   
   731    750       pConstraint = &pIdxInfo->aConstraint[ii];
   732    751       pUsage = &pIdxInfo->aConstraintUsage[ii];
................................................................................
   755    774         }
   756    775         if( zOp[0]=='L' ){
   757    776           zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", 
   758    777                                  zSep, zCol);
   759    778         } else {
   760    779           zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp);
   761    780         }
   762         -      string_concat(&zQuery, zNew, 1);
          781  +      string_concat(&zQuery, zNew, 1, &rc);
   763    782   
   764    783         zSep = "AND";
   765    784         pUsage->argvIndex = ++nArg;
   766    785         pUsage->omit = 1;
   767    786       }
   768    787     }
   769    788   
................................................................................
   775    794       int iCol = pIdxInfo->aOrderBy->iColumn;
   776    795       char *zCol = pVtab->aCol[iCol];
   777    796       char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
   778    797       if( iCol<0 ){
   779    798         zCol = "rowid";
   780    799       }
   781    800       zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir);
   782         -    string_concat(&zQuery, zNew, 1);
          801  +    string_concat(&zQuery, zNew, 1, &rc);
   783    802       pIdxInfo->orderByConsumed = 1;
   784    803     }
   785    804   
   786    805     appendToEchoModule(pVtab->interp, "xBestIndex");;
   787    806     appendToEchoModule(pVtab->interp, zQuery);
   788    807   
   789    808     if( !zQuery ){
   790         -    return SQLITE_NOMEM;
          809  +    return rc;
   791    810     }
   792    811     pIdxInfo->idxNum = hashString(zQuery);
   793    812     pIdxInfo->idxStr = zQuery;
   794    813     pIdxInfo->needToFreeIdxStr = 1;
   795    814     if (useCost) {
   796    815       pIdxInfo->estimatedCost = cost;
   797    816     } else if( useIdx ){
................................................................................
   839    858   
   840    859     assert( nData==pVtab->nCol+2 || nData==1 );
   841    860   
   842    861     /* If apData[0] is an integer and nData>1 then do an UPDATE */
   843    862     if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
   844    863       char *zSep = " SET";
   845    864       z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName);
          865  +    if( !z ){
          866  +      rc = SQLITE_NOMEM;
          867  +    }
   846    868   
   847    869       bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER);
   848    870       bindArgZero = 1;
   849    871   
   850    872       if( bindArgOne ){
   851         -       string_concat(&z, " SET rowid=?1 ", 0);
          873  +       string_concat(&z, " SET rowid=?1 ", 0, &rc);
   852    874          zSep = ",";
   853    875       }
   854    876       for(i=2; i<nData; i++){
   855    877         if( apData[i]==0 ) continue;
   856    878         string_concat(&z, sqlite3_mprintf(
   857         -          "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1);
          879  +          "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1, &rc);
   858    880         zSep = ",";
   859    881       }
   860         -    string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1);
          882  +    string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc);
   861    883     }
   862    884   
   863    885     /* If apData[0] is an integer and nData==1 then do a DELETE */
   864    886     else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
   865    887       z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
          888  +    if( !z ){
          889  +      rc = SQLITE_NOMEM;
          890  +    }
   866    891       bindArgZero = 1;
   867    892     }
   868    893   
   869    894     /* If the first argument is NULL and there are more than two args, INSERT */
   870    895     else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){
   871    896       int ii;
   872    897       char *zInsert = 0;
   873    898       char *zValues = 0;
   874    899     
   875    900       zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName);
          901  +    if( !zInsert ){
          902  +      rc = SQLITE_NOMEM;
          903  +    }
   876    904       if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){
   877    905         bindArgOne = 1;
   878    906         zValues = sqlite3_mprintf("?");
   879         -      string_concat(&zInsert, "rowid", 0);
          907  +      string_concat(&zInsert, "rowid", 0, &rc);
   880    908       }
   881    909   
   882    910       assert((pVtab->nCol+2)==nData);
   883    911       for(ii=2; ii<nData; ii++){
   884    912         string_concat(&zInsert, 
   885         -          sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1);
          913  +          sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1, &rc);
   886    914         string_concat(&zValues, 
   887         -          sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1);
          915  +          sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc);
   888    916       }
   889    917   
   890         -    string_concat(&z, zInsert, 1);
   891         -    string_concat(&z, ") VALUES(", 0);
   892         -    string_concat(&z, zValues, 1);
   893         -    string_concat(&z, ")", 0);
          918  +    string_concat(&z, zInsert, 1, &rc);
          919  +    string_concat(&z, ") VALUES(", 0, &rc);
          920  +    string_concat(&z, zValues, 1, &rc);
          921  +    string_concat(&z, ")", 0, &rc);
   894    922     }
   895    923   
   896    924     /* Anything else is an error */
   897    925     else{
   898    926       assert(0);
   899    927       return SQLITE_ERROR;
   900    928     }
   901    929   
   902         -  rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
          930  +  if( rc==SQLITE_OK ){
          931  +    rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
          932  +  }
   903    933     assert( rc!=SQLITE_OK || pStmt );
   904    934     sqlite3_free(z);
   905    935     if( rc==SQLITE_OK ) {
   906    936       if( bindArgZero ){
   907    937         sqlite3_bind_value(pStmt, nData, apData[0]);
   908    938       }
   909    939       if( bindArgOne ){
................................................................................
   931    961   static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){
   932    962     char *z;
   933    963     echo_vtab *pVtab = (echo_vtab *)tab;
   934    964     z = sqlite3_mprintf("echo(%s)", pVtab->zTableName);
   935    965     appendToEchoModule(pVtab->interp, zCall);
   936    966     appendToEchoModule(pVtab->interp, z);
   937    967     sqlite3_free(z);
   938         -  return SQLITE_OK;
          968  +  return (z?SQLITE_OK:SQLITE_NOMEM);
   939    969   }
   940    970   static int echoBegin(sqlite3_vtab *tab){
          971  +  int rc;
   941    972     echo_vtab *pVtab = (echo_vtab *)tab;
   942    973     Tcl_Interp *interp = pVtab->interp;
   943    974     const char *zVal; 
   944    975   
   945         -  echoTransactionCall(tab, "xBegin");
          976  +  rc = echoTransactionCall(tab, "xBegin");
   946    977   
   947         -  /* Check if the $::echo_module_begin_fail variable is defined. If it is,
   948         -  ** and it is set to the name of the real table underlying this virtual
   949         -  ** echo module table, then cause this xSync operation to fail.
   950         -  */
   951         -  zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
   952         -  if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
   953         -    return SQLITE_ERROR;
          978  +  if( rc==SQLITE_OK ){
          979  +    /* Check if the $::echo_module_begin_fail variable is defined. If it is,
          980  +    ** and it is set to the name of the real table underlying this virtual
          981  +    ** echo module table, then cause this xSync operation to fail.
          982  +    */
          983  +    zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
          984  +    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
          985  +      rc = SQLITE_ERROR;
          986  +    }
   954    987     }
   955         -  return SQLITE_OK;
          988  +  return rc;
   956    989   }
   957    990   static int echoSync(sqlite3_vtab *tab){
          991  +  int rc;
   958    992     echo_vtab *pVtab = (echo_vtab *)tab;
   959    993     Tcl_Interp *interp = pVtab->interp;
   960    994     const char *zVal; 
   961    995   
   962         -  echoTransactionCall(tab, "xSync");
          996  +  rc = echoTransactionCall(tab, "xSync");
   963    997   
   964         -  /* Check if the $::echo_module_sync_fail variable is defined. If it is,
   965         -  ** and it is set to the name of the real table underlying this virtual
   966         -  ** echo module table, then cause this xSync operation to fail.
   967         -  */
   968         -  zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
   969         -  if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
   970         -    return -1;
          998  +  if( rc==SQLITE_OK ){
          999  +    /* Check if the $::echo_module_sync_fail variable is defined. If it is,
         1000  +    ** and it is set to the name of the real table underlying this virtual
         1001  +    ** echo module table, then cause this xSync operation to fail.
         1002  +    */
         1003  +    zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
         1004  +    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
         1005  +      rc = -1;
         1006  +    }
   971   1007     }
   972         -  return SQLITE_OK;
         1008  +  return rc;
   973   1009   }
   974   1010   static int echoCommit(sqlite3_vtab *tab){
         1011  +  sqlite3MallocBenignFailure(1);
   975   1012     return echoTransactionCall(tab, "xCommit");
   976   1013   }
   977   1014   static int echoRollback(sqlite3_vtab *tab){
   978   1015     return echoTransactionCall(tab, "xRollback");
   979   1016   }
   980   1017   
   981   1018   /*

Changes to src/test_malloc.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   **
    13     13   ** This file contains code used to implement test interfaces to the
    14     14   ** memory allocation subsystem.
    15     15   **
    16         -** $Id: test_malloc.c,v 1.5 2007/08/24 03:51:34 drh Exp $
           16  +** $Id: test_malloc.c,v 1.6 2007/08/29 12:31:28 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "tcl.h"
    20     20   #include <stdlib.h>
    21     21   #include <string.h>
    22     22   #include <assert.h>
    23     23   
................................................................................
   241    241     }
   242    242   #endif
   243    243     return TCL_OK;
   244    244   }
   245    245   
   246    246   
   247    247   /*
   248         -** Usage:    sqlite3_memdebug_fail  COUNTER  ?REPEAT?
          248  +** Usage:    sqlite3_memdebug_fail  COUNTER  ?OPTIONS?
          249  +**
          250  +** where options are:
          251  +**
          252  +**     -repeat    <boolean>
          253  +**     -benigncnt <varname>
   249    254   **
   250    255   ** Arrange for a simulated malloc() failure after COUNTER successes.
   251    256   ** If REPEAT is 1 then all subsequent malloc()s fail.   If REPEAT is
   252    257   ** 0 then only a single failure occurs.
   253    258   **
   254    259   ** Each call to this routine overrides the prior counter value.
   255    260   ** This routine returns the number of simulated failures that have
................................................................................
   259    264   */
   260    265   static int test_memdebug_fail(
   261    266     void * clientData,
   262    267     Tcl_Interp *interp,
   263    268     int objc,
   264    269     Tcl_Obj *CONST objv[]
   265    270   ){
          271  +  int ii;
   266    272     int iFail;
   267         -  int iRepeat;
          273  +  int iRepeat = -1;
          274  +  int iBenignCnt;
          275  +  Tcl_Obj *pBenignCnt = 0;
          276  +
   268    277     int nFail = 0;
   269         -  if( objc!=3 && objc!=2 ){
   270         -    Tcl_WrongNumArgs(interp, 1, objv, "COUNTER ?REPEAT?");
          278  +
          279  +  if( objc<2 ){
          280  +    Tcl_WrongNumArgs(interp, 1, objv, "COUNTER ?OPTIONS?");
   271    281       return TCL_ERROR;
   272    282     }
   273    283     if( Tcl_GetIntFromObj(interp, objv[1], &iFail) ) return TCL_ERROR;
   274         -  if( objc==3 ){
   275         -    if( Tcl_GetIntFromObj(interp, objv[2], &iRepeat) ) return TCL_ERROR;
   276         -  }else{
   277         -    iRepeat = -1;
          284  +
          285  +  for(ii=2; ii<objc; ii+=2){
          286  +    int nOption;
          287  +    char *zOption = Tcl_GetStringFromObj(objv[ii], &nOption);
          288  +    char *zErr = 0;
          289  +
          290  +    if( nOption>1 && strncmp(zOption, "-repeat", nOption)==0 ){
          291  +      if( ii==(objc-1) ){
          292  +        zErr = "option requires an argument: ";
          293  +      }else{
          294  +        if( Tcl_GetIntFromObj(interp, objv[ii+1], &iRepeat) ){
          295  +          return TCL_ERROR;
          296  +        }
          297  +      }
          298  +    }else if( nOption>1 && strncmp(zOption, "-benigncnt", nOption)==0 ){
          299  +      if( ii==(objc-1) ){
          300  +        zErr = "option requires an argument: ";
          301  +      }else{
          302  +        pBenignCnt = objv[ii+1];
          303  +      }
          304  +    }else{
          305  +      zErr = "unknown option: ";
          306  +    }
          307  +
          308  +    if( zErr ){
          309  +      Tcl_AppendResult(interp, zErr, zOption, 0);
          310  +      return TCL_ERROR;
          311  +    }
   278    312     }
          313  +  
   279    314   #ifdef SQLITE_MEMDEBUG
   280    315     {
   281         -    extern int sqlite3_memdebug_fail(int,int);
   282         -    nFail = sqlite3_memdebug_fail(iFail, iRepeat);
          316  +    extern int sqlite3_memdebug_fail(int,int,int*);
          317  +    nFail = sqlite3_memdebug_fail(iFail, iRepeat, &iBenignCnt);
          318  +    if( pBenignCnt ){
          319  +      Tcl_ObjSetVar2(interp, pBenignCnt, 0, Tcl_NewIntObj(iBenignCnt), 0);
          320  +    }
   283    321     }
   284    322   #endif
   285    323     Tcl_SetObjResult(interp, Tcl_NewIntObj(nFail));
   286    324     return TCL_OK;
   287    325   }
   288    326   
   289    327   

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.72 2007/08/24 11:43:37 drh Exp $
           17  +** $Id: vacuum.c,v 1.73 2007/08/29 12:31:28 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "vdbeInt.h"
    21     21   
    22     22   #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
    23     23   /*
    24     24   ** Execute zSql on database db. Return an error code.
    25     25   */
    26     26   static int execSql(sqlite3 *db, const char *zSql){
    27     27     sqlite3_stmt *pStmt;
           28  +  if( !zSql ){
           29  +    return SQLITE_NOMEM;
           30  +  }
    28     31     if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
    29     32       return sqlite3_errcode(db);
    30     33     }
    31     34     while( SQLITE_ROW==sqlite3_step(pStmt) ){}
    32     35     return sqlite3_finalize(pStmt);
    33     36   }
    34     37   

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.646 2007/08/28 23:28:08 drh Exp $
           46  +** $Id: vdbe.c,v 1.647 2007/08/29 12:31:28 danielk1977 Exp $
    47     47   */
    48     48   #include "sqliteInt.h"
    49     49   #include <ctype.h>
    50     50   #include <math.h>
    51     51   #include "vdbeInt.h"
    52     52   
    53     53   /*
................................................................................
  2633   2633     if( pBt ){
  2634   2634       rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
  2635   2635     }else{
  2636   2636       rc = SQLITE_OK;
  2637   2637       iMeta = 0;
  2638   2638     }
  2639   2639     if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
  2640         -    sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
         2640  +    sqlite3_free(p->zErrMsg);
         2641  +    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  2641   2642       /* If the schema-cookie from the database file matches the cookie 
  2642   2643       ** stored with the in-memory representation of the schema, do
  2643   2644       ** not reload the schema from the database file.
  2644   2645       **
  2645   2646       ** If virtual-tables are in use, this is not just an optimisation.
  2646   2647       ** Often, v-tables store their data in other SQLite tables, which
  2647   2648       ** are queried from within xNext() and other v-table methods using

Changes to src/vdbeapi.c.

   230    230   
   231    231   /* Force an SQLITE_TOOBIG error. */
   232    232   void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   233    233     assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   234    234     sqlite3VdbeMemSetZeroBlob(&pCtx->s, SQLITE_MAX_LENGTH+1);
   235    235   }
   236    236   
          237  +/* An SQLITE_NOMEM error. */
          238  +void sqlite3_result_error_nomem(sqlite3_context *pCtx){
          239  +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
          240  +  sqlite3VdbeMemSetNull(&pCtx->s);
          241  +  pCtx->isError = 1;
          242  +  pCtx->s.db->mallocFailed = 1;
          243  +}
   237    244   
   238    245   /*
   239    246   ** Execute the statement pStmt, either until a row of data is ready, the
   240    247   ** statement is completely executed or an error occurs.
   241    248   **
   242    249   ** This routine implements the bulk of the logic behind the sqlite_step()
   243    250   ** API.  The only thing omitted is the automatic recompile if a 

Changes to src/vdbeaux.c.

   111    111   */
   112    112   static void resizeOpArray(Vdbe *p, int N){
   113    113     int runMode = p->magic==VDBE_MAGIC_RUN;
   114    114     if( runMode || p->nOpAlloc<N ){
   115    115       VdbeOp *pNew;
   116    116       int nNew = N + 100*(!runMode);
   117    117       int oldSize = p->nOpAlloc;
   118         -    pNew = sqlite3_realloc(p->aOp, nNew*sizeof(Op));
          118  +    pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   119    119       if( pNew ){
   120    120         p->nOpAlloc = nNew;
   121    121         p->aOp = pNew;
   122    122         if( nNew>oldSize ){
   123    123           memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
   124    124         }
   125         -    }else{
   126         -      p->db->mallocFailed = 1;
   127    125       }
   128    126     }
   129    127   }
   130    128   
   131    129   /*
   132    130   ** Add a new instruction to the list of instructions current in the
   133    131   ** VDBE.  Return the address of the new instruction.

Changes to src/vdbemem.c.

   256    256       if( pMem->z && pMem->z!=pMem->zShort ){
   257    257         sqlite3_free( pMem->z );
   258    258       }
   259    259       *pMem = ctx.s;
   260    260       if( pMem->flags & MEM_Short ){
   261    261         pMem->z = pMem->zShort;
   262    262       }
   263         -    if( ctx.isError ){
   264         -      rc = SQLITE_ERROR;
   265         -    }
          263  +    rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
   266    264     }
   267    265     return rc;
   268    266   }
   269    267   
   270    268   /*
   271    269   ** Release any memory held by the Mem. This may leave the Mem in an
   272    270   ** inconsistent state, for example with (Mem.z==0) and

Changes to src/vtab.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 help implement virtual tables.
    13     13   **
    14         -** $Id: vtab.c,v 1.54 2007/08/24 03:51:34 drh Exp $
           14  +** $Id: vtab.c,v 1.55 2007/08/29 12:31:29 danielk1977 Exp $
    15     15   */
    16     16   #ifndef SQLITE_OMIT_VIRTUALTABLE
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   static int createModule(
    20     20     sqlite3 *db,                    /* Database in which module is registered */
    21     21     const char *zName,              /* Name assigned to this module */
................................................................................
   292    292     else {
   293    293       Table *pOld;
   294    294       Schema *pSchema = pTab->pSchema;
   295    295       const char *zName = pTab->zName;
   296    296       int nName = strlen(zName) + 1;
   297    297       pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   298    298       if( pOld ){
          299  +      db->mallocFailed = 1;
   299    300         assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   300    301         return;
   301    302       }
   302    303       pSchema->db = pParse->db;
   303    304       pParse->pNewTable = 0;
   304    305     }
   305    306   }

Changes to src/where.c.

    12     12   ** This module contains C code that generates VDBE code used to process
    13     13   ** the WHERE clause of SQL statements.  This module is reponsible for
    14     14   ** generating the code that loops through a table looking for applicable
    15     15   ** rows.  Indices are selected and used to speed the search when doing
    16     16   ** so is applicable.  Because this module is responsible for selecting
    17     17   ** indices, you might also think of this module as the "query optimizer".
    18     18   **
    19         -** $Id: where.c,v 1.257 2007/08/16 11:36:15 danielk1977 Exp $
           19  +** $Id: where.c,v 1.258 2007/08/29 12:31:29 danielk1977 Exp $
    20     20   */
    21     21   #include "sqliteInt.h"
    22     22   
    23     23   /*
    24     24   ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
    25     25   */
    26     26   #define BMS  (sizeof(Bitmask)*8)
................................................................................
   787    787       int i;
   788    788       static const u8 ops[] = {TK_GE, TK_LE};
   789    789       assert( pList!=0 );
   790    790       assert( pList->nExpr==2 );
   791    791       for(i=0; i<2; i++){
   792    792         Expr *pNewExpr;
   793    793         int idxNew;
   794         -      pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(db, pExpr->pLeft),
          794  +      pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
   795    795                                sqlite3ExprDup(db, pList->a[i].pExpr), 0);
   796    796         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   797    797         exprAnalyze(pSrc, pWC, idxNew);
   798    798         pTerm = &pWC->a[idxTerm];
   799    799         pWC->a[idxNew].iParent = idxTerm;
   800    800       }
   801    801       pTerm->nChild = 2;
................................................................................
   854    854           if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
   855    855           pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
   856    856           pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
   857    857           pLeft = pOrTerm->pExpr->pLeft;
   858    858         }
   859    859         assert( pLeft!=0 );
   860    860         pDup = sqlite3ExprDup(db, pLeft);
   861         -      pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
          861  +      pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
   862    862         if( pNew ){
   863    863           int idxNew;
   864    864           transferJoinMarkings(pNew, pExpr);
   865    865           pNew->pList = pList;
   866    866           idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   867    867           exprAnalyze(pSrc, pWC, idxNew);
   868    868           pTerm = &pWC->a[idxTerm];
................................................................................
   930    930   
   931    931       pRight = pExpr->pList->a[0].pExpr;
   932    932       pLeft = pExpr->pList->a[1].pExpr;
   933    933       prereqExpr = exprTableUsage(pMaskSet, pRight);
   934    934       prereqColumn = exprTableUsage(pMaskSet, pLeft);
   935    935       if( (prereqExpr & prereqColumn)==0 ){
   936    936         Expr *pNewExpr;
   937         -      pNewExpr = sqlite3Expr(TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
          937  +      pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
   938    938         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   939    939         pNewTerm = &pWC->a[idxNew];
   940    940         pNewTerm->prereqRight = prereqExpr;
   941    941         pNewTerm->leftCursor = pLeft->iTable;
   942    942         pNewTerm->leftColumn = pLeft->iColumn;
   943    943         pNewTerm->eOperator = WO_MATCH;
   944    944         pNewTerm->iParent = idxTerm;

Changes to test/capi3.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 script testing the callback-free C/C++ API.
    13     13   #
    14         -# $Id: capi3.test,v 1.53 2007/08/25 13:37:49 danielk1977 Exp $
           14  +# $Id: capi3.test,v 1.54 2007/08/29 12:31:29 danielk1977 Exp $
    15     15   #
    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   # Return the UTF-16 representation of the supplied UTF-8 string $str.
    21     21   # If $nt is true, append two 0x00 bytes as a nul terminator.
................................................................................
   750    750   }
   751    751   
   752    752   # Test the error message when a "real" out of memory occurs.
   753    753   if {[info command sqlite3_memdebug_fail]!=""} {
   754    754     do_test capi3-10-1 {
   755    755       sqlite3 db test.db
   756    756       set DB [sqlite3_connection_pointer db]
   757         -    sqlite3_memdebug_fail 0 0
          757  +    sqlite3_memdebug_fail 0
   758    758       catchsql {
   759    759         select * from sqlite_master;
   760    760       }
   761    761     } {1 {out of memory}}
   762    762     do_test capi3-10-2 {
   763    763       sqlite3_errmsg $::DB
   764    764     } {out of memory}
   765    765     ifcapable {utf16} {
   766    766       do_test capi3-10-3 {
   767    767         utf8 [sqlite3_errmsg16 $::DB]
   768    768       } {out of memory}
   769    769     }
   770    770     db close
   771         -  sqlite3_memdebug_fail -1 0
          771  +  sqlite3_memdebug_fail -1
   772    772   }
   773    773   
   774    774   # The following tests - capi3-11.* - test that a COMMIT or ROLLBACK
   775    775   # statement issued while there are still outstanding VMs that are part of
   776    776   # the transaction fails.
   777    777   sqlite3 db test.db
   778    778   set DB [sqlite3_connection_pointer db]

Changes to test/capi3c.test.

     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  
    12     12   #
    13     13   # This is a copy of the capi3.test file that has been adapted to
    14     14   # test the new sqlite3_prepare_v2 interface.
    15     15   #
    16         -# $Id: capi3c.test,v 1.10 2007/08/25 13:37:49 danielk1977 Exp $
           16  +# $Id: capi3c.test,v 1.11 2007/08/29 12:31:29 danielk1977 Exp $
    17     17   #
    18     18   
    19     19   set testdir [file dirname $argv0]
    20     20   source $testdir/tester.tcl
    21     21   
    22     22   # Return the UTF-16 representation of the supplied UTF-8 string $str.
    23     23   # If $nt is true, append two 0x00 bytes as a nul terminator.
................................................................................
   745    745   }
   746    746   
   747    747   # Test the error message when a "real" out of memory occurs.
   748    748   if {[info command sqlite3_memdebug_fail]!=""} {
   749    749     do_test capi3c-10-1 {
   750    750       sqlite3 db test.db
   751    751       set DB [sqlite3_connection_pointer db]
   752         -    sqlite3_memdebug_fail 0 0
          752  +    sqlite3_memdebug_fail 0
   753    753       catchsql {
   754    754         select * from sqlite_master;
   755    755       }
   756    756     } {1 {out of memory}}
   757    757     do_test capi3c-10-2 {
   758    758       sqlite3_errmsg $::DB
   759    759     } {out of memory}
   760    760     ifcapable {utf16} {
   761    761       do_test capi3c-10-3 {
   762    762         utf8 [sqlite3_errmsg16 $::DB]
   763    763       } {out of memory}
   764    764     }
   765    765     db close
   766         -  sqlite3_memdebug_fail -1 0
          766  +  sqlite3_memdebug_fail -1
   767    767   }
   768    768   
   769    769   # The following tests - capi3c-11.* - test that a COMMIT or ROLLBACK
   770    770   # statement issued while there are still outstanding VMs that are part of
   771    771   # the transaction fails.
   772    772   sqlite3 db test.db
   773    773   set DB [sqlite3_connection_pointer db]

Changes to test/incrblob_err.test.

     5      5   #
     6      6   #    May you do good and not evil.
     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   #
    12         -# $Id: incrblob_err.test,v 1.5 2007/08/27 23:48:24 drh Exp $
           12  +# $Id: incrblob_err.test,v 1.6 2007/08/29 12:31:29 danielk1977 Exp $
    13     13   #
    14     14   
    15     15   set testdir [file dirname $argv0]
    16     16   source $testdir/tester.tcl
    17     17   
    18     18   ifcapable {!incrblob  || !memdebug} {
    19     19     finish_test
................................................................................
    75     75       error "Bad data read..."
    76     76     }
    77     77     set rc [catch {close $::blob}]
    78     78     if {$rc} { 
    79     79       error "out of memory" 
    80     80     }
    81     81   } 
    82         -sqlite3_memdebug_fail -1 0
           82  +sqlite3_memdebug_fail -1
    83     83   
    84     84   do_ioerr_test incrblob_err-4 -cksum 1 -sqlprep {
    85     85     CREATE TABLE blobs(k, v BLOB);
    86     86     INSERT INTO blobs VALUES(1, $::data);
    87     87   } -tclbody {
    88     88     set ::blob [db incrblob blobs v 1]
    89     89     read $::blob

Changes to test/malloc.test.

    12     12   # This file attempts to check the behavior of the SQLite library in 
    13     13   # an out-of-memory situation. When compiled with -DSQLITE_DEBUG=1, 
    14     14   # the SQLite library accepts a special command (sqlite3_memdebug_fail N C)
    15     15   # which causes the N-th malloc to fail.  This special feature is used
    16     16   # to see what happens in the library if a malloc were to really fail
    17     17   # due to an out-of-memory situation.
    18     18   #
    19         -# $Id: malloc.test,v 1.44 2007/08/22 20:18:22 drh Exp $
           19  +# $Id: malloc.test,v 1.45 2007/08/29 12:31:29 danielk1977 Exp $
    20     20   
    21     21   set testdir [file dirname $argv0]
    22     22   source $testdir/tester.tcl
    23     23   
    24     24   # Only run these tests if memory debugging is turned on.
    25     25   #
    26     26   ifcapable !memdebug {
................................................................................
   211    211       }
   212    212       append ::bomstr [encoding convertto unicode "123456789_123456789_12345678"]
   213    213     } -tclbody {
   214    214       sqlite3_column_text16 $::STMT 0
   215    215       sqlite3_column_int $::STMT 0
   216    216       sqlite3_column_text16 $::STMT 1
   217    217       sqlite3_column_double $::STMT 1
   218         -    sqlite3_reset $::STMT
          218  +    set rc [sqlite3_reset $::STMT]
          219  +    if {$rc eq "SQLITE_NOMEM"} {error "out of memory"}
   219    220       sqlite3_bind_text16 $::STMT 1 $::bomstr 60
   220    221       #catch {sqlite3_finalize $::STMT}
   221    222       #if {[lindex [sqlite_malloc_stat] 2]<=0} {
   222    223       #  error "out of memory"
   223    224       #}
   224    225     } -cleanup {
   225    226       if {$::STMT!=""} {

Changes to test/malloc2.test.

    12     12   # This file attempts to check that the library can recover from a malloc()
    13     13   # failure when sqlite3_global_recover() is invoked.
    14     14   #
    15     15   # (Later:) The sqlite3_global_recover() interface is now a no-op.
    16     16   # Recovery from malloc() failures is automatic.  But we keep these
    17     17   # tests around because you can never have too many test cases.
    18     18   #
    19         -# $Id: malloc2.test,v 1.6 2007/08/22 22:04:37 drh Exp $
           19  +# $Id: malloc2.test,v 1.7 2007/08/29 12:31:29 danielk1977 Exp $
    20     20   
    21     21   set testdir [file dirname $argv0]
    22     22   source $testdir/tester.tcl
    23     23   
    24     24   # Only run these tests if memory debugging is turned on.
    25     25   #
    26     26   ifcapable !memdebug {
................................................................................
    61     61     array set ::mallocopts $args
    62     62     set sum [cksum db]
    63     63   
    64     64     for {set ::n 1} {true} {incr ::n} {
    65     65   
    66     66       # Run the SQL. Malloc number $::n is set to fail. A malloc() failure
    67     67       # may or may not be reported.
    68         -    sqlite3_memdebug_fail $::n 1
           68  +    sqlite3_memdebug_fail $::n -repeat 1
    69     69       do_test malloc2-$tn.$::n.2 {
    70     70         set res [catchsql [string trim $::mallocopts(-sql)]]
    71     71         set rc [expr { 
    72     72           0==[string compare $res {1 {out of memory}}] ||
    73     73           0==[lindex $res 0]
    74     74         }]
    75     75         if {$rc!=1} {
................................................................................
    76     76           puts "Error: $res"
    77     77         }
    78     78         set rc
    79     79       } {1}
    80     80   
    81     81       # If $::n is greater than the number of malloc() calls required to
    82     82       # execute the SQL, then this test is finished. Break out of the loop.
    83         -    set nFail [sqlite3_memdebug_fail -1 -1]
           83  +    set nFail [sqlite3_memdebug_fail -1]
    84     84       if {$nFail==0} break
    85     85   
    86     86       # Nothing should work now, because the allocator should refuse to
    87     87       # allocate any memory.
    88     88       #
    89     89       # Update: SQLite now automatically recovers from a malloc() failure.
    90     90       # So the statement in the test below would work. 

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.11 2007/08/22 22:04:37 drh Exp $
           16  +# $Id: malloc3.test,v 1.12 2007/08/29 12:31:29 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   #
    23     23   ifcapable !memdebug {
................................................................................
   556    556           incr pc
   557    557         }
   558    558   
   559    559         -sql {
   560    560           set ::rollback_hook_count 0
   561    561   
   562    562           set ac [sqlite3_get_autocommit $::DB]        ;# Auto-Commit
   563         -        sqlite3_memdebug_fail $iFail 1
          563  +        sqlite3_memdebug_fail $iFail -repeat 1
   564    564           set rc [catch {db eval [lindex $v 1]} msg]   ;# True error occurs
   565    565           set nac [sqlite3_get_autocommit $::DB]       ;# New Auto-Commit 
   566    566   
   567    567   
   568    568           if {$rc != 0 && $nac && !$ac} {
   569    569             # Before [db eval] the auto-commit flag was clear. Now it
   570    570             # is set. Since an error occured we assume this was not a
................................................................................
   571    571   	  # commit - therefore a rollback occured. Check that the
   572    572   	  # rollback-hook was invoked.
   573    573             do_test malloc3-rollback_hook.$iterid {
   574    574               set ::rollback_hook_count
   575    575             } {1}
   576    576           }
   577    577   
   578         -        set nFail [sqlite3_memdebug_fail -1 -1]
          578  +        set nFail [sqlite3_memdebug_fail -1]
   579    579           if {$rc == 0} {
   580    580               # Successful execution of sql. Our "mallocs-until-failure" 
   581    581               # count should be greater than 0. Otherwise a malloc() failed
   582    582               # and the error was not reported.
   583    583               if {$nFail>0} {
   584    584                 error "Unreported malloc() failure"
   585    585               }
................................................................................
   635    635   }
   636    636   
   637    637   # Turn of the Tcl interface's prepared statement caching facility.
   638    638   db cache size 0
   639    639   
   640    640   run_test $::run_test_script 9 1
   641    641   # run_test [lrange $::run_test_script 0 3] 0 63
   642         -sqlite3_memdebug_fail -1 -1
          642  +sqlite3_memdebug_fail -1
   643    643   db close
   644    644   
   645    645   finish_test

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.5 2007/08/23 02:47:53 drh Exp $
           15  +# $Id: malloc4.test,v 1.6 2007/08/29 12:31:29 danielk1977 Exp $
    16     16   
    17     17   #---------------------------------------------------------------------------
    18     18   # NOTES ON EXPECTED BEHAVIOUR
    19     19   #
    20     20   # [193] When a memory allocation failure occurs during sqlite3_column_name(),
    21     21   #       sqlite3_column_name16(), sqlite3_column_decltype(), or
    22     22   #       sqlite3_column_decltype16() the function shall return NULL.
................................................................................
    47     47       # Prepare the statement
    48     48       do_test ${testid}.1 {
    49     49         set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL]
    50     50         expr [string length $::STMT] > 0
    51     51       } {1}
    52     52   
    53     53       # Set the Nth malloc() to fail.
    54         -    sqlite3_memdebug_fail $n 1
           54  +    sqlite3_memdebug_fail $n -repeat 1
    55     55   
    56     56       # Test malloc failure in the _name(), _name16(), decltype() and
    57     57       # decltype16() APIs. Calls that occur after the malloc() failure should
    58     58       # return NULL. No error is raised though.
    59     59       #
    60     60       # ${testid}.2.1 - Call _name()
    61     61       # ${testid}.2.2 - Call _name16()

Changes to test/mallocA.test.

     6      6   #    May you do good and not evil.
     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 contains additional out-of-memory checks (see malloc.tcl).
    12     12   #
    13         -# $Id: mallocA.test,v 1.3 2007/08/22 22:04:37 drh Exp $
           13  +# $Id: mallocA.test,v 1.4 2007/08/29 12:31:29 danielk1977 Exp $
    14     14   
    15     15   set testdir [file dirname $argv0]
    16     16   source $testdir/tester.tcl
    17     17   
    18     18   # Only run these tests if memory debugging is turned on.
    19     19   #
    20     20   ifcapable !memdebug {
................................................................................
    37     37     CREATE INDEX t1i2 ON t1(b,c);
    38     38     CREATE TABLE t2(x,y,z);
    39     39   }
    40     40   db close
    41     41   file copy test.db test.db.bu
    42     42   
    43     43   
    44         -do_malloc_test 1 -testdb test.db.bu -sqlbody {
           44  +do_malloc_test mallocA-1 -testdb test.db.bu -sqlbody {
    45     45     ANALYZE
    46     46   }
    47         -do_malloc_test 2 -testdb test.db.bu -sqlbody {
           47  +do_malloc_test mallocA-2 -testdb test.db.bu -sqlbody {
    48     48     REINDEX;
    49     49   }
    50         -do_malloc_test 3 -testdb test.db.bu -sqlbody {
           50  +do_malloc_test mallocA-3 -testdb test.db.bu -sqlbody {
    51     51     REINDEX t1;
    52     52   }
    53         -do_malloc_test 4 -testdb test.db.bu -sqlbody {
           53  +do_malloc_test mallocA-4 -testdb test.db.bu -sqlbody {
    54     54     REINDEX main.t1;
    55     55   }
    56         -do_malloc_test 5 -testdb test.db.bu -sqlbody {
           56  +do_malloc_test mallocA-5 -testdb test.db.bu -sqlbody {
    57     57     REINDEX nocase;
    58     58   }
    59     59   
    60     60   # Ensure that no file descriptors were leaked.
    61     61   do_test malloc-99.X {
    62     62     catch {db close}
    63     63     set sqlite_open_file_count
    64     64   } {0}
    65     65   
    66     66   file delete -force test.db.bu
    67     67   finish_test

Changes to test/mallocC.test.

     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # 
    12     12   # This file tests aspects of the malloc failure while parsing
    13     13   # CREATE TABLE statements in auto_vacuum mode.
    14     14   #
    15         -# $Id: mallocC.test,v 1.3 2007/08/22 22:04:37 drh Exp $
           15  +# $Id: mallocC.test,v 1.4 2007/08/29 12:31:29 danielk1977 Exp $
    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   # Only run these tests if memory debugging is turned on.
    21     21   #
    22     22   ifcapable !memdebug {
................................................................................
    57     57     array set ::mallocopts $args
    58     58     set sum [cksum db]
    59     59   
    60     60     for {set ::n 1} {true} {incr ::n} {
    61     61   
    62     62       # Run the SQL. Malloc number $::n is set to fail. A malloc() failure
    63     63       # may or may not be reported.
    64         -    sqlite3_memdebug_fail $::n 1
           64  +    sqlite3_memdebug_fail $::n -repeat 1
    65     65       do_test mallocC-$tn.$::n.1 {
    66     66         set res [catchsql [string trim $::mallocopts(-sql)]]
    67     67         set rc [expr { 
    68     68           0==[string compare $res {1 {out of memory}}] ||
    69     69           0==[lindex $res 0]
    70     70         }]
    71     71         if {$rc!=1} {
................................................................................
    72     72           puts "Error: $res"
    73     73         }
    74     74         set rc
    75     75       } {1}
    76     76   
    77     77       # If $::n is greater than the number of malloc() calls required to
    78     78       # execute the SQL, then this test is finished. Break out of the loop.
    79         -    set nFail [sqlite3_memdebug_fail -1 -1]
           79  +    set nFail [sqlite3_memdebug_fail -1]
    80     80       if {$nFail==0} {
    81     81         break
    82     82       }
    83     83   
    84     84       # Recover from the malloc failure.
    85     85       #
    86     86       # Update: The new malloc() failure handling means that a transaction may

Changes to test/malloc_common.tcl.

    38     38     }
    39     39     if {[info exists ::mallocopts(-start)]} {
    40     40       set start $::mallocopts(-start)
    41     41     } else {
    42     42       set start 1
    43     43     }
    44     44   
    45         -  set ::go 1
    46         -  for {set ::n $start} {$::go && $::n < 50000} {incr ::n} {
    47         -    do_test $tn.$::n {
           45  +  foreach ::iRepeat {0 1} {
           46  +    set ::go 1
           47  +    for {set ::n $start} {$::go && $::n < 50000} {incr ::n} {
    48     48   
    49         -      # Remove all traces of database files test.db and test2.db from the files
    50         -      # system. Then open (empty database) "test.db" with the handle [db].
    51         -      # 
    52         -      catch {db close} 
    53         -      catch {file delete -force test.db}
    54         -      catch {file delete -force test.db-journal}
    55         -      catch {file delete -force test2.db}
    56         -      catch {file delete -force test2.db-journal}
    57         -      if {[info exists ::mallocopts(-testdb)]} {
    58         -        file copy $::mallocopts(-testdb) test.db
    59         -      }
    60         -      catch {sqlite3 db test.db} 
    61         -
    62         -      # Execute any -tclprep and -sqlprep scripts.
           49  +      # If $::iRepeat is 0, then the malloc() failure is transient - it
           50  +      # fails and then subsequent calls succeed. If $::iRepeat is 1, 
           51  +      # then the failure is persistent - once malloc() fails it keeps
           52  +      # failing.
    63     53         #
    64         -      if {[info exists ::mallocopts(-tclprep)]} {
    65         -        eval $::mallocopts(-tclprep)
    66         -      }
    67         -      if {[info exists ::mallocopts(-sqlprep)]} {
    68         -        execsql $::mallocopts(-sqlprep)
    69         -      }
           54  +      set zRepeat "transient"
           55  +      if {$::iRepeat} {set zRepeat "persistent"}
           56  +
           57  +      do_test ${tn}.${zRepeat}.${::n} {
           58  +  
           59  +        # Remove all traces of database files test.db and test2.db 
           60  +        # from the file-system. Then open (empty database) "test.db" 
           61  +        # with the handle [db].
           62  +        # 
           63  +        catch {db close} 
           64  +        catch {file delete -force test.db}
           65  +        catch {file delete -force test.db-journal}
           66  +        catch {file delete -force test2.db}
           67  +        catch {file delete -force test2.db-journal}
           68  +        if {[info exists ::mallocopts(-testdb)]} {
           69  +          file copy $::mallocopts(-testdb) test.db
           70  +        }
           71  +        catch {sqlite3 db test.db} 
           72  +  
           73  +        # Execute any -tclprep and -sqlprep scripts.
           74  +        #
           75  +        if {[info exists ::mallocopts(-tclprep)]} {
           76  +          eval $::mallocopts(-tclprep)
           77  +        }
           78  +        if {[info exists ::mallocopts(-sqlprep)]} {
           79  +          execsql $::mallocopts(-sqlprep)
           80  +        }
           81  +  
           82  +        # Now set the ${::n}th malloc() to fail and execute the -tclbody 
           83  +        # and -sqlbody scripts.
           84  +        #
           85  +        sqlite3_memdebug_fail $::n -repeat $::iRepeat
           86  +        set ::mallocbody {}
           87  +        if {[info exists ::mallocopts(-tclbody)]} {
           88  +          append ::mallocbody "$::mallocopts(-tclbody)\n"
           89  +        }
           90  +        if {[info exists ::mallocopts(-sqlbody)]} {
           91  +          append ::mallocbody "db eval {$::mallocopts(-sqlbody)}"
           92  +        }
           93  +
           94  +        # The following block sets local variables as follows:
           95  +        #
           96  +        #     isFail  - True if an error (any error) was reported by sqlite.
           97  +        #     nFail   - The total number of simulated malloc() failures.
           98  +        #     nBenign - The number of benign simulated malloc() failures.
           99  +        #
          100  +        set isFail [catch $::mallocbody msg]
          101  +        set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign]
          102  +#puts "isFail=$isFail nFail=$nFail nBenign=$nBenign msg=$msg"
    70    103   
    71         -      # Now set the ${::n}th malloc() to fail and execute the -tclbody and
    72         -      # -sqlbody scripts.
    73         -      #
    74         -      sqlite3_memdebug_fail $::n 1
    75         -      set ::mallocbody {}
    76         -      if {[info exists ::mallocopts(-tclbody)]} {
    77         -        append ::mallocbody "$::mallocopts(-tclbody)\n"
    78         -      }
    79         -      if {[info exists ::mallocopts(-sqlbody)]} {
    80         -        append ::mallocbody "db eval {$::mallocopts(-sqlbody)}"
    81         -      }
    82         -      set v [catch $::mallocbody msg]
    83         -      set failFlag [sqlite3_memdebug_fail -1 0]
    84         -      set go [expr {$failFlag>0}]
          104  +        # If one or more mallocs failed, run this loop body again.
          105  +        #
          106  +        set go [expr {$nFail>0}]
    85    107   
    86         -
    87         -      if {$failFlag==0} {
    88         -        if {$v} {
          108  +        if {($nFail-$nBenign)==0} {
          109  +          if {$isFail} {
          110  +            set v2 $msg
          111  +          } else {
          112  +            set isFail 1
          113  +            set v2 1
          114  +          }
          115  +        } elseif {!$isFail} {
    89    116             set v2 $msg
    90         -        } else {
    91         -          set v 1
          117  +        } elseif {[info command db]=="" || [db errorcode]==7
          118  +                     || $msg=="out of memory"} {
    92    119             set v2 1
          120  +        } else {
          121  +          set v2 $msg
    93    122           }
    94         -      } elseif {!$v} {
    95         -        set v2 $msg
    96         -      } elseif {[info command db]=="" || [db errorcode]==7
    97         -                   || $msg=="out of memory"} {
    98         -        set v2 1
    99         -      } else {
   100         -        set v2 $msg
          123  +        lappend isFail $v2
          124  +      } {1 1}
          125  +  
          126  +      if {[info exists ::mallocopts(-cleanup)]} {
          127  +        catch [list uplevel #0 $::mallocopts(-cleanup)] msg
   101    128         }
   102         -      lappend v $v2
   103         -    } {1 1}
   104         -
   105         -    if {[info exists ::mallocopts(-cleanup)]} {
   106         -      catch [list uplevel #0 $::mallocopts(-cleanup)] msg
   107    129       }
   108    130     }
   109    131     unset ::mallocopts
   110    132   }

Changes to test/vtab_err.test.

     5      5   #
     6      6   #    May you do good and not evil.
     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   #
    12         -# $Id: vtab_err.test,v 1.6 2007/08/25 13:37:49 danielk1977 Exp $
           12  +# $Id: vtab_err.test,v 1.7 2007/08/29 12:31:29 danielk1977 Exp $
    13     13   
    14     14   set testdir [file dirname $argv0]
    15     15   source $testdir/tester.tcl
    16     16   
    17     17   source $testdir/malloc_common.tcl
    18     18   
    19     19   ifcapable !vtab {
................................................................................
    36     36     BEGIN;
    37     37       CREATE TABLE r2(a, b, c);
    38     38       INSERT INTO r2 SELECT * FROM e;
    39     39       INSERT INTO e SELECT a||'x', b, c FROM r2;
    40     40     COMMIT;
    41     41   }
    42     42   
    43         -do_malloc_test vtab_err-2 -tclprep {
           43  +do_malloc_test vtab_err-2 -tclprep { 
    44     44     register_echo_module [sqlite3_connection_pointer db]
    45     45   } -sqlbody {
    46     46     BEGIN;
    47     47     CREATE TABLE r(a PRIMARY KEY, b, c);
    48     48     CREATE VIRTUAL TABLE e USING echo(r);
    49     49     INSERT INTO e VALUES(1, 2, 3);
    50     50     INSERT INTO e VALUES('a', 'b', 'c');
................................................................................
    54     54     BEGIN;
    55     55       CREATE TABLE r2(a, b, c);
    56     56       INSERT INTO r2 SELECT * FROM e;
    57     57       INSERT INTO e SELECT a||'x', b, c FROM r2;
    58     58     COMMIT;
    59     59   } 
    60     60   
    61         -sqlite3_memdebug_fail -1 0
           61  +sqlite3_memdebug_fail -1
    62     62   
    63     63   finish_test