/ Check-in [e1606658]
Login

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

Overview
Comment:Some elements of the new malloc() failure handling. Not all cases work properly yet. Also, library is not threadsafe if malloc() fails right now. (CVS 2800)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:e1606658f1b4530e3001db4779b5669c8d13c853
User & Date: danielk1977 2005-12-06 12:52:59
Context
2005-12-06
12:57
Add test file for new malloc() failure handling. (CVS 2801) check-in: 0b82f962 user: danielk1977 tags: trunk
12:52
Some elements of the new malloc() failure handling. Not all cases work properly yet. Also, library is not threadsafe if malloc() fails right now. (CVS 2800) check-in: e1606658 user: danielk1977 tags: trunk
2005-12-05
22:22
Update mailing list hyperlink on the support page. (CVS 2799) check-in: 41a7aeee user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/alter.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 used to generate VDBE code
    13     13   ** that implements the ALTER TABLE command.
    14     14   **
    15         -** $Id: alter.c,v 1.9 2005/10/20 07:28:18 drh Exp $
           15  +** $Id: alter.c,v 1.10 2005/12/06 12:52:59 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <ctype.h>
    19     19   
    20     20   /*
    21     21   ** The code in this file only exists if we are not omitting the
    22     22   ** ALTER TABLE logic from the build.
................................................................................
   254    254     char *zName = 0;          /* NULL-terminated version of pName */ 
   255    255     sqlite3 *db = pParse->db; /* Database connection */
   256    256     Vdbe *v;
   257    257   #ifndef SQLITE_OMIT_TRIGGER
   258    258     char *zWhere = 0;         /* Where clause to locate temp triggers */
   259    259   #endif
   260    260     
   261         -  if( sqlite3_malloc_failed ) goto exit_rename_table;
          261  +  if( sqlite3Tsd()->mallocFailed ) goto exit_rename_table;
   262    262     assert( pSrc->nSrc==1 );
   263    263   
   264    264     pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   265    265     if( !pTab ) goto exit_rename_table;
   266    266     iDb = pTab->iDb;
   267    267     zDb = db->aDb[iDb].zName;
   268    268   
................................................................................
   500    500     int iDb;
   501    501     int i;
   502    502     int nAlloc;
   503    503   
   504    504   
   505    505     /* Look up the table being altered. */
   506    506     assert( pParse->pNewTable==0 );
   507         -  if( sqlite3_malloc_failed ) goto exit_begin_add_column;
          507  +  if( sqlite3Tsd()->mallocFailed ) goto exit_begin_add_column;
   508    508     pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   509    509     if( !pTab ) goto exit_begin_add_column;
   510    510   
   511    511     /* Make sure this is not an attempt to ALTER a view. */
   512    512     if( pTab->pSelect ){
   513    513       sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   514    514       goto exit_begin_add_column;

Changes to src/attach.c.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the ATTACH and DETACH commands.
    13     13   **
    14         -** $Id: attach.c,v 1.34 2005/08/20 03:03:04 drh Exp $
           14  +** $Id: attach.c,v 1.35 2005/12/06 12:52:59 danielk1977 Exp $
    15     15   */
    16     16   #include "sqliteInt.h"
    17     17   
    18     18   /*
    19     19   ** This routine is called by the parser to process an ATTACH statement:
    20     20   **
    21     21   **     ATTACH DATABASE filename AS dbname
................................................................................
   146    146         db->aDb[i].pBt = 0;
   147    147       }
   148    148       sqlite3ResetInternalSchema(db, 0);
   149    149       assert( pParse->nErr>0 );  /* Always set by sqlite3ReadSchema() */
   150    150       if( pParse->rc==SQLITE_OK ){
   151    151         pParse->rc = SQLITE_ERROR;
   152    152       }
          153  +    db->nDb = i;
   153    154     }
   154    155   
   155    156   attach_end:
   156    157     sqliteFree(zFile);
   157    158     sqliteFree(zName);
   158    159   }
   159    160   

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.355 2005/11/14 22:29:05 drh Exp $
           25  +** $Id: build.c,v 1.356 2005/12/06 12:52:59 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.
................................................................................
    46     46   ** Note that if an error occurred, it might be the case that
    47     47   ** no VDBE code was generated.
    48     48   */
    49     49   void sqlite3FinishCoding(Parse *pParse){
    50     50     sqlite3 *db;
    51     51     Vdbe *v;
    52     52   
    53         -  if( sqlite3_malloc_failed ) return;
           53  +  if( sqlite3Tsd()->mallocFailed ) return;
    54     54     if( pParse->nested ) return;
    55     55     if( !pParse->pVdbe ){
    56     56       if( pParse->rc==SQLITE_OK && pParse->nErr ){
    57     57         pParse->rc = SQLITE_ERROR;
    58     58       }
    59     59       return;
    60     60     }
................................................................................
  1292   1292     Token *pCons,           /* The ',' token after the last column defn. */
  1293   1293     Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  1294   1294     Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
  1295   1295   ){
  1296   1296     Table *p;
  1297   1297     sqlite3 *db = pParse->db;
  1298   1298   
  1299         -  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
         1299  +  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3Tsd()->mallocFailed ) {
         1300  +    return;
         1301  +  }
  1300   1302     p = pParse->pNewTable;
  1301   1303     if( p==0 ) return;
  1302   1304   
  1303   1305     assert( !db->init.busy || !pSelect );
  1304   1306   
  1305   1307   #ifndef SQLITE_OMIT_CHECK
  1306   1308     /* Resolve names in all CHECK constraint expressions.
................................................................................
  1518   1520     /* Make a copy of the entire SELECT statement that defines the view.
  1519   1521     ** This will force all the Expr.token.z values to be dynamically
  1520   1522     ** allocated rather than point to the input string - which means that
  1521   1523     ** they will persist after the current sqlite3_exec() call returns.
  1522   1524     */
  1523   1525     p->pSelect = sqlite3SelectDup(pSelect);
  1524   1526     sqlite3SelectDelete(pSelect);
         1527  +  if( sqlite3Tsd()->mallocFailed ){
         1528  +    return;
         1529  +  }
  1525   1530     if( !pParse->db->init.busy ){
  1526   1531       sqlite3ViewGetColumnNames(pParse, p);
  1527   1532     }
  1528   1533   
  1529   1534     /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  1530   1535     ** the end.
  1531   1536     */
................................................................................
  1588   1593     ** "*" elements in the results set of the view and will assign cursors
  1589   1594     ** to the elements of the FROM clause.  But we do not want these changes
  1590   1595     ** to be permanent.  So the computation is done on a copy of the SELECT
  1591   1596     ** statement that defines the view.
  1592   1597     */
  1593   1598     assert( pTable->pSelect );
  1594   1599     pSel = sqlite3SelectDup(pTable->pSelect);
  1595         -  n = pParse->nTab;
  1596         -  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  1597         -  pTable->nCol = -1;
  1598         -  pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
  1599         -  pParse->nTab = n;
  1600         -  if( pSelTab ){
  1601         -    assert( pTable->aCol==0 );
  1602         -    pTable->nCol = pSelTab->nCol;
  1603         -    pTable->aCol = pSelTab->aCol;
  1604         -    pSelTab->nCol = 0;
  1605         -    pSelTab->aCol = 0;
  1606         -    sqlite3DeleteTable(0, pSelTab);
  1607         -    DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
  1608         -  }else{
  1609         -    pTable->nCol = 0;
         1600  +  if( pSel ){
         1601  +    n = pParse->nTab;
         1602  +    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
         1603  +    pTable->nCol = -1;
         1604  +    pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
         1605  +    pParse->nTab = n;
         1606  +    if( pSelTab ){
         1607  +      assert( pTable->aCol==0 );
         1608  +      pTable->nCol = pSelTab->nCol;
         1609  +      pTable->aCol = pSelTab->aCol;
         1610  +      pSelTab->nCol = 0;
         1611  +      pSelTab->aCol = 0;
         1612  +      sqlite3DeleteTable(0, pSelTab);
         1613  +      DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
         1614  +    }else{
         1615  +      pTable->nCol = 0;
         1616  +      nErr++;
         1617  +    }
         1618  +    sqlite3SelectDelete(pSel);
         1619  +  } else {
  1610   1620       nErr++;
  1611   1621     }
  1612         -  sqlite3SelectDelete(pSel);
  1613   1622     return nErr;  
  1614   1623   }
  1615   1624   #endif /* SQLITE_OMIT_VIEW */
  1616   1625   
  1617   1626   #ifndef SQLITE_OMIT_VIEW
  1618   1627   /*
  1619   1628   ** Clear the column names from every VIEW in database idx.
................................................................................
  1745   1754   */
  1746   1755   void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
  1747   1756     Table *pTab;
  1748   1757     Vdbe *v;
  1749   1758     sqlite3 *db = pParse->db;
  1750   1759     int iDb;
  1751   1760   
  1752         -  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
         1761  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto exit_drop_table;
  1753   1762     assert( pName->nSrc==1 );
  1754   1763     pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
  1755   1764   
  1756   1765     if( pTab==0 ) goto exit_drop_table;
  1757   1766     iDb = pTab->iDb;
  1758   1767     assert( iDb>=0 && iDb<db->nDb );
  1759   1768   #ifndef SQLITE_OMIT_AUTHORIZATION
................................................................................
  2094   2103     Token nullId;    /* Fake token for an empty ID list */
  2095   2104     DbFixer sFix;    /* For assigning database names to pTable */
  2096   2105     sqlite3 *db = pParse->db;
  2097   2106   
  2098   2107     int iDb;          /* Index of the database that is being written */
  2099   2108     Token *pName = 0; /* Unqualified name of the index to create */
  2100   2109   
  2101         -  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
         2110  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto exit_create_index;
  2102   2111   
  2103   2112     /*
  2104   2113     ** Find the table that is to be indexed.  Return early if not found.
  2105   2114     */
  2106   2115     if( pTblName!=0 ){
  2107   2116   
  2108   2117       /* Use the two-part index name to determine the database 
................................................................................
  2222   2231     }
  2223   2232   
  2224   2233     /* 
  2225   2234     ** Allocate the index structure. 
  2226   2235     */
  2227   2236     pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) +
  2228   2237                           (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr );
  2229         -  if( sqlite3_malloc_failed ) goto exit_create_index;
         2238  +  if( sqlite3Tsd()->mallocFailed ) goto exit_create_index;
  2230   2239     pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
  2231   2240     pIndex->aiRowEst = (unsigned*)&pIndex->aiColumn[pList->nExpr];
  2232   2241     pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1];
  2233   2242     strcpy(pIndex->zName, zName);
  2234   2243     pIndex->pTable = pTab;
  2235   2244     pIndex->nColumn = pList->nExpr;
  2236   2245     pIndex->onError = onError;
................................................................................
  2468   2477   ** implements the DROP INDEX statement.
  2469   2478   */
  2470   2479   void sqlite3DropIndex(Parse *pParse, SrcList *pName){
  2471   2480     Index *pIndex;
  2472   2481     Vdbe *v;
  2473   2482     sqlite3 *db = pParse->db;
  2474   2483   
  2475         -  if( pParse->nErr || sqlite3_malloc_failed ){
         2484  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ){
  2476   2485       goto exit_drop_index;
  2477   2486     }
  2478   2487     assert( pName->nSrc==1 );
  2479   2488     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2480   2489       goto exit_drop_index;
  2481   2490     }
  2482   2491     pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
................................................................................
  2675   2684   
  2676   2685   /*
  2677   2686   ** Assign cursors to all tables in a SrcList
  2678   2687   */
  2679   2688   void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  2680   2689     int i;
  2681   2690     struct SrcList_item *pItem;
  2682         -  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  2683         -    if( pItem->iCursor>=0 ) break;
  2684         -    pItem->iCursor = pParse->nTab++;
  2685         -    if( pItem->pSelect ){
  2686         -      sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
         2691  +  assert(pList || sqlite3Tsd()->mallocFailed);
         2692  +  if( pList ){
         2693  +    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
         2694  +      if( pItem->iCursor>=0 ) break;
         2695  +      pItem->iCursor = pParse->nTab++;
         2696  +      if( pItem->pSelect ){
         2697  +        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
         2698  +      }
  2687   2699       }
  2688   2700     }
  2689   2701   }
  2690   2702   
  2691   2703   /*
  2692   2704   ** Add an alias to the last identifier on the given identifier list.
  2693   2705   */
................................................................................
  2721   2733   */
  2722   2734   void sqlite3BeginTransaction(Parse *pParse, int type){
  2723   2735     sqlite3 *db;
  2724   2736     Vdbe *v;
  2725   2737     int i;
  2726   2738   
  2727   2739     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2728         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2740  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  2729   2741     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  2730   2742   
  2731   2743     v = sqlite3GetVdbe(pParse);
  2732   2744     if( !v ) return;
  2733   2745     if( type!=TK_DEFERRED ){
  2734   2746       for(i=0; i<db->nDb; i++){
  2735   2747         sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
................................................................................
  2742   2754   ** Commit a transaction
  2743   2755   */
  2744   2756   void sqlite3CommitTransaction(Parse *pParse){
  2745   2757     sqlite3 *db;
  2746   2758     Vdbe *v;
  2747   2759   
  2748   2760     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2749         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2761  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  2750   2762     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  2751   2763   
  2752   2764     v = sqlite3GetVdbe(pParse);
  2753   2765     if( v ){
  2754   2766       sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
  2755   2767     }
  2756   2768   }
................................................................................
  2759   2771   ** Rollback a transaction
  2760   2772   */
  2761   2773   void sqlite3RollbackTransaction(Parse *pParse){
  2762   2774     sqlite3 *db;
  2763   2775     Vdbe *v;
  2764   2776   
  2765   2777     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2766         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2778  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  2767   2779     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  2768   2780   
  2769   2781     v = sqlite3GetVdbe(pParse);
  2770   2782     if( v ){
  2771   2783       sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
  2772   2784     }
  2773   2785   }

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.4 2005/10/20 07:28:18 drh Exp $
           16  +** $Id: callback.c,v 1.5 2005/12/06 12:52:59 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.
................................................................................
   171    171         pColl[0].zName[nName] = 0;
   172    172         pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   173    173   
   174    174         /* If a malloc() failure occured in sqlite3HashInsert(), it will 
   175    175         ** return the pColl pointer to be deleted (because it wasn't added
   176    176         ** to the hash table).
   177    177         */
   178         -      assert( !pDel || (sqlite3_malloc_failed && pDel==pColl) );
          178  +      assert( !pDel || (sqlite3Tsd()->mallocFailed && pDel==pColl) );
   179    179         sqliteFree(pDel);
   180    180       }
   181    181     }
   182    182     return pColl;
   183    183   }
   184    184   
   185    185   /*

Changes to src/delete.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   ** in order to generate code for DELETE FROM statements.
    14     14   **
    15         -** $Id: delete.c,v 1.111 2005/09/20 17:42:23 drh Exp $
           15  +** $Id: delete.c,v 1.112 2005/12/06 12:52:59 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Look up every table that is named in pSrc.  If any table is not found,
    21     21   ** add an error message to pParse->zErrMsg and return NULL.  If all tables
    22     22   ** are found, return a pointer to the last table.
................................................................................
    98     98   
    99     99   #ifndef SQLITE_OMIT_TRIGGER
   100    100     int isView;                  /* True if attempting to delete from a view */
   101    101     int triggers_exist = 0;      /* True if any triggers exist */
   102    102   #endif
   103    103   
   104    104     sContext.pParse = 0;
   105         -  if( pParse->nErr || sqlite3_malloc_failed ){
          105  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ){
   106    106       goto delete_from_cleanup;
   107    107     }
   108    108     db = pParse->db;
   109    109     assert( pTabList->nSrc==1 );
   110    110   
   111    111     /* Locate the table which we want to delete.  This table has to be
   112    112     ** put in an SrcList structure because some of the subroutines we

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.240 2005/11/29 03:13:22 drh Exp $
           15  +** $Id: expr.c,v 1.241 2005/12/06 12:52:59 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   **
................................................................................
   259    259   /*
   260    260   ** Set the Expr.span field of the given expression to span all
   261    261   ** text between the two given tokens.
   262    262   */
   263    263   void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
   264    264     assert( pRight!=0 );
   265    265     assert( pLeft!=0 );
   266         -  if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
          266  +  if( !sqlite3Tsd()->mallocFailed && pRight->z && pLeft->z ){
   267    267       assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
   268    268       if( pLeft->dyn==0 && pRight->dyn==0 ){
   269    269         pExpr->span.z = pLeft->z;
   270    270         pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
   271    271       }else{
   272    272         pExpr->span.z = 0;
   273    273       }
................................................................................
   354    354       if( i>=pParse->nVarExpr ){
   355    355         pExpr->iTable = ++pParse->nVar;
   356    356         if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
   357    357           pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
   358    358           sqlite3ReallocOrFree((void**)&pParse->apVarExpr,
   359    359                          pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
   360    360         }
   361         -      if( !sqlite3_malloc_failed ){
          361  +      if( !sqlite3Tsd()->mallocFailed ){
   362    362           assert( pParse->apVarExpr!=0 );
   363    363           pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
   364    364         }
   365    365       }
   366    366     } 
   367    367   }
   368    368   
................................................................................
   458    458       if( pOldExpr->span.z!=0 && pNewExpr ){
   459    459         /* Always make a copy of the span for top-level expressions in the
   460    460         ** expression list.  The logic in SELECT processing that determines
   461    461         ** the names of columns in the result set needs this information */
   462    462         sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
   463    463       }
   464    464       assert( pNewExpr==0 || pNewExpr->span.z!=0 
   465         -            || pOldExpr->span.z==0 || sqlite3_malloc_failed );
          465  +            || pOldExpr->span.z==0 || sqlite3Tsd()->mallocFailed );
   466    466       pItem->zName = sqliteStrDup(pOldItem->zName);
   467    467       pItem->sortOrder = pOldItem->sortOrder;
   468    468       pItem->isAgg = pOldItem->isAgg;
   469    469       pItem->done = 0;
   470    470     }
   471    471     return pNew;
   472    472   }
................................................................................
   827    827     struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   828    828     NameContext *pTopNC = pNC;        /* First namecontext in the list */
   829    829   
   830    830     assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
   831    831     zDb = sqlite3NameFromToken(pDbToken);
   832    832     zTab = sqlite3NameFromToken(pTableToken);
   833    833     zCol = sqlite3NameFromToken(pColumnToken);
   834         -  if( sqlite3_malloc_failed ){
          834  +  if( sqlite3Tsd()->mallocFailed ){
   835    835       goto lookupname_end;
   836    836     }
   837    837   
   838    838     pExpr->iTable = -1;
   839    839     while( pNC && cnt==0 ){
   840    840       ExprList *pEList;
   841    841       SrcList *pSrcList = pNC->pSrcList;
................................................................................
  1301   1301     ** If all of the above are false, then we can run this code just once
  1302   1302     ** save the results, and reuse the same result on subsequent invocations.
  1303   1303     */
  1304   1304     if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
  1305   1305       int mem = pParse->nMem++;
  1306   1306       sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
  1307   1307       testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
  1308         -    assert( testAddr>0 || sqlite3_malloc_failed );
         1308  +    assert( testAddr>0 || sqlite3Tsd()->mallocFailed );
  1309   1309       sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
  1310   1310     }
  1311   1311   
  1312   1312     switch( pExpr->op ){
  1313   1313       case TK_IN: {
  1314   1314         char affinity;
  1315   1315         KeyInfo keyInfo;

Changes to src/insert.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 INSERT statements in SQLite.
    14     14   **
    15         -** $Id: insert.c,v 1.149 2005/11/24 13:15:33 drh Exp $
           15  +** $Id: insert.c,v 1.150 2005/12/06 12:52:59 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Set P3 of the most recently inserted opcode to a column affinity
    21     21   ** string for index pIdx. A column affinity string has one character
    22     22   ** for each column in the table, according to the affinity of the column:
................................................................................
   220    220     int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
   221    221   #endif
   222    222   
   223    223   #ifndef SQLITE_OMIT_AUTOINCREMENT
   224    224     int counterRowid;     /* Memory cell holding rowid of autoinc counter */
   225    225   #endif
   226    226   
   227         -  if( pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
          227  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto insert_cleanup;
   228    228     db = pParse->db;
   229    229   
   230    230     /* Locate the table into which we will be inserting new information.
   231    231     */
   232    232     assert( pTabList->nSrc==1 );
   233    233     zTab = pTabList->a[0].zName;
   234    234     if( zTab==0 ) goto insert_cleanup;
................................................................................
   334    334       int rc, iInitCode;
   335    335       iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   336    336       iSelectLoop = sqlite3VdbeCurrentAddr(v);
   337    337       iInsertBlock = sqlite3VdbeMakeLabel(v);
   338    338   
   339    339       /* Resolve the expressions in the SELECT statement and execute it. */
   340    340       rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
   341         -    if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
          341  +    if( rc || pParse->nErr || sqlite3Tsd()->mallocFailed ) goto insert_cleanup;
   342    342   
   343    343       iCleanup = sqlite3VdbeMakeLabel(v);
   344    344       sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
   345    345       assert( pSelect->pEList );
   346    346       nColumn = pSelect->pEList->nExpr;
   347    347   
   348    348       /* Set useTempTable to TRUE if the result of the SELECT statement

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.7 2004/09/06 17:34:13 drh Exp $
           17  +** $Id: legacy.c,v 1.8 2005/12/06 12:52:59 danielk1977 Exp $
    18     18   */
    19     19   
    20     20   #include "sqliteInt.h"
    21     21   #include "os.h"
    22     22   #include <ctype.h>
    23     23   
    24     24   /*
................................................................................
   118    118       azCols = 0;
   119    119     }
   120    120   
   121    121   exec_out:
   122    122     if( pStmt ) sqlite3_finalize(pStmt);
   123    123     if( azCols ) sqliteFree(azCols);
   124    124   
   125         -  if( sqlite3_malloc_failed ){
          125  +  if( sqlite3Tsd()->mallocFailed ){
   126    126       rc = SQLITE_NOMEM;
   127    127     }
   128    128     if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
   129    129       *pzErrMsg = malloc(1+strlen(sqlite3_errmsg(db)));
   130    130       if( *pzErrMsg ){
   131    131         strcpy(*pzErrMsg, sqlite3_errmsg(db));
   132    132       }
   133    133     }else if( pzErrMsg ){
   134    134       *pzErrMsg = 0;
   135    135     }
   136    136   
   137    137     return rc;
   138    138   }

Changes to src/main.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: main.c,v 1.304 2005/11/30 03:20:31 drh Exp $
           17  +** $Id: main.c,v 1.305 2005/12/06 12:52:59 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "os.h"
    21     21   #include <ctype.h>
    22     22   
    23     23   /*
    24     24   ** The following constant value is used by the SQLITE_BIGENDIAN and
................................................................................
   631    631   
   632    632   /*
   633    633   ** Return UTF-8 encoded English language explanation of the most recent
   634    634   ** error.
   635    635   */
   636    636   const char *sqlite3_errmsg(sqlite3 *db){
   637    637     const char *z;
   638         -  if( sqlite3_malloc_failed ){
          638  +  if( sqlite3Tsd()->mallocFailed ){
   639    639       return sqlite3ErrStr(SQLITE_NOMEM);
   640    640     }
   641    641     if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
   642    642       return sqlite3ErrStr(SQLITE_MISUSE);
   643    643     }
   644    644     z = sqlite3_value_text(db->pErr);
   645    645     if( z==0 ){
................................................................................
   670    670       0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
   671    671       0, 'o', 0, 'u', 0, 't', 0, ' ', 
   672    672       0, 'o', 0, 'f', 0, ' ', 
   673    673       0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
   674    674     };
   675    675   
   676    676     const void *z;
   677         -  if( sqlite3_malloc_failed ){
          677  +  if( sqlite3Tsd()->mallocFailed ){
   678    678       return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
   679    679     }
   680    680     if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
   681    681       return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
   682    682     }
   683    683     z = sqlite3_value_text16(db->pErr);
   684    684     if( z==0 ){
................................................................................
   690    690   }
   691    691   #endif /* SQLITE_OMIT_UTF16 */
   692    692   
   693    693   /*
   694    694   ** Return the most recent error code generated by an SQLite routine.
   695    695   */
   696    696   int sqlite3_errcode(sqlite3 *db){
   697         -  if( sqlite3_malloc_failed ){
          697  +  if( sqlite3Tsd()->mallocFailed ){
   698    698       return SQLITE_NOMEM;
   699    699     }
   700    700     if( sqlite3SafetyCheck(db) ){
   701    701       return SQLITE_MISUSE;
   702    702     }
   703    703     return db->errCode;
   704    704   }
................................................................................
   738    738     /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   739    739     ** and UTF-16, so add a version for each to avoid any unnecessary
   740    740     ** conversions. The only error that can occur here is a malloc() failure.
   741    741     */
   742    742     if( sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binCollFunc) ||
   743    743         sqlite3_create_collation(db, "BINARY", SQLITE_UTF16, 0,binCollFunc) ||
   744    744         (db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0))==0 ){
   745         -    rc = db->errCode;
   746         -    assert( rc!=SQLITE_OK );
          745  +    assert(rc!=SQLITE_OK || sqlite3Tsd()->mallocFailed);
   747    746       db->magic = SQLITE_MAGIC_CLOSED;
   748    747       goto opendb_out;
   749    748     }
   750    749   
   751    750     /* Also add a UTF-8 case-insensitive collation sequence. */
   752    751     sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);
   753    752   
................................................................................
   782    781     ** is accessed.
   783    782     */
   784    783     sqlite3RegisterBuiltinFunctions(db);
   785    784     sqlite3Error(db, SQLITE_OK, 0);
   786    785     db->magic = SQLITE_MAGIC_OPEN;
   787    786   
   788    787   opendb_out:
   789         -  if( sqlite3_errcode(db)==SQLITE_OK && sqlite3_malloc_failed ){
          788  +  if( sqlite3_errcode(db)==SQLITE_OK && sqlite3Tsd()->mallocFailed ){
   790    789       sqlite3Error(db, SQLITE_NOMEM, 0);
   791    790     }
   792    791     *ppDb = db;
   793    792   #ifndef SQLITE_OMIT_GLOBALRECOVER
   794    793     if( db ){
   795    794       sqlite3Os.xEnterMutex();
   796    795       db->pNext = pDbList;
................................................................................
  1006   1005   ** within SQLite. 
  1007   1006   **
  1008   1007   ** This function is *not* threadsafe. Calling this from within a threaded
  1009   1008   ** application when threads other than the caller have used SQLite is 
  1010   1009   ** dangerous and will almost certainly result in malfunctions.
  1011   1010   */
  1012   1011   int sqlite3_global_recover(){
         1012  +#if 0
  1013   1013     int rc = SQLITE_OK;
  1014   1014   
  1015         -  if( sqlite3_malloc_failed ){
         1015  +  if( sqlite3Tsd()->mallocFailed ){
  1016   1016       sqlite3 *db;
  1017   1017       int i;
  1018         -    sqlite3_malloc_failed = 0;
         1018  +    sqlite3Tsd()->mallocFailed = 0;
  1019   1019       for(db=pDbList; db; db=db->pNext ){
  1020   1020         sqlite3ExpirePreparedStatements(db);
  1021   1021         for(i=0; i<db->nDb; i++){
  1022   1022           Btree *pBt = db->aDb[i].pBt;
  1023   1023           if( pBt && (rc=sqlite3BtreeReset(pBt))!=0 ){
  1024   1024             goto recover_out;
  1025   1025           }
................................................................................
  1026   1026         } 
  1027   1027         db->autoCommit = 1;
  1028   1028       }
  1029   1029     }
  1030   1030   
  1031   1031   recover_out:
  1032   1032     if( rc!=SQLITE_OK ){
  1033         -    sqlite3_malloc_failed = 1;
         1033  +    sqlite3Tsd()->mallocFailed = 1;
  1034   1034     }
  1035   1035     return rc;
         1036  +#endif
         1037  +  return SQLITE_OK;
  1036   1038   }
  1037   1039   #endif
  1038   1040   
  1039   1041   /*
  1040   1042   ** Test to see whether or not the database connection is in autocommit
  1041   1043   ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
  1042   1044   ** by default.  Autocommit is disabled by a BEGIN statement and reenabled

Changes to src/os_unix.c.

   685    685     sqlite3Os.xLeaveMutex();
   686    686     if( rc ){
   687    687       close(f.h);
   688    688       return SQLITE_NOMEM;
   689    689     }
   690    690     f.locktype = 0;
   691    691     TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
          692  +
   692    693     return allocateUnixFile(&f, pId);
   693    694   }
   694    695   
   695    696   /*
   696    697   ** Attempt to open a file descriptor for the directory that contains a
   697    698   ** file.  This file descriptor can be used to fsync() the directory
   698    699   ** in order to make sure the creation of a new file is actually written

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.222 2005/11/30 03:20:31 drh Exp $
           21  +** @(#) $Id: pager.c,v 1.223 2005/12/06 12:52:59 danielk1977 Exp $
    22     22   */
    23     23   #ifndef SQLITE_OMIT_DISKIO
    24     24   #include "sqliteInt.h"
    25     25   #include "os.h"
    26     26   #include "pager.h"
    27     27   #include <assert.h>
    28     28   #include <string.h>
................................................................................
  1594   1594     int readOnly = 0;
  1595   1595     int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
  1596   1596     int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
  1597   1597     char zTemp[SQLITE_TEMPNAME_SIZE];
  1598   1598   
  1599   1599     *ppPager = 0;
  1600   1600     memset(&fd, 0, sizeof(fd));
  1601         -  if( sqlite3_malloc_failed ){
         1601  +  if( sqlite3Tsd()->mallocFailed ){
  1602   1602       return SQLITE_NOMEM;
  1603   1603     }
  1604   1604     if( zFilename && zFilename[0] ){
  1605   1605   #ifndef SQLITE_OMIT_MEMORYDB
  1606   1606       if( strcmp(zFilename,":memory:")==0 ){
  1607   1607         memDb = 1;
  1608   1608         zFullPathname = sqliteStrDup("");
................................................................................
  2409   2409       TEST_INCR(pPager->nMiss);
  2410   2410       if( pPager->nPage<pPager->mxPage || pPager->pFirst==0 || MEMDB ){
  2411   2411         /* Create a new page */
  2412   2412         pPg = sqliteMallocRaw( sizeof(*pPg) + pPager->pageSize
  2413   2413                                 + sizeof(u32) + pPager->nExtra
  2414   2414                                 + MEMDB*sizeof(PgHistory) );
  2415   2415         if( pPg==0 ){
  2416         -        pPager->errMask |= PAGER_ERR_MEM;
         2416  +        // pPager->errMask |= PAGER_ERR_MEM;
  2417   2417           return SQLITE_NOMEM;
  2418   2418         }
  2419   2419         memset(pPg, 0, sizeof(*pPg));
  2420   2420         if( MEMDB ){
  2421   2421           memset(PGHDR_TO_HIST(pPg, pPager), 0, sizeof(PgHistory));
  2422   2422         }
  2423   2423         pPg->pPager = pPager;
................................................................................
  2688   2688     pPager->origDbSize = pPager->dbSize;
  2689   2689   
  2690   2690     rc = writeJournalHdr(pPager);
  2691   2691   
  2692   2692     if( pPager->stmtAutoopen && rc==SQLITE_OK ){
  2693   2693       rc = sqlite3pager_stmt_begin(pPager);
  2694   2694     }
  2695         -  if( rc!=SQLITE_OK ){
         2695  +  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  2696   2696       rc = pager_unwritelock(pPager);
  2697   2697       if( rc==SQLITE_OK ){
  2698   2698         rc = SQLITE_FULL;
  2699   2699       }
  2700   2700     }
  2701   2701     return rc;
  2702   2702   
  2703   2703   failed_to_open_journal:
  2704   2704     sqliteFree(pPager->aInJournal);
  2705   2705     pPager->aInJournal = 0;
  2706         -  sqlite3OsUnlock(pPager->fd, NO_LOCK);
  2707         -  pPager->state = PAGER_UNLOCK;
         2706  +  if( rc==SQLITE_NOMEM ){
         2707  +    /* If this was a malloc() failure, then we will not be closing the pager
         2708  +    ** file. So delete any journal file we may have just created. Otherwise,
         2709  +    ** the system will get confused, we have a read-lock on the file and a
         2710  +    ** mysterious journal has appeared in the filesystem.
         2711  +    */
         2712  +    sqlite3Os.xDelete(pPager->zJournal);
         2713  +  }else{
         2714  +    sqlite3OsUnlock(pPager->fd, NO_LOCK);
         2715  +    pPager->state = PAGER_UNLOCK;
         2716  +  }
  2708   2717     return rc;
  2709   2718   }
  2710   2719   
  2711   2720   /*
  2712   2721   ** Acquire a write-lock on the database.  The lock is removed when
  2713   2722   ** the any of the following happen:
  2714   2723   **
................................................................................
  3266   3275     if( !pPager->journalOpen ){
  3267   3276       pPager->stmtAutoopen = 1;
  3268   3277       return SQLITE_OK;
  3269   3278     }
  3270   3279     assert( pPager->journalOpen );
  3271   3280     pPager->aInStmt = sqliteMalloc( pPager->dbSize/8 + 1 );
  3272   3281     if( pPager->aInStmt==0 ){
  3273         -    sqlite3OsLock(pPager->fd, SHARED_LOCK);
         3282  +    /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
  3274   3283       return SQLITE_NOMEM;
  3275   3284     }
  3276   3285   #ifndef NDEBUG
  3277   3286     rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
  3278   3287     if( rc ) goto stmt_begin_failed;
  3279   3288     assert( pPager->stmtJSize == pPager->journalOff );
  3280   3289   #endif

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.4 2005/09/10 16:46:13 drh Exp $
           16  +** $Id: prepare.c,v 1.5 2005/12/06 12:52:59 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "os.h"
    20     20   #include <ctype.h>
    21     21   
    22     22   /*
    23     23   ** Fill the InitData structure with an error message that indicates
    24     24   ** that the database is corrupt.
    25     25   */
    26     26   static void corruptSchema(InitData *pData, const char *zExtra){
    27         -  if( !sqlite3_malloc_failed ){
           27  +  if( !sqlite3Tsd()->mallocFailed ){
    28     28       sqlite3SetString(pData->pzErrMsg, "malformed database schema",
    29     29          zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
    30     30     }
    31     31   }
    32     32   
    33     33   /*
    34     34   ** This is the callback routine for the code that initializes the
................................................................................
    67     67       int rc;
    68     68       assert( db->init.busy );
    69     69       db->init.iDb = iDb;
    70     70       db->init.newTnum = atoi(argv[1]);
    71     71       rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
    72     72       db->init.iDb = 0;
    73     73       if( SQLITE_OK!=rc ){
    74         -      corruptSchema(pData, zErr);
           74  +      if( rc==SQLITE_NOMEM ){
           75  +          sqlite3Tsd()->mallocFailed = 1;
           76  +      }else{
           77  +          corruptSchema(pData, zErr);
           78  +      }
    75     79         sqlite3_free(zErr);
    76     80         return rc;
    77     81       }
    78     82     }else{
    79     83       /* If the SQL column is blank it means this is an index that
    80     84       ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
    81     85       ** constraint for a CREATE TABLE.  The index should have already
................................................................................
   297    301   #ifndef SQLITE_OMIT_ANALYZE
   298    302       if( rc==SQLITE_OK ){
   299    303         sqlite3AnalysisLoad(db, iDb);
   300    304       }
   301    305   #endif
   302    306       sqlite3BtreeCloseCursor(curMain);
   303    307     }
   304         -  if( sqlite3_malloc_failed ){
          308  +  if( sqlite3Tsd()->mallocFailed ){
   305    309       sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
   306    310       rc = SQLITE_NOMEM;
   307    311       sqlite3ResetInternalSchema(db, 0);
   308    312     }
   309    313     if( rc==SQLITE_OK ){
   310    314       DbSetProperty(db, iDb, DB_SchemaLoaded);
   311    315     }else{
................................................................................
   421    425     sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   422    426     const char** pzTail       /* OUT: End of parsed string */
   423    427   ){
   424    428     Parse sParse;
   425    429     char *zErrMsg = 0;
   426    430     int rc = SQLITE_OK;
   427    431   
   428         -  if( sqlite3_malloc_failed ){
   429         -    return SQLITE_NOMEM;
   430         -  }
          432  +  assert(!sqlite3Tsd()->mallocFailed);
   431    433   
   432    434     assert( ppStmt );
   433    435     *ppStmt = 0;
   434    436     if( sqlite3SafetyOn(db) ){
   435    437       return SQLITE_MISUSE;
   436    438     }
   437    439   
   438    440     memset(&sParse, 0, sizeof(sParse));
   439    441     sParse.db = db;
   440    442     sqlite3RunParser(&sParse, zSql, &zErrMsg);
   441    443   
   442         -  if( sqlite3_malloc_failed ){
   443         -    rc = SQLITE_NOMEM;
          444  +  if( sqlite3Tsd()->mallocFailed ){
          445  +    sParse.rc = SQLITE_NOMEM;
          446  +#if 0
          447  +    sqlite3RollbackInternalChanges(db);
   444    448       sqlite3RollbackAll(db);
   445         -    sqlite3ResetInternalSchema(db, 0);
   446    449       db->flags &= ~SQLITE_InTrans;
   447         -    goto prepare_out;
          450  +    db->autoCommit = 1;
          451  +#endif
   448    452     }
   449    453     if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
   450    454     if( sParse.rc!=SQLITE_OK && sParse.checkSchema && !schemaIsValid(db) ){
   451    455       sParse.rc = SQLITE_SCHEMA;
   452    456     }
   453    457     if( sParse.rc==SQLITE_SCHEMA ){
   454    458       sqlite3ResetInternalSchema(db, 0);
................................................................................
   486    490   
   487    491     if( zErrMsg ){
   488    492       sqlite3Error(db, rc, "%s", zErrMsg);
   489    493       sqliteFree(zErrMsg);
   490    494     }else{
   491    495       sqlite3Error(db, rc, 0);
   492    496     }
          497  +
          498  +  /* We must check for malloc failure last of all, in case malloc() failed
          499  +  ** inside of the sqlite3Error() call above or something.
          500  +  */
          501  +  if( sqlite3Tsd()->mallocFailed ){
          502  +    rc = SQLITE_NOMEM;
          503  +    sqlite3Error(db, rc, 0);
          504  +  }
          505  +
          506  +  sqlite3ClearMallocFailed();
   493    507     return rc;
   494    508   }
   495    509   
   496    510   #ifndef SQLITE_OMIT_UTF16
   497    511   /*
   498    512   ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   499    513   */

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.280 2005/11/16 13:47:51 drh Exp $
           15  +** $Id: select.c,v 1.281 2005/12/06 12:52:59 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   
    20     20   /*
    21     21   ** Allocate a new Select structure and return a pointer to that
    22     22   ** structure.
................................................................................
   151    151   }
   152    152   
   153    153   /*
   154    154   ** Set the value of a token to a '\000'-terminated string.
   155    155   */
   156    156   static void setToken(Token *p, const char *z){
   157    157     p->z = z;
   158         -  p->n = strlen(z);
          158  +  p->n = z ? strlen(z) : 0;
   159    159     p->dyn = 0;
   160    160   }
   161    161   
   162    162   /*
   163    163   ** Create an expression node for an identifier with the name of zName
   164    164   */
   165    165   static Expr *createIdExpr(const char *zName){
................................................................................
   852    852     /* If this is an EXPLAIN, skip this step */
   853    853     if( pParse->explain ){
   854    854       return;
   855    855     }
   856    856   #endif
   857    857   
   858    858     assert( v!=0 );
   859         -  if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
          859  +  if( pParse->colNamesSet || v==0 || sqlite3Tsd()->mallocFailed ) return;
   860    860     pParse->colNamesSet = 1;
   861    861     fullNames = (db->flags & SQLITE_FullColNames)!=0;
   862    862     shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   863    863     sqlite3VdbeSetNumCols(v, pEList->nExpr);
   864    864     for(i=0; i<pEList->nExpr; i++){
   865    865       Expr *p;
   866    866       p = pEList->a[i].pExpr;
................................................................................
   980    980         /* Use the original text of the column expression as its name */
   981    981         zName = sqlite3MPrintf("%T", &p->span);
   982    982       }else{
   983    983         /* If all else fails, make up a name */
   984    984         zName = sqlite3MPrintf("column%d", i+1);
   985    985       }
   986    986       sqlite3Dequote(zName);
   987         -    if( sqlite3_malloc_failed ){
          987  +    if( sqlite3Tsd()->mallocFailed ){
   988    988         sqliteFree(zName);
   989    989         sqlite3DeleteTable(0, pTab);
   990    990         return 0;
   991    991       }
   992    992   
   993    993       /* Make sure the column name is unique.  If the name is not unique,
   994    994       ** append a integer to the name so that it becomes unique.
................................................................................
  1052   1052   static int prepSelectStmt(Parse *pParse, Select *p){
  1053   1053     int i, j, k, rc;
  1054   1054     SrcList *pTabList;
  1055   1055     ExprList *pEList;
  1056   1056     Table *pTab;
  1057   1057     struct SrcList_item *pFrom;
  1058   1058   
  1059         -  if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
         1059  +  if( p==0 || p->pSrc==0 || sqlite3Tsd()->mallocFailed ) return 1;
  1060   1060     pTabList = p->pSrc;
  1061   1061     pEList = p->pEList;
  1062   1062   
  1063   1063     /* Make sure cursor numbers have been assigned to all entries in
  1064   1064     ** the FROM clause of the SELECT statement.
  1065   1065     */
  1066   1066     sqlite3SrcListAssignCursors(pParse, p->pSrc);
................................................................................
  1160   1160       for(k=0; k<pEList->nExpr; k++){
  1161   1161         Expr *pE = a[k].pExpr;
  1162   1162         if( pE->op!=TK_ALL &&
  1163   1163              (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  1164   1164           /* This particular expression does not need to be expanded.
  1165   1165           */
  1166   1166           pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
  1167         -        pNew->a[pNew->nExpr-1].zName = a[k].zName;
         1167  +        if( pNew ){
         1168  +          pNew->a[pNew->nExpr-1].zName = a[k].zName;
         1169  +        }else{
         1170  +          rc = 1;
         1171  +        }
  1168   1172           a[k].pExpr = 0;
  1169   1173           a[k].zName = 0;
  1170   1174         }else{
  1171   1175           /* This expression is a "*" or a "TABLE.*" and needs to be
  1172   1176           ** expanded. */
  1173   1177           int tableSeen = 0;      /* Set to 1 when TABLE matches */
  1174   1178           char *zTName;            /* text of name of TABLE */
................................................................................
  2635   2639     int isDistinct;        /* True if the DISTINCT keyword is present */
  2636   2640     int distinct;          /* Table to use for the distinct set */
  2637   2641     int rc = 1;            /* Value to return from this function */
  2638   2642     int addrSortIndex;     /* Address of an OP_OpenVirtual instruction */
  2639   2643     AggInfo sAggInfo;      /* Information used by aggregate queries */
  2640   2644     int iEnd;              /* Address of the end of the query */
  2641   2645   
  2642         -  if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
         2646  +  if( sqlite3Tsd()->mallocFailed || pParse->nErr || p==0 ) return 1;
  2643   2647     if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  2644   2648     memset(&sAggInfo, 0, sizeof(sAggInfo));
  2645   2649   
  2646   2650   #ifndef SQLITE_OMIT_COMPOUND_SELECT
  2647   2651     /* If there is are a sequence of queries, do the earlier ones first.
  2648   2652     */
  2649   2653     if( p->pPrior ){
................................................................................
  2889   2893       }
  2890   2894       sAggInfo.nAccumulator = sAggInfo.nColumn;
  2891   2895       for(i=0; i<sAggInfo.nFunc; i++){
  2892   2896         if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
  2893   2897           goto select_end;
  2894   2898         }
  2895   2899       }
  2896         -    if( sqlite3_malloc_failed ) goto select_end;
         2900  +    if( sqlite3Tsd()->mallocFailed ) goto select_end;
  2897   2901   
  2898   2902       /* Processing for aggregates with GROUP BY is very different and
  2899   2903       ** much more complex tha aggregates without a GROUP BY.
  2900   2904       */
  2901   2905       if( pGroupBy ){
  2902   2906         KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
  2903   2907   

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.428 2005/11/14 22:29:05 drh Exp $
           14  +** @(#) $Id: sqliteInt.h,v 1.429 2005/12/06 12:52:59 danielk1977 Exp $
    15     15   */
    16     16   #ifndef _SQLITEINT_H_
    17     17   #define _SQLITEINT_H_
    18     18   
    19     19   /*
    20     20   ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    21     21   ** Setting NDEBUG makes the code smaller and run faster.  So the following
................................................................................
   259    259   # define sqliteMalloc        sqlite3Malloc
   260    260   # define sqliteMallocRaw     sqlite3MallocRaw
   261    261   # define sqliteRealloc       sqlite3Realloc
   262    262   # define sqliteStrDup        sqlite3StrDup
   263    263   # define sqliteStrNDup       sqlite3StrNDup
   264    264   #endif
   265    265   
   266         -/*
   267         -** This variable gets set if malloc() ever fails.  After it gets set,
   268         -** the SQLite library shuts down permanently.
   269         -*/
   270         -extern int sqlite3_malloc_failed;
   271         -
   272    266   /*
   273    267   ** The following global variables are used for testing and debugging
   274    268   ** only.  They only work if SQLITE_DEBUG is defined.
   275    269   */
   276    270   #ifdef SQLITE_MEMDEBUG
   277    271   extern int sqlite3_nMalloc;      /* Number of sqliteMalloc() calls */
   278    272   extern int sqlite3_nFree;        /* Number of sqliteFree() calls */
................................................................................
  1381   1375   ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  1382   1376   */
  1383   1377   typedef struct {
  1384   1378     sqlite3 *db;        /* The database being initialized */
  1385   1379     char **pzErrMsg;    /* Error message stored here */
  1386   1380   } InitData;
  1387   1381   
         1382  +/*
         1383  +** An instance of this structure is allocated for each thread that uses SQLite.
         1384  +*/
         1385  +typedef struct SqliteTsd SqliteTsd;
         1386  +struct SqliteTsd {
         1387  +  int mallocFailed;               /* True after a malloc() has failed */
         1388  +};
         1389  +
  1388   1390   /*
  1389   1391    * This global flag is set for performance testing of triggers. When it is set
  1390   1392    * SQLite will perform the overhead of building new and old trigger references 
  1391   1393    * even when no triggers exist
  1392   1394    */
  1393   1395   extern int sqlite3_always_code_trigger_setup;
  1394   1396   
................................................................................
  1670   1672   void sqlite3Analyze(Parse*, Token*, Token*);
  1671   1673   int sqlite3InvokeBusyHandler(BusyHandler*);
  1672   1674   int sqlite3FindDb(sqlite3*, Token*);
  1673   1675   void sqlite3AnalysisLoad(sqlite3*,int iDB);
  1674   1676   void sqlite3DefaultRowEst(Index*);
  1675   1677   void sqlite3RegisterLikeFunctions(sqlite3*, int);
  1676   1678   int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
         1679  +SqliteTsd *sqlite3Tsd();
         1680  +void sqlite3ClearMallocFailed();
  1677   1681   
  1678   1682   #ifdef SQLITE_SSE
  1679   1683   #include "sseInt.h"
  1680   1684   #endif
  1681   1685   
  1682   1686   #endif

Changes to src/test1.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing the printf() interface to SQLite.  This code
    13     13   ** is not included in the SQLite library.  It is used for automated
    14     14   ** testing of the SQLite library.
    15     15   **
    16         -** $Id: test1.c,v 1.170 2005/12/05 13:20:02 drh Exp $
           16  +** $Id: test1.c,v 1.171 2005/12/06 12:53:00 danielk1977 Exp $
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "tcl.h"
    20     20   #include "os.h"
    21     21   #include <stdlib.h>
    22     22   #include <string.h>
    23     23   
................................................................................
   783    783   **
   784    784   ** Rig sqliteMalloc() to fail on the N-th call and every REPEAT-INTERVAL call
   785    785   ** after that.  If REPEAT-INTERVAL is 0 or is omitted, then only a single
   786    786   ** malloc will fail.  If REPEAT-INTERVAL is 1 then all mallocs after the
   787    787   ** first failure will continue to fail on every call.  If REPEAT-INTERVAL is
   788    788   ** 2 then every other malloc will fail.  And so forth.
   789    789   **
   790         -** Turn off this mechanism and reset the sqlite3_malloc_failed variable is N==0.
          790  +** Turn off this mechanism and reset the sqlite3Tsd()->mallocFailed variable is N==0.
   791    791   */
   792    792   #ifdef SQLITE_MEMDEBUG
   793    793   static int sqlite_malloc_fail(
   794    794     void *NotUsed,
   795    795     Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
   796    796     int argc,              /* Number of arguments */
   797    797     char **argv            /* Text of each argument */
................................................................................
   806    806     if( argc==3 ){
   807    807       if( Tcl_GetInt(interp, argv[2], &rep) ) return TCL_ERROR;
   808    808     }else{
   809    809       rep = 0;
   810    810     }
   811    811     sqlite3_iMallocFail = n;
   812    812     sqlite3_iMallocReset = rep;
   813         -  sqlite3_malloc_failed = 0;
          813  +  sqlite3Tsd()->mallocFailed = 0;
   814    814     return TCL_OK;
   815    815   }
   816    816   #endif
   817    817   
   818    818   /*
   819    819   ** Usage: sqlite_malloc_stat
   820    820   **
................................................................................
   948    948     if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
   949    949     return TCL_OK;
   950    950   }
   951    951   
   952    952   /*
   953    953   ** Usage:  sqlite3_reset  STMT 
   954    954   **
   955         -** Finalize a statement handle.
          955  +** Reset a statement handle.
   956    956   */
   957    957   static int test_reset(
   958    958     void * clientData,
   959    959     Tcl_Interp *interp,
   960    960     int objc,
   961    961     Tcl_Obj *CONST objv[]
   962    962   ){
................................................................................
   968    968           Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
   969    969       return TCL_ERROR;
   970    970     }
   971    971   
   972    972     if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
   973    973   
   974    974     rc = sqlite3_reset(pStmt);
   975         -  if( pStmt && 
   976         -      sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
          975  +  if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){
          976  +    return TCL_ERROR;
          977  +  }
   977    978     Tcl_SetResult(interp, (char *)errorName(rc), TCL_STATIC);
          979  +/*
   978    980     if( rc ){
   979    981       return TCL_ERROR;
   980    982     }
          983  +*/
   981    984     return TCL_OK;
   982    985   }
   983    986   
   984    987   /*
   985    988   ** Usage:  sqlite3_expired STMT 
   986    989   **
   987    990   ** Return TRUE if a recompilation of the statement is recommended.

Changes to src/tokenize.c.

    11     11   *************************************************************************
    12     12   ** An tokenizer for SQL
    13     13   **
    14     14   ** This file contains C code that splits an SQL input string up into
    15     15   ** individual tokens and sends those tokens one-by-one over to the
    16     16   ** parser for analysis.
    17     17   **
    18         -** $Id: tokenize.c,v 1.108 2005/10/23 11:29:40 drh Exp $
           18  +** $Id: tokenize.c,v 1.109 2005/12/06 12:53:00 danielk1977 Exp $
    19     19   */
    20     20   #include "sqliteInt.h"
    21     21   #include "os.h"
    22     22   #include <ctype.h>
    23     23   #include <stdlib.h>
    24     24   
    25     25   /*
................................................................................
   344    344     extern int sqlite3Parser(void*, int, Token, Parse*);
   345    345   
   346    346     db->flags &= ~SQLITE_Interrupt;
   347    347     pParse->rc = SQLITE_OK;
   348    348     i = 0;
   349    349     pEngine = sqlite3ParserAlloc((void*(*)(int))sqlite3MallocX);
   350    350     if( pEngine==0 ){
   351         -    sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
   352    351       return SQLITE_NOMEM;
   353    352     }
   354    353     assert( pParse->sLastToken.dyn==0 );
   355    354     assert( pParse->pNewTable==0 );
   356    355     assert( pParse->pNewTrigger==0 );
   357    356     assert( pParse->nVar==0 );
   358    357     assert( pParse->nVarExpr==0 );
   359    358     assert( pParse->nVarExprAlloc==0 );
   360    359     assert( pParse->apVarExpr==0 );
   361    360     pParse->zTail = pParse->zSql = zSql;
   362         -  while( sqlite3_malloc_failed==0 && zSql[i]!=0 ){
          361  +  while( sqlite3Tsd()->mallocFailed==0 && zSql[i]!=0 ){
   363    362       assert( i>=0 );
   364    363       pParse->sLastToken.z = &zSql[i];
   365    364       assert( pParse->sLastToken.dyn==0 );
   366    365       pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
   367    366       i += pParse->sLastToken.n;
   368    367       switch( tokenType ){
   369    368         case TK_SPACE:
................................................................................
   403    402       if( lastTokenParsed!=TK_SEMI ){
   404    403         sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   405    404         pParse->zTail = &zSql[i];
   406    405       }
   407    406       sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   408    407     }
   409    408     sqlite3ParserFree(pEngine, sqlite3FreeX);
   410         -  if( sqlite3_malloc_failed ){
          409  +  if( sqlite3Tsd()->mallocFailed ){
   411    410       pParse->rc = SQLITE_NOMEM;
   412    411     }
   413    412     if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   414         -    sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc),
   415         -                    (char*)0);
          413  +    sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
   416    414     }
   417    415     if( pParse->zErrMsg ){
   418    416       if( pzErrMsg && *pzErrMsg==0 ){
   419    417         *pzErrMsg = pParse->zErrMsg;
   420    418       }else{
   421    419         sqliteFree(pParse->zErrMsg);
   422    420       }

Changes to src/trigger.c.

    76     76     }
    77     77   
    78     78     /* If the trigger name was unqualified, and the table is a temp table,
    79     79     ** then set iDb to 1 to create the trigger in the temporary database.
    80     80     ** If sqlite3SrcListLookup() returns 0, indicating the table does not
    81     81     ** exist, the error is caught by the block below.
    82     82     */
    83         -  if( !pTableName || sqlite3_malloc_failed ) goto trigger_cleanup;
           83  +  if( !pTableName || sqlite3Tsd()->mallocFailed ) goto trigger_cleanup;
    84     84     pTab = sqlite3SrcListLookup(pParse, pTableName);
    85     85     if( pName2->n==0 && pTab && pTab->iDb==1 ){
    86     86       iDb = 1;
    87     87     }
    88     88   
    89     89     /* Ensure the table name matches database name and that the table exists */
    90         -  if( sqlite3_malloc_failed ) goto trigger_cleanup;
           90  +  if( sqlite3Tsd()->mallocFailed ) goto trigger_cleanup;
    91     91     assert( pTableName->nSrc==1 );
    92     92     if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
    93     93         sqlite3FixSrcList(&sFix, pTableName) ){
    94     94       goto trigger_cleanup;
    95     95     }
    96     96     pTab = sqlite3SrcListLookup(pParse, pTableName);
    97     97     if( !pTab ){
................................................................................
   246    246   
   247    247     if( db->init.busy ){
   248    248       Table *pTab;
   249    249       Trigger *pDel;
   250    250       pDel = sqlite3HashInsert(&db->aDb[pTrig->iDb].trigHash, 
   251    251                        pTrig->name, strlen(pTrig->name)+1, pTrig);
   252    252       if( pDel ){
   253         -      assert( sqlite3_malloc_failed && pDel==pTrig );
          253  +      assert( sqlite3Tsd()->mallocFailed && pDel==pTrig );
   254    254         goto triggerfinish_cleanup;
   255    255       }
   256    256       pTab = sqlite3LocateTable(pParse,pTrig->table,db->aDb[pTrig->iTabDb].zName);
   257    257       assert( pTab!=0 );
   258    258       pTrig->pNext = pTab->pTrigger;
   259    259       pTab->pTrigger = pTrig;
   260    260       pTrig = 0;
................................................................................
   426    426     Trigger *pTrigger = 0;
   427    427     int i;
   428    428     const char *zDb;
   429    429     const char *zName;
   430    430     int nName;
   431    431     sqlite3 *db = pParse->db;
   432    432   
   433         -  if( sqlite3_malloc_failed ) goto drop_trigger_cleanup;
          433  +  if( sqlite3Tsd()->mallocFailed ) goto drop_trigger_cleanup;
   434    434     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   435    435       goto drop_trigger_cleanup;
   436    436     }
   437    437   
   438    438     assert( pName->nSrc==1 );
   439    439     zDb = pName->a[0].zDatabase;
   440    440     zName = pName->a[0].zName;

Changes to src/update.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 UPDATE statements.
    14     14   **
    15         -** $Id: update.c,v 1.113 2005/11/14 22:29:05 drh Exp $
           15  +** $Id: update.c,v 1.114 2005/12/06 12:53:01 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** The most recently coded instruction was an OP_Column to retrieve the
    21     21   ** i-th column of table pTab. This routine sets the P3 parameter of the 
    22     22   ** OP_Column to the default value, if any.
................................................................................
    95     95     int triggers_exist = 0;      /* True if any row triggers exist */
    96     96   #endif
    97     97   
    98     98     int newIdx      = -1;  /* index of trigger "new" temp table       */
    99     99     int oldIdx      = -1;  /* index of trigger "old" temp table       */
   100    100   
   101    101     sContext.pParse = 0;
   102         -  if( pParse->nErr || sqlite3_malloc_failed ) goto update_cleanup;
          102  +  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto update_cleanup;
   103    103     db = pParse->db;
   104    104     assert( pTabList->nSrc==1 );
   105    105   
   106    106     /* Locate the table which we want to update. 
   107    107     */
   108    108     pTab = sqlite3SrcListLookup(pParse, pTabList);
   109    109     if( pTab==0 ) goto update_cleanup;

Changes to src/util.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Utility functions used throughout sqlite.
    13     13   **
    14     14   ** This file contains functions for allocating memory, comparing
    15     15   ** strings, and stuff like that.
    16     16   **
    17         -** $Id: util.c,v 1.148 2005/10/20 07:28:19 drh Exp $
           17  +** $Id: util.c,v 1.149 2005/12/06 12:53:01 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include <stdarg.h>
    21     21   #include <ctype.h>
    22     22   
    23     23   #if SQLITE_MEMDEBUG>2 && defined(__GLIBC__)
    24     24   #include <execinfo.h>
................................................................................
    33     33     }
    34     34     fprintf(stderr, "\n");
    35     35   }
    36     36   #else
    37     37   #define print_stack_trace()
    38     38   #endif
    39     39   
           40  +#if 0
    40     41   /*
    41     42   ** If malloc() ever fails, this global variable gets set to 1.
    42     43   ** This causes the library to abort and never again function.
    43     44   */
    44         -int sqlite3_malloc_failed = 0;
           45  +int sqlite3Tsd()->mallocFailed = 0;
           46  +#endif
    45     47   
    46     48   /*
    47     49   ** If SQLITE_MEMDEBUG is defined, then use versions of malloc() and
    48     50   ** free() that track memory usage and check for buffer overruns.
    49     51   */
    50     52   #ifdef SQLITE_MEMDEBUG
    51     53   
................................................................................
    77     79   ** Check for a simulated memory allocation failure.  Return true if
    78     80   ** the failure should be simulated.  Return false to proceed as normal.
    79     81   */
    80     82   static int simulatedMallocFailure(int n, char *zFile, int line){
    81     83     if( sqlite3_iMallocFail>=0 ){
    82     84       sqlite3_iMallocFail--;
    83     85       if( sqlite3_iMallocFail==0 ){
    84         -      sqlite3_malloc_failed++;
           86  +      sqlite3Tsd()->mallocFailed++;
    85     87   #if SQLITE_MEMDEBUG>1
    86     88         fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
    87     89                 n, zFile,line);
    88     90   #endif
    89     91         sqlite3_iMallocFail = sqlite3_iMallocReset;
    90     92         return 1;
    91     93       }
................................................................................
    97     99   ** Allocate new memory and set it to zero.  Return NULL if
    98    100   ** no memory is available.
    99    101   */
   100    102   void *sqlite3Malloc_(int n, int bZero, char *zFile, int line){
   101    103     void *p;
   102    104     int *pi;
   103    105     int i, k;
          106  +
          107  +  /* Any malloc() calls between a malloc() failure and clearing the
          108  +  ** mallocFailed flag (done before returning control to the user)
          109  +  ** automatically fail. Although this restriction may have to be relaxed in
          110  +  ** the future, for now it makes the system easier to test.
          111  +  **
          112  +  ** TODO: This will eventually be done as part of the same wrapper that may
          113  +  ** call sqlite3_release_memory(). Above the sqlite3OsMalloc() level.
          114  +  */
          115  +  if( sqlite3Tsd()->mallocFailed ){
          116  +    return 0;
          117  +  }
          118  +
   104    119     if( n==0 ){
   105    120       return 0;
   106    121     }
   107    122     if( simulatedMallocFailure(n, zFile, line) ){
   108    123       return 0;
   109    124     }
   110    125     sqlite3_memUsed += n;
   111    126     if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
   112    127     k = (n+sizeof(int)-1)/sizeof(int);
   113    128     pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
   114    129     if( pi==0 ){
   115         -    if( n>0 ) sqlite3_malloc_failed++;
          130  +    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   116    131       return 0;
   117    132     }
   118    133     sqlite3_nMalloc++;
   119    134     for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
   120    135     pi[N_GUARD] = n;
   121    136     for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
   122    137     p = &pi[N_GUARD+1];
................................................................................
   224    239                 (int)oldP);
   225    240         return 0;
   226    241       }
   227    242     }
   228    243     k = (n + sizeof(int) - 1)/sizeof(int);
   229    244     pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
   230    245     if( pi==0 ){
   231         -    if( n>0 ) sqlite3_malloc_failed++;
          246  +    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   232    247       return 0;
   233    248     }
   234    249     for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
   235    250     pi[N_GUARD] = n;
   236    251     sqlite3_memUsed += n;
   237    252     if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
   238    253     for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
................................................................................
   290    305   ** Allocate new memory and set it to zero.  Return NULL if
   291    306   ** no memory is available.  See also sqliteMallocRaw().
   292    307   */
   293    308   void *sqlite3Malloc(int n){
   294    309     void *p;
   295    310     if( n==0 ) return 0;
   296    311     if( (p = malloc(n))==0 ){
   297         -    if( n>0 ) sqlite3_malloc_failed++;
          312  +    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   298    313     }else{
   299    314       memset(p, 0, n);
   300    315     }
   301    316     return p;
   302    317   }
   303    318   
   304    319   /*
................................................................................
   305    320   ** Allocate new memory but do not set it to zero.  Return NULL if
   306    321   ** no memory is available.  See also sqliteMalloc().
   307    322   */
   308    323   void *sqlite3MallocRaw(int n){
   309    324     void *p;
   310    325     if( n==0 ) return 0;
   311    326     if( (p = malloc(n))==0 ){
   312         -    if( n>0 ) sqlite3_malloc_failed++;
          327  +    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   313    328     }
   314    329     return p;
   315    330   }
   316    331   
   317    332   /*
   318    333   ** Free memory previously obtained from sqliteMalloc()
   319    334   */
................................................................................
   335    350     }
   336    351     if( n==0 ){
   337    352       sqliteFree(p);
   338    353       return 0;
   339    354     }
   340    355     p2 = realloc(p, n);
   341    356     if( p2==0 ){
   342         -    if( n>0 ) sqlite3_malloc_failed++;
          357  +    if( n>0 ) sqlite3Tsd()->mallocFailed++;
   343    358     }
   344    359     return p2;
   345    360   }
   346    361   
   347    362   /*
   348    363   ** Make a copy of a string in memory obtained from sqliteMalloc()
   349    364   */
................................................................................
  1003   1018       assert( sizeof(p)==sizeof(v2) );
  1004   1019       v2 = (u32)v;
  1005   1020       p = *(void**)&v2;
  1006   1021     }
  1007   1022     return p;
  1008   1023   }
  1009   1024   #endif
         1025  +
         1026  +/*
         1027  +** Return a pointer to the SqliteTsd associated with the calling thread.
         1028  +*/
         1029  +static SqliteTsd tsd = { 0 };
         1030  +SqliteTsd *sqlite3Tsd(){
         1031  +  return &tsd;
         1032  +}
         1033  +
         1034  +void sqlite3ClearMallocFailed(){
         1035  +  sqlite3Tsd()->mallocFailed = 0;
         1036  +}
         1037  +
         1038  +
         1039  +

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.49 2005/11/30 03:20:32 drh Exp $
           17  +** $Id: vacuum.c,v 1.50 2005/12/06 12:53:01 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "os.h"
    21     21   
    22     22   #ifndef SQLITE_OMIT_VACUUM
    23     23   /*
    24     24   ** Generate a random name of 20 character in length.
................................................................................
   166    166     zSql = 0;
   167    167     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   168    168     assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
   169    169     pTemp = db->aDb[db->nDb-1].pBt;
   170    170     sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
   171    171        sqlite3BtreeGetReserve(pMain));
   172    172     assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
   173         -  execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
          173  +  rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
          174  +  if( rc!=SQLITE_OK ){
          175  +    goto end_of_vacuum;
          176  +  }
   174    177   
   175    178   #ifndef SQLITE_OMIT_AUTOVACUUM
   176    179     sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain));
   177    180   #endif
   178    181   
   179    182     /* Begin a transaction */
   180    183     rc = execSql(db, "BEGIN EXCLUSIVE;");
................................................................................
   280    283       if( rc!=SQLITE_OK ) goto end_of_vacuum;
   281    284       rc = sqlite3BtreeCommit(pTemp);
   282    285       if( rc!=SQLITE_OK ) goto end_of_vacuum;
   283    286       rc = sqlite3BtreeCommit(pMain);
   284    287     }
   285    288   
   286    289   end_of_vacuum:
          290  +  /* If one of the execSql() calls above returned SQLITE_NOMEM, then the
          291  +  ** mallocFailed flag will be clear (because execSql() calls sqlite3_exec()).
          292  +  ** Fix this so the flag and return code match.
          293  +  */
          294  +  if( rc==SQLITE_NOMEM ){
          295  +    sqlite3Tsd()->mallocFailed = 1;
          296  +  }
          297  +
   287    298     /* Restore the original value of db->flags */
   288    299     db->flags = saved_flags;
   289    300   
   290    301     /* Currently there is an SQL level transaction open on the vacuum
   291    302     ** database. No locks are held on any other files (since the main file
   292    303     ** was committed at the btree level). So it safe to end the transaction
   293    304     ** by manually setting the autoCommit flag to true and detaching the
   294    305     ** vacuum database. The vacuum_db journal file is deleted when the pager
   295    306     ** is closed by the DETACH.
   296    307     */
   297    308     db->autoCommit = 1;
   298         -  rc2 = execSql(db, "DETACH vacuum_db;");
   299         -  if( rc==SQLITE_OK ){
   300         -    rc = rc2;
          309  +
          310  +  /* TODO: We need to detach vacuum_db (if it is attached) even if malloc()
          311  +  ** failed. Right now trying to do so will cause an assert() to fail in **
          312  +  **_prepare() (because it should be impossible to call _prepare() with the **
          313  +  ** mallocFailed flag set). So really, we need to be able to detach a database
          314  +  ** without calling malloc(). Which seems plausible.
          315  +  */
          316  +  if( !sqlite3Tsd()->mallocFailed ){
          317  +    rc2 = execSql(db, "DETACH vacuum_db;");
          318  +    if( rc==SQLITE_OK ){
          319  +      rc = rc2;
          320  +    }
   301    321     }
   302    322     if( zTemp ){
   303    323       sqlite3Os.xDelete(zTemp);
   304    324       sqliteFree(zTemp);
   305    325     }
   306    326     sqliteFree( zSql );
   307    327     sqlite3ResetInternalSchema(db, 0);
   308    328   #endif
   309    329   
   310    330     return rc;
   311    331   }

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.501 2005/11/30 03:20:32 drh Exp $
           46  +** $Id: vdbe.c,v 1.502 2005/12/06 12:53:01 danielk1977 Exp $
    47     47   */
    48     48   #include "sqliteInt.h"
    49     49   #include "os.h"
    50     50   #include <ctype.h>
    51     51   #include "vdbeInt.h"
    52     52   
    53     53   /*
................................................................................
   390    390   
   391    391     if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
   392    392     assert( db->magic==SQLITE_MAGIC_BUSY );
   393    393     assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   394    394     p->rc = SQLITE_OK;
   395    395     assert( p->explain==0 );
   396    396     pTos = p->pTos;
   397         -  if( sqlite3_malloc_failed ) goto no_mem;
          397  +  if( sqlite3Tsd()->mallocFailed ) goto no_mem;
   398    398     if( p->popStack ){
   399    399       popStack(&pTos, p->popStack);
   400    400       p->popStack = 0;
   401    401     }
   402    402     p->resOnStack = 0;
   403    403     db->busyHandler.nBusy = 0;
   404    404     CHECK_FOR_INTERRUPT;
   405    405     for(pc=p->pc; rc==SQLITE_OK; pc++){
   406    406       assert( pc>=0 && pc<p->nOp );
   407    407       assert( pTos<=&p->aStack[pc] );
   408         -    if( sqlite3_malloc_failed ) goto no_mem;
          408  +    if( sqlite3Tsd()->mallocFailed ) goto no_mem;
   409    409   #ifdef VDBE_PROFILE
   410    410       origPc = pc;
   411    411       start = hwtime();
   412    412   #endif
   413    413       pOp = &p->aOp[pc];
   414    414   
   415    415       /* Only allow tracing if SQLITE_DEBUG is defined.
................................................................................
  1131   1131       assert( pOp[-1].p3type==P3_COLLSEQ );
  1132   1132       assert( pOp[-1].opcode==OP_CollSeq );
  1133   1133       ctx.pColl = (CollSeq *)pOp[-1].p3;
  1134   1134     }
  1135   1135     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  1136   1136     (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  1137   1137     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  1138         -  if( sqlite3_malloc_failed ) goto no_mem;
         1138  +  if( sqlite3Tsd()->mallocFailed ) goto no_mem;
  1139   1139     popStack(&pTos, n);
  1140   1140   
  1141   1141     /* If any auxilary data functions have been called by this user function,
  1142   1142     ** immediately call the destructor for any non-static values.
  1143   1143     */
  1144   1144     if( ctx.pVdbeFunc ){
  1145   1145       sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
................................................................................
  3109   3109   #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  3110   3110   #endif
  3111   3111   
  3112   3112       if( !pC->useRandomRowid ){
  3113   3113         if( pC->nextRowidValid ){
  3114   3114           v = pC->nextRowid;
  3115   3115         }else{
  3116         -        rx = sqlite3BtreeLast(pC->pCursor, &res);
         3116  +        rc = sqlite3BtreeLast(pC->pCursor, &res);
         3117  +        if( rc!=SQLITE_OK ){
         3118  +          goto abort_due_to_error;
         3119  +        }
  3117   3120           if( res ){
  3118   3121             v = 1;
  3119   3122           }else{
  3120   3123             sqlite3BtreeKeySize(pC->pCursor, &v);
  3121   3124             v = keyToInt(v);
  3122   3125             if( v==MAX_ROWID ){
  3123   3126               pC->useRandomRowid = 1;
................................................................................
  3889   3892     zSql = sqlite3MPrintf(
  3890   3893        "SELECT name, rootpage, sql, %d FROM '%q'.%s WHERE %s",
  3891   3894        pOp->p1, db->aDb[iDb].zName, zMaster, pOp->p3);
  3892   3895     if( zSql==0 ) goto no_mem;
  3893   3896     sqlite3SafetyOff(db);
  3894   3897     assert( db->init.busy==0 );
  3895   3898     db->init.busy = 1;
         3899  +  assert(0==sqlite3Tsd()->mallocFailed);
  3896   3900     rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  3897   3901     db->init.busy = 0;
  3898   3902     sqlite3SafetyOn(db);
         3903  +  if( rc==SQLITE_NOMEM ){
         3904  +    sqlite3Tsd()->mallocFailed = 1;
         3905  +    goto no_mem;
         3906  +  }
  3899   3907     sqliteFree(zSql);
  3900   3908     break;  
  3901   3909   }
  3902   3910   
  3903   3911   #ifndef SQLITE_OMIT_ANALYZE
  3904   3912   /* Opcode: LoadAnalysis P1 * *
  3905   3913   **
................................................................................
  4429   4437     /* Fall thru into abort_due_to_error */
  4430   4438   
  4431   4439     /* Jump to here for any other kind of fatal error.  The "rc" variable
  4432   4440     ** should hold the error number.
  4433   4441     */
  4434   4442   abort_due_to_error:
  4435   4443     if( p->zErrMsg==0 ){
  4436         -    if( sqlite3_malloc_failed ) rc = SQLITE_NOMEM;
         4444  +    if( sqlite3Tsd()->mallocFailed ) rc = SQLITE_NOMEM;
  4437   4445       sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
  4438   4446     }
  4439   4447     goto vdbe_halt;
  4440   4448   
  4441   4449     /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  4442   4450     ** flag.
  4443   4451     */

Changes to src/vdbeapi.c.

   151    151   ** Execute the statement pStmt, either until a row of data is ready, the
   152    152   ** statement is completely executed or an error occurs.
   153    153   */
   154    154   int sqlite3_step(sqlite3_stmt *pStmt){
   155    155     Vdbe *p = (Vdbe*)pStmt;
   156    156     sqlite3 *db;
   157    157     int rc;
          158  +
          159  +  assert(!sqlite3Tsd()->mallocFailed);
   158    160   
   159    161     if( p==0 || p->magic!=VDBE_MAGIC_RUN ){
   160    162       return SQLITE_MISUSE;
   161    163     }
   162    164     if( p->aborted ){
   163    165       return SQLITE_ABORT;
   164    166     }
................................................................................
   235    237       assert( p->aOp[p->nOp-1].p3!=0 );
   236    238       assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
   237    239       db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
   238    240     }
   239    241   #endif
   240    242   
   241    243     sqlite3Error(p->db, rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
          244  +  sqlite3ClearMallocFailed();
   242    245     return rc;
   243    246   }
   244    247   
   245    248   /*
   246    249   ** Extract the user data from a sqlite3_context structure and return a
   247    250   ** pointer to it.
   248    251   */

Changes to src/vdbeaux.c.

    98     98     int i;
    99     99     VdbeOp *pOp;
   100    100   
   101    101     i = p->nOp;
   102    102     p->nOp++;
   103    103     assert( p->magic==VDBE_MAGIC_INIT );
   104    104     resizeOpArray(p, i+1);
   105         -  if( sqlite3_malloc_failed ){
          105  +  if( sqlite3Tsd()->mallocFailed ){
   106    106       return 0;
   107    107     }
   108    108     pOp = &p->aOp[i];
   109    109     pOp->opcode = op;
   110    110     pOp->p1 = p1;
   111    111     pOp->p2 = p2;
   112    112     pOp->p3 = 0;
................................................................................
   297    297   ** Add a whole list of operations to the operation stack.  Return the
   298    298   ** address of the first operation added.
   299    299   */
   300    300   int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   301    301     int addr;
   302    302     assert( p->magic==VDBE_MAGIC_INIT );
   303    303     resizeOpArray(p, p->nOp + nOp);
   304         -  if( sqlite3_malloc_failed ){
          304  +  if( sqlite3Tsd()->mallocFailed ){
   305    305       return 0;
   306    306     }
   307    307     addr = p->nOp;
   308    308     if( nOp>0 ){
   309    309       int i;
   310    310       VdbeOpList const *pIn = aOp;
   311    311       for(i=0; i<nOp; i++, pIn++){
................................................................................
   412    412   **
   413    413   ** If addr<0 then change P3 on the most recently inserted instruction.
   414    414   */
   415    415   void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
   416    416     Op *pOp;
   417    417     assert( p->magic==VDBE_MAGIC_INIT );
   418    418     if( p==0 || p->aOp==0 ){
   419         -    freeP3(n, (void*)*(char**)&zP3);
          419  +    if (n != P3_KEYINFO) {
          420  +      freeP3(n, (void*)*(char**)&zP3);
          421  +    }
   420    422       return;
   421    423     }
   422    424     if( addr<0 || addr>=p->nOp ){
   423    425       addr = p->nOp - 1;
   424    426       if( addr<0 ) return;
   425    427     }
   426    428     pOp = &p->aOp[addr];
................................................................................
   730    732           nStack*sizeof(p->aStack[0])    /* aStack */
   731    733         + nArg*sizeof(Mem*)              /* apArg */
   732    734         + nVar*sizeof(Mem)               /* aVar */
   733    735         + nVar*sizeof(char*)             /* azVar */
   734    736         + nMem*sizeof(Mem)               /* aMem */
   735    737         + nCursor*sizeof(Cursor*)        /* apCsr */
   736    738       );
   737         -    if( !sqlite3_malloc_failed ){
          739  +    if( !sqlite3Tsd()->mallocFailed ){
   738    740         p->aMem = &p->aStack[nStack];
   739    741         p->nMem = nMem;
   740    742         p->aVar = &p->aMem[nMem];
   741    743         p->nVar = nVar;
   742    744         p->okVar = 0;
   743    745         p->apArg = (Mem**)&p->aVar[nVar];
   744    746         p->azVar = (char**)&p->apArg[nArg];
................................................................................
   880    882   ** the string is freed using sqliteFree() when the vdbe is finished with
   881    883   ** it. Otherwise, N bytes of zName are copied.
   882    884   */
   883    885   int sqlite3VdbeSetColName(Vdbe *p, int idx, const char *zName, int N){
   884    886     int rc;
   885    887     Mem *pColName;
   886    888     assert( idx<(2*p->nResColumn) );
   887         -  if( sqlite3_malloc_failed ) return SQLITE_NOMEM;
          889  +  if( sqlite3Tsd()->mallocFailed ) return SQLITE_NOMEM;
   888    890     assert( p->aColName!=0 );
   889    891     pColName = &(p->aColName[idx]);
   890    892     if( N==P3_DYNAMIC || N==P3_STATIC ){
   891    893       rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
   892    894     }else{
   893    895       rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
   894    896     }
................................................................................
  1143   1145   ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
  1144   1146   ** means the close did not happen and needs to be repeated.
  1145   1147   */
  1146   1148   int sqlite3VdbeHalt(Vdbe *p){
  1147   1149     sqlite3 *db = p->db;
  1148   1150     int i;
  1149   1151     int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
         1152  +
         1153  +  if( sqlite3Tsd()->mallocFailed ){
         1154  +    p->rc = SQLITE_NOMEM;
         1155  +  }
  1150   1156   
  1151   1157     if( p->magic!=VDBE_MAGIC_RUN ){
  1152   1158       /* Already halted.  Nothing to do. */
  1153   1159       assert( p->magic==VDBE_MAGIC_HALT );
  1154   1160       return SQLITE_OK;
  1155   1161     }
  1156   1162     closeAllCursors(p);
  1157   1163     checkActiveVdbeCnt(db);
  1158   1164     if( p->pc<0 ){
  1159   1165       /* No commit or rollback needed if the program never started */
  1160   1166     }else if( db->autoCommit && db->activeVdbeCnt==1 ){
  1161         -    if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
         1167  +
         1168  +    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && p->rc!=SQLITE_NOMEM)){
  1162   1169         /* The auto-commit flag is true, there are no other active queries
  1163   1170         ** using this handle and the vdbe program was successful or hit an
  1164   1171         ** 'OR FAIL' constraint. This means a commit is required.
  1165   1172         */
  1166   1173         int rc = vdbeCommit(db);
  1167   1174         if( rc==SQLITE_BUSY ){
  1168   1175           return SQLITE_BUSY;
  1169   1176         }else if( rc!=SQLITE_OK ){
  1170   1177           p->rc = rc;
  1171   1178           xFunc = sqlite3BtreeRollback;
         1179  +      }else{
         1180  +        sqlite3CommitInternalChanges(db);
  1172   1181         }
  1173   1182       }else{
  1174   1183         xFunc = sqlite3BtreeRollback;
  1175   1184       }
  1176   1185     }else{
         1186  +
         1187  +    if( p->rc==SQLITE_NOMEM ){
         1188  +      /* This loop does static analysis of the query to see which of the
         1189  +      ** following three categories it falls into:
         1190  +      **
         1191  +      **     Read-only
         1192  +      **     Query with statement journal          -> rollback statement
         1193  +      **     Query without statement journal       -> rollback transaction
         1194  +      **
         1195  +      ** We could do something more elegant than this static analysis (i.e.
         1196  +      ** store the type of query as part of the compliation phase), but 
         1197  +      ** handling malloc() failure is a fairly obscure edge case so this is
         1198  +      ** probably easier.
         1199  +      **
         1200  +      ** Todo: This means we always override the p->errorAction value for a
         1201  +      ** malloc() failure. Is there any other choice here though?
         1202  +      */
         1203  +      int isReadOnly = 1;
         1204  +      int isStatement = 0;
         1205  +      assert(p->aOp || p->nOp==0);
         1206  +      for(i=0; i<p->nOp; i++){ 
         1207  +        switch( p->aOp[i].opcode ){
         1208  +          case OP_Transaction:
         1209  +            isReadOnly = 0;
         1210  +            break;
         1211  +          case OP_Statement:
         1212  +            isStatement = 1;
         1213  +            break;
         1214  +        }
         1215  +      }
         1216  +      if( (isReadOnly||isStatement) && p->errorAction!=OE_Rollback ){
         1217  +        p->errorAction = OE_Abort;
         1218  +      }else{ 
         1219  +        p->errorAction = OE_Rollback;
         1220  +      }
         1221  +    }
         1222  +
  1177   1223       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  1178   1224         xFunc = sqlite3BtreeCommitStmt;
  1179   1225       }else if( p->errorAction==OE_Abort ){
  1180   1226         xFunc = sqlite3BtreeRollbackStmt;
  1181   1227       }else{
  1182   1228         xFunc = sqlite3BtreeRollback;
  1183   1229         db->autoCommit = 1;
................................................................................
  1206   1252       }else{
  1207   1253         sqlite3VdbeSetChanges(db, 0);
  1208   1254       }
  1209   1255       p->nChange = 0;
  1210   1256     }
  1211   1257   
  1212   1258     /* Rollback or commit any schema changes that occurred. */
  1213         -  if( p->rc!=SQLITE_OK ){
  1214         -    sqlite3RollbackInternalChanges(db);
  1215         -  }else if( db->flags & SQLITE_InternChanges ){
  1216         -    sqlite3CommitInternalChanges(db);
         1259  +  if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
         1260  +    sqlite3ResetInternalSchema(db, 0);
         1261  +    if( xFunc!=sqlite3BtreeRollback ){
         1262  +      db->flags = (db->flags | SQLITE_InternChanges);
         1263  +    }
  1217   1264     }
  1218   1265   
  1219   1266     /* We have successfully halted and closed the VM.  Record this fact. */
  1220   1267     if( p->pc>=0 ){
  1221   1268       db->activeVdbeCnt--;
  1222   1269     }
  1223   1270     p->magic = VDBE_MAGIC_HALT;
................................................................................
  1274   1321   
  1275   1322     /* Reclaim all memory used by the VDBE
  1276   1323     */
  1277   1324     Cleanup(p);
  1278   1325   
  1279   1326     /* Save profiling information from this VDBE run.
  1280   1327     */
  1281         -  assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || sqlite3_malloc_failed==1 );
         1328  +  assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
  1282   1329   #ifdef VDBE_PROFILE
  1283   1330     {
  1284   1331       FILE *out = fopen("vdbe_profile.out", "a");
  1285   1332       if( out ){
  1286   1333         int i;
  1287   1334         fprintf(out, "---- ");
  1288   1335         for(i=0; i<p->nOp; i++){

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.185 2005/11/26 14:24:41 drh Exp $
           19  +** $Id: where.c,v 1.186 2005/12/06 12:53:01 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)
................................................................................
   563    563     WhereTerm *pTerm = &pWC->a[idxTerm];
   564    564     Expr *pExpr = pTerm->pExpr;
   565    565     Bitmask prereqLeft;
   566    566     Bitmask prereqAll;
   567    567     int nPattern;
   568    568     int isComplete;
   569    569   
   570         -  if( sqlite3_malloc_failed ) return;
          570  +  if( sqlite3Tsd()->mallocFailed ) return;
   571    571     prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   572    572     if( pExpr->op==TK_IN ){
   573    573       assert( pExpr->pRight==0 );
   574    574       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
   575    575                             | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
   576    576     }else{
   577    577       pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
................................................................................
  1428   1428     whereClauseInit(&wc, pParse);
  1429   1429     whereSplit(&wc, pWhere, TK_AND);
  1430   1430       
  1431   1431     /* Allocate and initialize the WhereInfo structure that will become the
  1432   1432     ** return value.
  1433   1433     */
  1434   1434     pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
  1435         -  if( sqlite3_malloc_failed ){
         1435  +  if( sqlite3Tsd()->mallocFailed ){
  1436   1436       goto whereBeginNoMem;
  1437   1437     }
  1438   1438     pWInfo->pParse = pParse;
  1439   1439     pWInfo->pTabList = pTabList;
  1440   1440     pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  1441   1441   
  1442   1442     /* Special case: a WHERE clause that is constant.  Evaluate the
................................................................................
  1452   1452     ** want to analyze these virtual terms, so start analyzing at the end
  1453   1453     ** and work forward so that the added virtual terms are never processed.
  1454   1454     */
  1455   1455     for(i=0; i<pTabList->nSrc; i++){
  1456   1456       createMask(&maskSet, pTabList->a[i].iCursor);
  1457   1457     }
  1458   1458     exprAnalyzeAll(pTabList, &maskSet, &wc);
  1459         -  if( sqlite3_malloc_failed ){
         1459  +  if( sqlite3Tsd()->mallocFailed ){
  1460   1460       goto whereBeginNoMem;
  1461   1461     }
  1462   1462   
  1463   1463     /* Chose the best index to use for each table in the FROM clause.
  1464   1464     **
  1465   1465     ** This loop fills in the following fields:
  1466   1466     **

Changes to test/malloc.test.

    10     10   #***********************************************************************
    11     11   # This file attempts to check the library in an out-of-memory situation.
    12     12   # When compiled with -DSQLITE_DEBUG=1, the SQLite library accepts a special
    13     13   # command (sqlite_malloc_fail N) which causes the N-th malloc to fail.  This
    14     14   # special feature is used to see what happens in the library if a malloc
    15     15   # were to really fail due to an out-of-memory situation.
    16     16   #
    17         -# $Id: malloc.test,v 1.24 2005/09/08 00:13:28 drh Exp $
           17  +# $Id: malloc.test,v 1.25 2005/12/06 12:53:01 danielk1977 Exp $
    18     18   
    19     19   set testdir [file dirname $argv0]
    20     20   source $testdir/tester.tcl
    21     21   
    22     22   # Only run these tests if memory debugging is turned on.
    23     23   #
    24     24   if {[info command sqlite_malloc_stat]==""} {
    25         -   puts "Skipping malloc tests: not compiled with -DSQLITE_DEBUG..."
           25  +   puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
    26     26      finish_test
    27     27      return
    28     28   }
    29     29   
    30     30   # Usage: do_malloc_test <test number> <options...>
    31     31   #
    32     32   # The first argument, <test number>, is an integer used to name the
................................................................................
    48     48   # to the -tclbody switch, followed by the SQL commands in any argument
    49     49   # passed to the -sqlbody switch are executed. Each iteration the
    50     50   # Nth call to sqliteMalloc() is made to fail, where N is increased
    51     51   # each time the loop runs starting from 1. When all commands execute
    52     52   # successfully, the loop ends.
    53     53   #
    54     54   proc do_malloc_test {tn args} {
           55  +  array unset ::mallocopts 
    55     56     array set ::mallocopts $args
    56     57   
    57     58     set ::go 1
    58         -  for {set ::n 1} {$::go} {incr ::n} {
           59  +  for {set ::n 1} {$::go && $::n < 50000} {incr ::n} {
    59     60       do_test malloc-$tn.$::n {
    60     61   
           62  +      # Remove all traces of database files test.db and test2.db from the files
           63  +      # system. Then open (empty database) "test.db" with the handle [db].
           64  +      # 
    61     65         sqlite_malloc_fail 0
    62     66         catch {db close}
    63     67         catch {file delete -force test.db}
    64     68         catch {file delete -force test.db-journal}
    65     69         catch {file delete -force test2.db}
    66     70         catch {file delete -force test2.db-journal}
    67     71         set ::DB [sqlite3 db test.db]
    68     72   
           73  +      # Execute any -tclprep and -sqlprep scripts.
           74  +      #
    69     75         if {[info exists ::mallocopts(-tclprep)]} {
    70     76           eval $::mallocopts(-tclprep)
    71     77         }
    72     78         if {[info exists ::mallocopts(-sqlprep)]} {
    73     79           execsql $::mallocopts(-sqlprep)
    74     80         }
    75     81   
           82  +      # Now set the ${::n}th malloc() to fail and execute the -tclbody and
           83  +      # -sqlbody scripts.
           84  +      #
    76     85         sqlite_malloc_fail $::n
    77     86         set ::mallocbody {}
    78     87         if {[info exists ::mallocopts(-tclbody)]} {
    79     88           append ::mallocbody "$::mallocopts(-tclbody)\n"
    80     89         }
    81     90         if {[info exists ::mallocopts(-sqlbody)]} {
    82     91           append ::mallocbody "db eval {$::mallocopts(-sqlbody)}"
    83     92         }
    84         -
    85     93         set v [catch $::mallocbody msg]
    86     94   
    87     95         set leftover [lindex [sqlite_malloc_stat] 2]
    88     96         if {$leftover>0} {
    89     97           if {$leftover>1} {puts "\nLeftover: $leftover\nReturn=$v  Message=$msg"}
    90     98           set ::go 0
    91     99           set v {1 1}

Changes to test/malloc2.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 attempts to check that the library can recover from a malloc()
    12     12   # failure when sqlite3_global_recover() is invoked.
    13     13   #
    14         -# $Id: malloc2.test,v 1.3 2005/06/06 14:45:43 drh Exp $
           14  +# $Id: malloc2.test,v 1.4 2005/12/06 12:53:01 danielk1977 Exp $
    15     15   
    16     16   set testdir [file dirname $argv0]
    17     17   source $testdir/tester.tcl
    18     18   
    19     19   # Only run these tests if memory debugging is turned on.
    20     20   #
    21     21   if {[info command sqlite_malloc_stat]==""} {
................................................................................
    83     83       if {[lindex [sqlite_malloc_stat] 2]>0} {
    84     84         sqlite_malloc_fail -1
    85     85         break
    86     86       }
    87     87   
    88     88       # Nothing should work now, because the allocator should refuse to
    89     89       # allocate any memory.
           90  +    #
           91  +    # Update: SQLite now automatically recovers from a malloc() failure.
           92  +    # So the statement in the test below would work. 
           93  +if 0 {
    90     94       do_test malloc2-$tn.$::n.3 {
    91     95         catchsql {SELECT 'nothing should work'}
    92     96       } {1 {out of memory}}
           97  +}
    93     98   
    94     99       # Recover from the malloc failure.
          100  +    #
          101  +    # Update: The new malloc() failure handling means that a transaction may
          102  +    # still be active even if a malloc() has failed. But when these tests were
          103  +    # written this was not the case. So do a manual ROLLBACK here so that the
          104  +    # tests pass.
    95    105       do_test malloc2-$tn.$::n.4 {
    96         -      if 0 {
    97         -        db close
    98         -        sqlite_malloc_fail -1
    99         -        set ::DB [sqlite3 db test.db]
   100         -        set dummy SQLITE_OK
   101         -      } else {
   102         -        sqlite3_global_recover
          106  +      sqlite3_global_recover
          107  +      catch {
          108  +        execsql {
          109  +          ROLLBACK;
          110  +        }
   103    111         }
   104         -    } {SQLITE_OK}
          112  +      expr 0
          113  +    } {0}
   105    114   
   106    115       # Checksum the database.
   107    116       do_test malloc2-$tn.$::n.5 {
   108    117         cksum db
   109    118       } $sum
   110    119   
   111    120       integrity_check malloc2-$tn.$::n.6
................................................................................
   260    269     sqlite db1 test.db
   261    270     db1 close
   262    271   } {}
   263    272   
   264    273   ########################################################################
   265    274   # Check that if a statement is active sqlite3_global_recover doesn't reset
   266    275   # the sqlite3_malloc_failed variable.
   267         -do_test malloc2-6.1 {
   268         -  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM def} -1 DUMMY]
   269         -  sqlite3_step $::STMT
   270         -} {SQLITE_ROW}
   271         -do_test malloc2-6.2 {
   272         -  sqlite3 db1 test.db
   273         -  sqlite_malloc_fail 100
   274         -  catchsql {
   275         -    SELECT * FROM def;
   276         -  } db1
   277         -} {1 {out of memory}}
   278         -do_test malloc2-6.3 {
   279         -  sqlite3_global_recover
   280         -} {SQLITE_BUSY}
   281         -do_test malloc2-6.4 {
   282         -  catchsql {
   283         -    SELECT 'hello';
   284         -  }
   285         -} {1 {out of memory}}
   286         -do_test malloc2-6.5 {
   287         -  sqlite3_reset $::STMT
   288         -} {SQLITE_OK}
   289         -do_test malloc2-6.6 {
   290         -  sqlite3_global_recover
   291         -} {SQLITE_OK}
   292         -do_test malloc2-6.7 {
   293         -  catchsql {
   294         -    SELECT 'hello';
   295         -  }
   296         -} {0 hello}
   297         -do_test malloc2-6.8 {
   298         -  sqlite3_step $::STMT
   299         -} {SQLITE_ERROR}
   300         -do_test malloc2-6.9 {
   301         -  sqlite3_finalize $::STMT
   302         -} {SQLITE_SCHEMA}
   303         -do_test malloc2-6.10 {
   304         -  db1 close
   305         -} {}
          276  +#
          277  +# Update: There is now no sqlite3_malloc_failed variable, so these tests 
          278  +# are not run.
          279  +#
          280  +# do_test malloc2-6.1 {
          281  +#   set ::STMT [sqlite3_prepare $::DB {SELECT * FROM def} -1 DUMMY]
          282  +#   sqlite3_step $::STMT
          283  +# } {SQLITE_ROW}
          284  +# do_test malloc2-6.2 {
          285  +#   sqlite3 db1 test.db
          286  +#   sqlite_malloc_fail 100
          287  +#   catchsql {
          288  +#     SELECT * FROM def;
          289  +#   } db1
          290  +# } {1 {out of memory}}
          291  +# do_test malloc2-6.3 {
          292  +#   sqlite3_global_recover
          293  +# } {SQLITE_BUSY}
          294  +# do_test malloc2-6.4 {
          295  +#   catchsql {
          296  +#     SELECT 'hello';
          297  +#   }
          298  +# } {1 {out of memory}}
          299  +# do_test malloc2-6.5 {
          300  +#   sqlite3_reset $::STMT
          301  +# } {SQLITE_OK}
          302  +# do_test malloc2-6.6 {
          303  +#   sqlite3_global_recover
          304  +# } {SQLITE_OK}
          305  +# do_test malloc2-6.7 {
          306  +#   catchsql {
          307  +#     SELECT 'hello';
          308  +#   }
          309  +# } {0 hello}
          310  +# do_test malloc2-6.8 {
          311  +#   sqlite3_step $::STMT
          312  +# } {SQLITE_ERROR}
          313  +# do_test malloc2-6.9 {
          314  +#   sqlite3_finalize $::STMT
          315  +# } {SQLITE_SCHEMA}
          316  +# do_test malloc2-6.10 {
          317  +#   db1 close
          318  +# } {}
   306    319   
   307    320   ########################################################################
   308    321   # Check that if an in-memory database is being used it is not possible
   309    322   # to recover from a malloc() failure.
   310         -ifcapable memorydb {
   311         -  do_test malloc2-7.1 {
   312         -    sqlite3 db1 :memory:
   313         -    list
   314         -  } {}
   315         -  do_test malloc2-7.2 {
   316         -    sqlite_malloc_fail 100
   317         -    catchsql {
   318         -      SELECT * FROM def;
   319         -    } 
   320         -  } {1 {out of memory}}
   321         -  do_test malloc2-7.3 {
   322         -    sqlite3_global_recover
   323         -  } {SQLITE_ERROR}
   324         -  do_test malloc2-7.4 {
   325         -    catchsql {
   326         -      SELECT 'hello';
   327         -    }
   328         -  } {1 {out of memory}}
   329         -  do_test malloc2-7.5 {
   330         -    db1 close
   331         -  } {}
   332         -  do_test malloc2-7.6 {
   333         -    sqlite3_global_recover
   334         -  } {SQLITE_OK}
   335         -  do_test malloc2-7.7 {
   336         -    catchsql {
   337         -      SELECT 'hello';
   338         -    }
   339         -  } {0 hello}
   340         -}
          323  +#
          324  +# Update: An in-memory database can now survive a malloc() failure, so these
          325  +# tests are not run.
          326  +#
          327  +# ifcapable memorydb {
          328  +#   do_test malloc2-7.1 {
          329  +#     sqlite3 db1 :memory:
          330  +#     list
          331  +#   } {}
          332  +#   do_test malloc2-7.2 {
          333  +#     sqlite_malloc_fail 100
          334  +#     catchsql {
          335  +#       SELECT * FROM def;
          336  +#     } 
          337  +#   } {1 {out of memory}}
          338  +#   do_test malloc2-7.3 {
          339  +#     sqlite3_global_recover
          340  +#   } {SQLITE_ERROR}
          341  +#   do_test malloc2-7.4 {
          342  +#     catchsql {
          343  +#       SELECT 'hello';
          344  +#     }
          345  +#   } {1 {out of memory}}
          346  +#   do_test malloc2-7.5 {
          347  +#     db1 close
          348  +#   } {}
          349  +#   do_test malloc2-7.6 {
          350  +#     sqlite3_global_recover
          351  +#   } {SQLITE_OK}
          352  +#   do_test malloc2-7.7 {
          353  +#     catchsql {
          354  +#       SELECT 'hello';
          355  +#     }
          356  +#   } {0 hello}
          357  +# }
   341    358   
   342    359   finish_test

Changes to test/schema.test.

     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.
    12     12   #
    13     13   # This file tests the various conditions under which an SQLITE_SCHEMA
    14     14   # error should be returned.
    15     15   #
    16         -# $Id: schema.test,v 1.4 2005/01/29 01:54:18 danielk1977 Exp $
           16  +# $Id: schema.test,v 1.5 2005/12/06 12:53:01 danielk1977 Exp $
    17     17   
    18     18   #---------------------------------------------------------------------
    19     19   # When any of the following types of SQL statements or actions are 
    20     20   # executed, all pre-compiled statements are invalidated. An attempt
    21     21   # to execute an invalidated statement always returns SQLITE_SCHEMA.
    22     22   #
    23     23   # CREATE/DROP TABLE...................................schema-1.*
................................................................................
    25     25   # CREATE/DROP TRIGGER.................................schema-3.*
    26     26   # CREATE/DROP INDEX...................................schema-4.*
    27     27   # DETACH..............................................schema-5.*
    28     28   # Deleting a user-function............................schema-6.*
    29     29   # Deleting a collation sequence.......................schema-7.*
    30     30   # Setting or changing the authorization function......schema-8.*
    31     31   #
    32         -# Note: Test cases schema-6.* are missing right now.
    33         -#
    34     32   # Test cases schema-9.* and schema-10.* test some specific bugs
    35     33   # that came up during development.
    36     34   #
    37     35   # Test cases schema-11.* test that it is impossible to delete or
    38     36   # change a collation sequence or user-function while SQL statements
    39     37   # are executing. Adding new collations or functions is allowed.
    40     38   #
    41         -# Note: Test cases schema-11.* are also missing right now.
    42     39   
    43     40   set testdir [file dirname $argv0]
    44     41   source $testdir/tester.tcl
    45     42   
    46     43   do_test schema-1.1 {
    47     44     set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
    48     45     execsql {

Changes to tool/memleak3.tcl.

   194    194   
   195    195     foreach key [array names ::memmap] {
   196    196       set stack [lindex $::memmap($key) 2]
   197    197       set bytes [lindex $::memmap($key) 0]
   198    198       lappend summarymap($stack) $bytes
   199    199     }
   200    200   
          201  +  set sorted [list]
   201    202     foreach stack [array names summarymap] {
   202    203       set allocs $summarymap($stack)
   203    204       set sum 0
   204    205       foreach a $allocs {
   205    206         incr sum $a
   206    207       }
   207    208       lappend sorted [list $sum $stack]