SQLite

Check-in [e1606658f1]
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
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e1606658f1b4530e3001db4779b5669c8d13c853
User & Date: danielk1977 2005-12-06 12:52:59.000
Context
2005-12-06
12:57
Add test file for new malloc() failure handling. (CVS 2801) (check-in: 0b82f9623c 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: e1606658f1 user: danielk1977 tags: trunk)
2005-12-05
22:22
Update mailing list hyperlink on the support page. (CVS 2799) (check-in: 41a7aeeeb4 user: drh tags: trunk)
Changes
Side-by-Side Diff Ignore Whitespace Patch
Changes to src/alter.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
**
** $Id: alter.c,v 1.9 2005/10/20 07:28:18 drh Exp $
** $Id: alter.c,v 1.10 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
254
255
256
257
258
259
260
261

262
263
264
265
266
267
268
254
255
256
257
258
259
260

261
262
263
264
265
266
267
268







-
+







  char *zName = 0;          /* NULL-terminated version of pName */ 
  sqlite3 *db = pParse->db; /* Database connection */
  Vdbe *v;
#ifndef SQLITE_OMIT_TRIGGER
  char *zWhere = 0;         /* Where clause to locate temp triggers */
#endif
  
  if( sqlite3_malloc_failed ) goto exit_rename_table;
  if( sqlite3Tsd()->mallocFailed ) goto exit_rename_table;
  assert( pSrc->nSrc==1 );

  pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  if( !pTab ) goto exit_rename_table;
  iDb = pTab->iDb;
  zDb = db->aDb[iDb].zName;

500
501
502
503
504
505
506
507

508
509
510
511
512
513
514
500
501
502
503
504
505
506

507
508
509
510
511
512
513
514







-
+







  int iDb;
  int i;
  int nAlloc;


  /* Look up the table being altered. */
  assert( pParse->pNewTable==0 );
  if( sqlite3_malloc_failed ) goto exit_begin_add_column;
  if( sqlite3Tsd()->mallocFailed ) goto exit_begin_add_column;
  pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  if( !pTab ) goto exit_begin_add_column;

  /* Make sure this is not an attempt to ALTER a view. */
  if( pTab->pSelect ){
    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
    goto exit_begin_add_column;
Changes to src/attach.c.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21













-
+







/*
** 2003 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
**
** $Id: attach.c,v 1.34 2005/08/20 03:03:04 drh Exp $
** $Id: attach.c,v 1.35 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** This routine is called by the parser to process an ATTACH statement:
**
**     ATTACH DATABASE filename AS dbname
146
147
148
149
150
151
152

153
154
155
156
157
158
159
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160







+







      db->aDb[i].pBt = 0;
    }
    sqlite3ResetInternalSchema(db, 0);
    assert( pParse->nErr>0 );  /* Always set by sqlite3ReadSchema() */
    if( pParse->rc==SQLITE_OK ){
      pParse->rc = SQLITE_ERROR;
    }
    db->nDb = i;
  }

attach_end:
  sqliteFree(zFile);
  sqliteFree(zName);
}

Changes to src/build.c.
18
19
20
21
22
23
24
25

26
27
28
29
30
31
32
18
19
20
21
22
23
24

25
26
27
28
29
30
31
32







-
+







**     CREATE INDEX
**     DROP INDEX
**     creating ID lists
**     BEGIN TRANSACTION
**     COMMIT
**     ROLLBACK
**
** $Id: build.c,v 1.355 2005/11/14 22:29:05 drh Exp $
** $Id: build.c,v 1.356 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** This routine is called when a new SQL statement is beginning to
** be parsed.  Initialize the pParse structure as needed.
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60
46
47
48
49
50
51
52

53
54
55
56
57
58
59
60







-
+







** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
void sqlite3FinishCoding(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( sqlite3_malloc_failed ) return;
  if( sqlite3Tsd()->mallocFailed ) return;
  if( pParse->nested ) return;
  if( !pParse->pVdbe ){
    if( pParse->rc==SQLITE_OK && pParse->nErr ){
      pParse->rc = SQLITE_ERROR;
    }
    return;
  }
1292
1293
1294
1295
1296
1297
1298
1299



1300
1301
1302
1303
1304
1305
1306
1292
1293
1294
1295
1296
1297
1298

1299
1300
1301
1302
1303
1304
1305
1306
1307
1308







-
+
+
+







  Token *pCons,           /* The ',' token after the last column defn. */
  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
){
  Table *p;
  sqlite3 *db = pParse->db;

  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3Tsd()->mallocFailed ) {
    return;
  }
  p = pParse->pNewTable;
  if( p==0 ) return;

  assert( !db->init.busy || !pSelect );

#ifndef SQLITE_OMIT_CHECK
  /* Resolve names in all CHECK constraint expressions.
1518
1519
1520
1521
1522
1523
1524



1525
1526
1527
1528
1529
1530
1531
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536







+
+
+







  /* Make a copy of the entire SELECT statement that defines the view.
  ** This will force all the Expr.token.z values to be dynamically
  ** allocated rather than point to the input string - which means that
  ** they will persist after the current sqlite3_exec() call returns.
  */
  p->pSelect = sqlite3SelectDup(pSelect);
  sqlite3SelectDelete(pSelect);
  if( sqlite3Tsd()->mallocFailed ){
    return;
  }
  if( !pParse->db->init.busy ){
    sqlite3ViewGetColumnNames(pParse, p);
  }

  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  ** the end.
  */
1588
1589
1590
1591
1592
1593
1594

1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612





















1613
1614
1615
1616
1617
1618
1619
1593
1594
1595
1596
1597
1598
1599
1600


















1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628







+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







  ** "*" elements in the results set of the view and will assign cursors
  ** to the elements of the FROM clause.  But we do not want these changes
  ** to be permanent.  So the computation is done on a copy of the SELECT
  ** statement that defines the view.
  */
  assert( pTable->pSelect );
  pSel = sqlite3SelectDup(pTable->pSelect);
  if( pSel ){
  n = pParse->nTab;
  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  pTable->nCol = -1;
  pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
  pParse->nTab = n;
  if( pSelTab ){
    assert( pTable->aCol==0 );
    pTable->nCol = pSelTab->nCol;
    pTable->aCol = pSelTab->aCol;
    pSelTab->nCol = 0;
    pSelTab->aCol = 0;
    sqlite3DeleteTable(0, pSelTab);
    DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
  }else{
    pTable->nCol = 0;
    nErr++;
  }
  sqlite3SelectDelete(pSel);
    n = pParse->nTab;
    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
    pTable->nCol = -1;
    pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
    pParse->nTab = n;
    if( pSelTab ){
      assert( pTable->aCol==0 );
      pTable->nCol = pSelTab->nCol;
      pTable->aCol = pSelTab->aCol;
      pSelTab->nCol = 0;
      pSelTab->aCol = 0;
      sqlite3DeleteTable(0, pSelTab);
      DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
    }else{
      pTable->nCol = 0;
      nErr++;
    }
    sqlite3SelectDelete(pSel);
  } else {
    nErr++;
  }
  return nErr;  
}
#endif /* SQLITE_OMIT_VIEW */

#ifndef SQLITE_OMIT_VIEW
/*
** Clear the column names from every VIEW in database idx.
1745
1746
1747
1748
1749
1750
1751
1752

1753
1754
1755
1756
1757
1758
1759
1754
1755
1756
1757
1758
1759
1760

1761
1762
1763
1764
1765
1766
1767
1768







-
+







*/
void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
  Table *pTab;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto exit_drop_table;
  assert( pName->nSrc==1 );
  pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);

  if( pTab==0 ) goto exit_drop_table;
  iDb = pTab->iDb;
  assert( iDb>=0 && iDb<db->nDb );
#ifndef SQLITE_OMIT_AUTHORIZATION
2094
2095
2096
2097
2098
2099
2100
2101

2102
2103
2104
2105
2106
2107
2108
2103
2104
2105
2106
2107
2108
2109

2110
2111
2112
2113
2114
2115
2116
2117







-
+







  Token nullId;    /* Fake token for an empty ID list */
  DbFixer sFix;    /* For assigning database names to pTable */
  sqlite3 *db = pParse->db;

  int iDb;          /* Index of the database that is being written */
  Token *pName = 0; /* Unqualified name of the index to create */

  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto exit_create_index;

  /*
  ** Find the table that is to be indexed.  Return early if not found.
  */
  if( pTblName!=0 ){

    /* Use the two-part index name to determine the database 
2222
2223
2224
2225
2226
2227
2228
2229

2230
2231
2232
2233
2234
2235
2236
2231
2232
2233
2234
2235
2236
2237

2238
2239
2240
2241
2242
2243
2244
2245







-
+







  }

  /* 
  ** Allocate the index structure. 
  */
  pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) +
                        (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr );
  if( sqlite3_malloc_failed ) goto exit_create_index;
  if( sqlite3Tsd()->mallocFailed ) goto exit_create_index;
  pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
  pIndex->aiRowEst = (unsigned*)&pIndex->aiColumn[pList->nExpr];
  pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1];
  strcpy(pIndex->zName, zName);
  pIndex->pTable = pTab;
  pIndex->nColumn = pList->nExpr;
  pIndex->onError = onError;
2468
2469
2470
2471
2472
2473
2474
2475

2476
2477
2478
2479
2480
2481
2482
2477
2478
2479
2480
2481
2482
2483

2484
2485
2486
2487
2488
2489
2490
2491







-
+







** implements the DROP INDEX statement.
*/
void sqlite3DropIndex(Parse *pParse, SrcList *pName){
  Index *pIndex;
  Vdbe *v;
  sqlite3 *db = pParse->db;

  if( pParse->nErr || sqlite3_malloc_failed ){
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ){
    goto exit_drop_index;
  }
  assert( pName->nSrc==1 );
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    goto exit_drop_index;
  }
  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2675
2676
2677
2678
2679
2680
2681


2682
2683
2684
2685
2686






2687
2688
2689
2690
2691
2692
2693
2684
2685
2686
2687
2688
2689
2690
2691
2692





2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705







+
+
-
-
-
-
-
+
+
+
+
+
+








/*
** Assign cursors to all tables in a SrcList
*/
void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  int i;
  struct SrcList_item *pItem;
  assert(pList || sqlite3Tsd()->mallocFailed);
  if( pList ){
  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
    if( pItem->iCursor>=0 ) break;
    pItem->iCursor = pParse->nTab++;
    if( pItem->pSelect ){
      sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
      if( pItem->iCursor>=0 ) break;
      pItem->iCursor = pParse->nTab++;
      if( pItem->pSelect ){
        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
      }
    }
  }
}

/*
** Add an alias to the last identifier on the given identifier list.
*/
2721
2722
2723
2724
2725
2726
2727
2728

2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749

2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766

2767
2768
2769
2770
2771
2772
2773
2733
2734
2735
2736
2737
2738
2739

2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760

2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777

2778
2779
2780
2781
2782
2783
2784
2785







-
+




















-
+
















-
+







*/
void sqlite3BeginTransaction(Parse *pParse, int type){
  sqlite3 *db;
  Vdbe *v;
  int i;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3_malloc_failed ) return;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;

  v = sqlite3GetVdbe(pParse);
  if( !v ) return;
  if( type!=TK_DEFERRED ){
    for(i=0; i<db->nDb; i++){
      sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
    }
  }
  sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
}

/*
** Commit a transaction
*/
void sqlite3CommitTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3_malloc_failed ) return;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;

  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
  }
}

/*
** Rollback a transaction
*/
void sqlite3RollbackTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3_malloc_failed ) return;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;

  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
  }
}
Changes to src/callback.c.
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
**
** $Id: callback.c,v 1.4 2005/10/20 07:28:18 drh Exp $
** $Id: callback.c,v 1.5 2005/12/06 12:52:59 danielk1977 Exp $
*/

#include "sqliteInt.h"

/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the database text encoding of name zName, length nName.
171
172
173
174
175
176
177
178

179
180
181
182
183
184
185
171
172
173
174
175
176
177

178
179
180
181
182
183
184
185







-
+







      pColl[0].zName[nName] = 0;
      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);

      /* If a malloc() failure occured in sqlite3HashInsert(), it will 
      ** return the pColl pointer to be deleted (because it wasn't added
      ** to the hash table).
      */
      assert( !pDel || (sqlite3_malloc_failed && pDel==pColl) );
      assert( !pDel || (sqlite3Tsd()->mallocFailed && pDel==pColl) );
      sqliteFree(pDel);
    }
  }
  return pColl;
}

/*
Changes to src/delete.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
**
** $Id: delete.c,v 1.111 2005/09/20 17:42:23 drh Exp $
** $Id: delete.c,v 1.112 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** Look up every table that is named in pSrc.  If any table is not found,
** add an error message to pParse->zErrMsg and return NULL.  If all tables
** are found, return a pointer to the last table.
98
99
100
101
102
103
104
105

106
107
108
109
110
111
112
98
99
100
101
102
103
104

105
106
107
108
109
110
111
112







-
+








#ifndef SQLITE_OMIT_TRIGGER
  int isView;                  /* True if attempting to delete from a view */
  int triggers_exist = 0;      /* True if any triggers exist */
#endif

  sContext.pParse = 0;
  if( pParse->nErr || sqlite3_malloc_failed ){
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ){
    goto delete_from_cleanup;
  }
  db = pParse->db;
  assert( pTabList->nSrc==1 );

  /* Locate the table which we want to delete.  This table has to be
  ** put in an SrcList structure because some of the subroutines we
Changes to src/expr.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
**
** $Id: expr.c,v 1.240 2005/11/29 03:13:22 drh Exp $
** $Id: expr.c,v 1.241 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** Return the 'affinity' of the expression pExpr if any.
**
259
260
261
262
263
264
265
266

267
268
269
270
271
272
273
259
260
261
262
263
264
265

266
267
268
269
270
271
272
273







-
+







/*
** Set the Expr.span field of the given expression to span all
** text between the two given tokens.
*/
void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
  assert( pRight!=0 );
  assert( pLeft!=0 );
  if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
  if( !sqlite3Tsd()->mallocFailed && pRight->z && pLeft->z ){
    assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
    if( pLeft->dyn==0 && pRight->dyn==0 ){
      pExpr->span.z = pLeft->z;
      pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
    }else{
      pExpr->span.z = 0;
    }
354
355
356
357
358
359
360
361

362
363
364
365
366
367
368
354
355
356
357
358
359
360

361
362
363
364
365
366
367
368







-
+







    if( i>=pParse->nVarExpr ){
      pExpr->iTable = ++pParse->nVar;
      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
        sqlite3ReallocOrFree((void**)&pParse->apVarExpr,
                       pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
      }
      if( !sqlite3_malloc_failed ){
      if( !sqlite3Tsd()->mallocFailed ){
        assert( pParse->apVarExpr!=0 );
        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
      }
    }
  } 
}

458
459
460
461
462
463
464
465

466
467
468
469
470
471
472
458
459
460
461
462
463
464

465
466
467
468
469
470
471
472







-
+







    if( pOldExpr->span.z!=0 && pNewExpr ){
      /* Always make a copy of the span for top-level expressions in the
      ** expression list.  The logic in SELECT processing that determines
      ** the names of columns in the result set needs this information */
      sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
    }
    assert( pNewExpr==0 || pNewExpr->span.z!=0 
            || pOldExpr->span.z==0 || sqlite3_malloc_failed );
            || pOldExpr->span.z==0 || sqlite3Tsd()->mallocFailed );
    pItem->zName = sqliteStrDup(pOldItem->zName);
    pItem->sortOrder = pOldItem->sortOrder;
    pItem->isAgg = pOldItem->isAgg;
    pItem->done = 0;
  }
  return pNew;
}
827
828
829
830
831
832
833
834

835
836
837
838
839
840
841
827
828
829
830
831
832
833

834
835
836
837
838
839
840
841







-
+







  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
  NameContext *pTopNC = pNC;        /* First namecontext in the list */

  assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
  zDb = sqlite3NameFromToken(pDbToken);
  zTab = sqlite3NameFromToken(pTableToken);
  zCol = sqlite3NameFromToken(pColumnToken);
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    goto lookupname_end;
  }

  pExpr->iTable = -1;
  while( pNC && cnt==0 ){
    ExprList *pEList;
    SrcList *pSrcList = pNC->pSrcList;
1301
1302
1303
1304
1305
1306
1307
1308

1309
1310
1311
1312
1313
1314
1315
1301
1302
1303
1304
1305
1306
1307

1308
1309
1310
1311
1312
1313
1314
1315







-
+







  ** If all of the above are false, then we can run this code just once
  ** save the results, and reuse the same result on subsequent invocations.
  */
  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
    int mem = pParse->nMem++;
    sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
    testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
    assert( testAddr>0 || sqlite3_malloc_failed );
    assert( testAddr>0 || sqlite3Tsd()->mallocFailed );
    sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
  }

  switch( pExpr->op ){
    case TK_IN: {
      char affinity;
      KeyInfo keyInfo;
Changes to src/insert.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle INSERT statements in SQLite.
**
** $Id: insert.c,v 1.149 2005/11/24 13:15:33 drh Exp $
** $Id: insert.c,v 1.150 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** Set P3 of the most recently inserted opcode to a column affinity
** string for index pIdx. A column affinity string has one character
** for each column in the table, according to the affinity of the column:
220
221
222
223
224
225
226
227

228
229
230
231
232
233
234
220
221
222
223
224
225
226

227
228
229
230
231
232
233
234







-
+







  int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
#endif

#ifndef SQLITE_OMIT_AUTOINCREMENT
  int counterRowid;     /* Memory cell holding rowid of autoinc counter */
#endif

  if( pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto insert_cleanup;
  db = pParse->db;

  /* Locate the table into which we will be inserting new information.
  */
  assert( pTabList->nSrc==1 );
  zTab = pTabList->a[0].zName;
  if( zTab==0 ) goto insert_cleanup;
334
335
336
337
338
339
340
341

342
343
344
345
346
347
348
334
335
336
337
338
339
340

341
342
343
344
345
346
347
348







-
+







    int rc, iInitCode;
    iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
    iSelectLoop = sqlite3VdbeCurrentAddr(v);
    iInsertBlock = sqlite3VdbeMakeLabel(v);

    /* Resolve the expressions in the SELECT statement and execute it. */
    rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
    if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
    if( rc || pParse->nErr || sqlite3Tsd()->mallocFailed ) goto insert_cleanup;

    iCleanup = sqlite3VdbeMakeLabel(v);
    sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
    assert( pSelect->pEList );
    nColumn = pSelect->pEList->nExpr;

    /* Set useTempTable to TRUE if the result of the SELECT statement
Changes to src/legacy.c.
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+







**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: legacy.c,v 1.7 2004/09/06 17:34:13 drh Exp $
** $Id: legacy.c,v 1.8 2005/12/06 12:52:59 danielk1977 Exp $
*/

#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>

/*
118
119
120
121
122
123
124
125

126
127
128
129
130
131
132
133
134
135
136
137
138
118
119
120
121
122
123
124

125
126
127
128
129
130
131
132
133
134
135
136
137
138







-
+













    azCols = 0;
  }

exec_out:
  if( pStmt ) sqlite3_finalize(pStmt);
  if( azCols ) sqliteFree(azCols);

  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    rc = SQLITE_NOMEM;
  }
  if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
    *pzErrMsg = malloc(1+strlen(sqlite3_errmsg(db)));
    if( *pzErrMsg ){
      strcpy(*pzErrMsg, sqlite3_errmsg(db));
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  return rc;
}
Changes to src/main.c.
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+







**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: main.c,v 1.304 2005/11/30 03:20:31 drh Exp $
** $Id: main.c,v 1.305 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>

/*
** The following constant value is used by the SQLITE_BIGENDIAN and
631
632
633
634
635
636
637
638

639
640
641
642
643
644
645
631
632
633
634
635
636
637

638
639
640
641
642
643
644
645







-
+








/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
  const char *z;
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return sqlite3ErrStr(SQLITE_NOMEM);
  }
  if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
    return sqlite3ErrStr(SQLITE_MISUSE);
  }
  z = sqlite3_value_text(db->pErr);
  if( z==0 ){
670
671
672
673
674
675
676
677

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697

698
699
700
701
702
703
704
670
671
672
673
674
675
676

677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696

697
698
699
700
701
702
703
704







-
+



















-
+







    0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
    0, 'o', 0, 'u', 0, 't', 0, ' ', 
    0, 'o', 0, 'f', 0, ' ', 
    0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
  };

  const void *z;
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  }
  if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
    return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  }
  z = sqlite3_value_text16(db->pErr);
  if( z==0 ){
    sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
         SQLITE_UTF8, SQLITE_STATIC);
    z = sqlite3_value_text16(db->pErr);
  }
  return z;
}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Return the most recent error code generated by an SQLite routine.
*/
int sqlite3_errcode(sqlite3 *db){
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return SQLITE_NOMEM;
  }
  if( sqlite3SafetyCheck(db) ){
    return SQLITE_MISUSE;
  }
  return db->errCode;
}
738
739
740
741
742
743
744
745
746

747
748
749
750
751
752
753
738
739
740
741
742
743
744


745
746
747
748
749
750
751
752







-
-
+







  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  if( sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binCollFunc) ||
      sqlite3_create_collation(db, "BINARY", SQLITE_UTF16, 0,binCollFunc) ||
      (db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0))==0 ){
    rc = db->errCode;
    assert( rc!=SQLITE_OK );
    assert(rc!=SQLITE_OK || sqlite3Tsd()->mallocFailed);
    db->magic = SQLITE_MAGIC_CLOSED;
    goto opendb_out;
  }

  /* Also add a UTF-8 case-insensitive collation sequence. */
  sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);

782
783
784
785
786
787
788
789

790
791
792
793
794
795
796
781
782
783
784
785
786
787

788
789
790
791
792
793
794
795







-
+







  ** is accessed.
  */
  sqlite3RegisterBuiltinFunctions(db);
  sqlite3Error(db, SQLITE_OK, 0);
  db->magic = SQLITE_MAGIC_OPEN;

opendb_out:
  if( sqlite3_errcode(db)==SQLITE_OK && sqlite3_malloc_failed ){
  if( sqlite3_errcode(db)==SQLITE_OK && sqlite3Tsd()->mallocFailed ){
    sqlite3Error(db, SQLITE_NOMEM, 0);
  }
  *ppDb = db;
#ifndef SQLITE_OMIT_GLOBALRECOVER
  if( db ){
    sqlite3Os.xEnterMutex();
    db->pNext = pDbList;
1006
1007
1008
1009
1010
1011
1012

1013
1014
1015

1016
1017
1018

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033

1034
1035


1036
1037
1038
1039
1040
1041
1042
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014

1015
1016
1017

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032

1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044







+


-
+


-
+














-
+


+
+







** within SQLite. 
**
** This function is *not* threadsafe. Calling this from within a threaded
** application when threads other than the caller have used SQLite is 
** dangerous and will almost certainly result in malfunctions.
*/
int sqlite3_global_recover(){
#if 0
  int rc = SQLITE_OK;

  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    sqlite3 *db;
    int i;
    sqlite3_malloc_failed = 0;
    sqlite3Tsd()->mallocFailed = 0;
    for(db=pDbList; db; db=db->pNext ){
      sqlite3ExpirePreparedStatements(db);
      for(i=0; i<db->nDb; i++){
        Btree *pBt = db->aDb[i].pBt;
        if( pBt && (rc=sqlite3BtreeReset(pBt))!=0 ){
          goto recover_out;
        }
      } 
      db->autoCommit = 1;
    }
  }

recover_out:
  if( rc!=SQLITE_OK ){
    sqlite3_malloc_failed = 1;
    sqlite3Tsd()->mallocFailed = 1;
  }
  return rc;
#endif
  return SQLITE_OK;
}
#endif

/*
** Test to see whether or not the database connection is in autocommit
** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
** by default.  Autocommit is disabled by a BEGIN statement and reenabled
Changes to src/os_unix.c.
685
686
687
688
689
690
691

692
693
694
695
696
697
698
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699







+







  sqlite3Os.xLeaveMutex();
  if( rc ){
    close(f.h);
    return SQLITE_NOMEM;
  }
  f.locktype = 0;
  TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);

  return allocateUnixFile(&f, pId);
}

/*
** Attempt to open a file descriptor for the directory that contains a
** file.  This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
Changes to src/pager.c.
14
15
16
17
18
19
20
21

22
23
24
25
26
27
28
14
15
16
17
18
19
20

21
22
23
24
25
26
27
28







-
+







** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
**
** @(#) $Id: pager.c,v 1.222 2005/11/30 03:20:31 drh Exp $
** @(#) $Id: pager.c,v 1.223 2005/12/06 12:52:59 danielk1977 Exp $
*/
#ifndef SQLITE_OMIT_DISKIO
#include "sqliteInt.h"
#include "os.h"
#include "pager.h"
#include <assert.h>
#include <string.h>
1594
1595
1596
1597
1598
1599
1600
1601

1602
1603
1604
1605
1606
1607
1608
1594
1595
1596
1597
1598
1599
1600

1601
1602
1603
1604
1605
1606
1607
1608







-
+







  int readOnly = 0;
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
  char zTemp[SQLITE_TEMPNAME_SIZE];

  *ppPager = 0;
  memset(&fd, 0, sizeof(fd));
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return SQLITE_NOMEM;
  }
  if( zFilename && zFilename[0] ){
#ifndef SQLITE_OMIT_MEMORYDB
    if( strcmp(zFilename,":memory:")==0 ){
      memDb = 1;
      zFullPathname = sqliteStrDup("");
2409
2410
2411
2412
2413
2414
2415
2416

2417
2418
2419
2420
2421
2422
2423
2409
2410
2411
2412
2413
2414
2415

2416
2417
2418
2419
2420
2421
2422
2423







-
+







    TEST_INCR(pPager->nMiss);
    if( pPager->nPage<pPager->mxPage || pPager->pFirst==0 || MEMDB ){
      /* Create a new page */
      pPg = sqliteMallocRaw( sizeof(*pPg) + pPager->pageSize
                              + sizeof(u32) + pPager->nExtra
                              + MEMDB*sizeof(PgHistory) );
      if( pPg==0 ){
        pPager->errMask |= PAGER_ERR_MEM;
        // pPager->errMask |= PAGER_ERR_MEM;
        return SQLITE_NOMEM;
      }
      memset(pPg, 0, sizeof(*pPg));
      if( MEMDB ){
        memset(PGHDR_TO_HIST(pPg, pPager), 0, sizeof(PgHistory));
      }
      pPg->pPager = pPager;
2688
2689
2690
2691
2692
2693
2694
2695

2696
2697
2698
2699
2700
2701
2702
2703
2704
2705








2706
2707



2708
2709
2710
2711
2712
2713
2714
2688
2689
2690
2691
2692
2693
2694

2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713


2714
2715
2716
2717
2718
2719
2720
2721
2722
2723







-
+










+
+
+
+
+
+
+
+
-
-
+
+
+







  pPager->origDbSize = pPager->dbSize;

  rc = writeJournalHdr(pPager);

  if( pPager->stmtAutoopen && rc==SQLITE_OK ){
    rc = sqlite3pager_stmt_begin(pPager);
  }
  if( rc!=SQLITE_OK ){
  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
    rc = pager_unwritelock(pPager);
    if( rc==SQLITE_OK ){
      rc = SQLITE_FULL;
    }
  }
  return rc;

failed_to_open_journal:
  sqliteFree(pPager->aInJournal);
  pPager->aInJournal = 0;
  if( rc==SQLITE_NOMEM ){
    /* If this was a malloc() failure, then we will not be closing the pager
    ** file. So delete any journal file we may have just created. Otherwise,
    ** the system will get confused, we have a read-lock on the file and a
    ** mysterious journal has appeared in the filesystem.
    */
    sqlite3Os.xDelete(pPager->zJournal);
  }else{
  sqlite3OsUnlock(pPager->fd, NO_LOCK);
  pPager->state = PAGER_UNLOCK;
    sqlite3OsUnlock(pPager->fd, NO_LOCK);
    pPager->state = PAGER_UNLOCK;
  }
  return rc;
}

/*
** Acquire a write-lock on the database.  The lock is removed when
** the any of the following happen:
**
3266
3267
3268
3269
3270
3271
3272
3273

3274
3275
3276
3277
3278
3279
3280
3275
3276
3277
3278
3279
3280
3281

3282
3283
3284
3285
3286
3287
3288
3289







-
+







  if( !pPager->journalOpen ){
    pPager->stmtAutoopen = 1;
    return SQLITE_OK;
  }
  assert( pPager->journalOpen );
  pPager->aInStmt = sqliteMalloc( pPager->dbSize/8 + 1 );
  if( pPager->aInStmt==0 ){
    sqlite3OsLock(pPager->fd, SHARED_LOCK);
    /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
    return SQLITE_NOMEM;
  }
#ifndef NDEBUG
  rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
  if( rc ) goto stmt_begin_failed;
  assert( pPager->stmtJSize == pPager->journalOff );
#endif
Changes to src/prepare.c.
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27

28
29
30
31
32
33
34
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34







-
+










-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
**
** $Id: prepare.c,v 1.4 2005/09/10 16:46:13 drh Exp $
** $Id: prepare.c,v 1.5 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>

/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(InitData *pData, const char *zExtra){
  if( !sqlite3_malloc_failed ){
  if( !sqlite3Tsd()->mallocFailed ){
    sqlite3SetString(pData->pzErrMsg, "malformed database schema",
       zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
  }
}

/*
** This is the callback routine for the code that initializes the
67
68
69
70
71
72
73



74


75
76
77
78
79
80
81
67
68
69
70
71
72
73
74
75
76

77
78
79
80
81
82
83
84
85







+
+
+
-
+
+







    int rc;
    assert( db->init.busy );
    db->init.iDb = iDb;
    db->init.newTnum = atoi(argv[1]);
    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
    db->init.iDb = 0;
    if( SQLITE_OK!=rc ){
      if( rc==SQLITE_NOMEM ){
          sqlite3Tsd()->mallocFailed = 1;
      }else{
      corruptSchema(pData, zErr);
          corruptSchema(pData, zErr);
      }
      sqlite3_free(zErr);
      return rc;
    }
  }else{
    /* If the SQL column is blank it means this is an index that
    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
    ** constraint for a CREATE TABLE.  The index should have already
297
298
299
300
301
302
303
304

305
306
307
308
309
310
311
301
302
303
304
305
306
307

308
309
310
311
312
313
314
315







-
+







#ifndef SQLITE_OMIT_ANALYZE
    if( rc==SQLITE_OK ){
      sqlite3AnalysisLoad(db, iDb);
    }
#endif
    sqlite3BtreeCloseCursor(curMain);
  }
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
    rc = SQLITE_NOMEM;
    sqlite3ResetInternalSchema(db, 0);
  }
  if( rc==SQLITE_OK ){
    DbSetProperty(db, iDb, DB_SchemaLoaded);
  }else{
421
422
423
424
425
426
427
428

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445





446
447


448
449
450
451
452
453
454
425
426
427
428
429
430
431

432


433
434
435
436
437
438
439
440
441
442
443




444
445
446
447
448
449

450
451
452
453
454
455
456
457
458







-
+
-
-











-
-
-
-
+
+
+
+
+

-
+
+







  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char** pzTail       /* OUT: End of parsed string */
){
  Parse sParse;
  char *zErrMsg = 0;
  int rc = SQLITE_OK;

  if( sqlite3_malloc_failed ){
  assert(!sqlite3Tsd()->mallocFailed);
    return SQLITE_NOMEM;
  }

  assert( ppStmt );
  *ppStmt = 0;
  if( sqlite3SafetyOn(db) ){
    return SQLITE_MISUSE;
  }

  memset(&sParse, 0, sizeof(sParse));
  sParse.db = db;
  sqlite3RunParser(&sParse, zSql, &zErrMsg);

  if( sqlite3_malloc_failed ){
    rc = SQLITE_NOMEM;
    sqlite3RollbackAll(db);
    sqlite3ResetInternalSchema(db, 0);
  if( sqlite3Tsd()->mallocFailed ){
    sParse.rc = SQLITE_NOMEM;
#if 0
    sqlite3RollbackInternalChanges(db);
    sqlite3RollbackAll(db);
    db->flags &= ~SQLITE_InTrans;
    goto prepare_out;
    db->autoCommit = 1;
#endif
  }
  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  if( sParse.rc!=SQLITE_OK && sParse.checkSchema && !schemaIsValid(db) ){
    sParse.rc = SQLITE_SCHEMA;
  }
  if( sParse.rc==SQLITE_SCHEMA ){
    sqlite3ResetInternalSchema(db, 0);
486
487
488
489
490
491
492










493
494
495
496
497
498
499
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513







+
+
+
+
+
+
+
+
+
+








  if( zErrMsg ){
    sqlite3Error(db, rc, "%s", zErrMsg);
    sqliteFree(zErrMsg);
  }else{
    sqlite3Error(db, rc, 0);
  }

  /* We must check for malloc failure last of all, in case malloc() failed
  ** inside of the sqlite3Error() call above or something.
  */
  if( sqlite3Tsd()->mallocFailed ){
    rc = SQLITE_NOMEM;
    sqlite3Error(db, rc, 0);
  }

  sqlite3ClearMallocFailed();
  return rc;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
*/
Changes to src/select.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
**
** $Id: select.c,v 1.280 2005/11/16 13:47:51 drh Exp $
** $Id: select.c,v 1.281 2005/12/06 12:52:59 danielk1977 Exp $
*/
#include "sqliteInt.h"


/*
** Allocate a new Select structure and return a pointer to that
** structure.
151
152
153
154
155
156
157
158

159
160
161
162
163
164
165
151
152
153
154
155
156
157

158
159
160
161
162
163
164
165







-
+







}

/*
** Set the value of a token to a '\000'-terminated string.
*/
static void setToken(Token *p, const char *z){
  p->z = z;
  p->n = strlen(z);
  p->n = z ? strlen(z) : 0;
  p->dyn = 0;
}

/*
** Create an expression node for an identifier with the name of zName
*/
static Expr *createIdExpr(const char *zName){
852
853
854
855
856
857
858
859

860
861
862
863
864
865
866
852
853
854
855
856
857
858

859
860
861
862
863
864
865
866







-
+







  /* If this is an EXPLAIN, skip this step */
  if( pParse->explain ){
    return;
  }
#endif

  assert( v!=0 );
  if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
  if( pParse->colNamesSet || v==0 || sqlite3Tsd()->mallocFailed ) return;
  pParse->colNamesSet = 1;
  fullNames = (db->flags & SQLITE_FullColNames)!=0;
  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  sqlite3VdbeSetNumCols(v, pEList->nExpr);
  for(i=0; i<pEList->nExpr; i++){
    Expr *p;
    p = pEList->a[i].pExpr;
980
981
982
983
984
985
986
987

988
989
990
991
992
993
994
980
981
982
983
984
985
986

987
988
989
990
991
992
993
994







-
+







      /* Use the original text of the column expression as its name */
      zName = sqlite3MPrintf("%T", &p->span);
    }else{
      /* If all else fails, make up a name */
      zName = sqlite3MPrintf("column%d", i+1);
    }
    sqlite3Dequote(zName);
    if( sqlite3_malloc_failed ){
    if( sqlite3Tsd()->mallocFailed ){
      sqliteFree(zName);
      sqlite3DeleteTable(0, pTab);
      return 0;
    }

    /* Make sure the column name is unique.  If the name is not unique,
    ** append a integer to the name so that it becomes unique.
1052
1053
1054
1055
1056
1057
1058
1059

1060
1061
1062
1063
1064
1065
1066
1052
1053
1054
1055
1056
1057
1058

1059
1060
1061
1062
1063
1064
1065
1066







-
+







static int prepSelectStmt(Parse *pParse, Select *p){
  int i, j, k, rc;
  SrcList *pTabList;
  ExprList *pEList;
  Table *pTab;
  struct SrcList_item *pFrom;

  if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
  if( p==0 || p->pSrc==0 || sqlite3Tsd()->mallocFailed ) return 1;
  pTabList = p->pSrc;
  pEList = p->pEList;

  /* Make sure cursor numbers have been assigned to all entries in
  ** the FROM clause of the SELECT statement.
  */
  sqlite3SrcListAssignCursors(pParse, p->pSrc);
1160
1161
1162
1163
1164
1165
1166

1167




1168
1169
1170
1171
1172
1173
1174
1160
1161
1162
1163
1164
1165
1166
1167

1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178







+
-
+
+
+
+







    for(k=0; k<pEList->nExpr; k++){
      Expr *pE = a[k].pExpr;
      if( pE->op!=TK_ALL &&
           (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
        /* This particular expression does not need to be expanded.
        */
        pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
        if( pNew ){
        pNew->a[pNew->nExpr-1].zName = a[k].zName;
          pNew->a[pNew->nExpr-1].zName = a[k].zName;
        }else{
          rc = 1;
        }
        a[k].pExpr = 0;
        a[k].zName = 0;
      }else{
        /* This expression is a "*" or a "TABLE.*" and needs to be
        ** expanded. */
        int tableSeen = 0;      /* Set to 1 when TABLE matches */
        char *zTName;            /* text of name of TABLE */
2635
2636
2637
2638
2639
2640
2641
2642

2643
2644
2645
2646
2647
2648
2649
2639
2640
2641
2642
2643
2644
2645

2646
2647
2648
2649
2650
2651
2652
2653







-
+







  int isDistinct;        /* True if the DISTINCT keyword is present */
  int distinct;          /* Table to use for the distinct set */
  int rc = 1;            /* Value to return from this function */
  int addrSortIndex;     /* Address of an OP_OpenVirtual instruction */
  AggInfo sAggInfo;      /* Information used by aggregate queries */
  int iEnd;              /* Address of the end of the query */

  if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
  if( sqlite3Tsd()->mallocFailed || pParse->nErr || p==0 ) return 1;
  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  memset(&sAggInfo, 0, sizeof(sAggInfo));

#ifndef SQLITE_OMIT_COMPOUND_SELECT
  /* If there is are a sequence of queries, do the earlier ones first.
  */
  if( p->pPrior ){
2889
2890
2891
2892
2893
2894
2895
2896

2897
2898
2899
2900
2901
2902
2903
2893
2894
2895
2896
2897
2898
2899

2900
2901
2902
2903
2904
2905
2906
2907







-
+







    }
    sAggInfo.nAccumulator = sAggInfo.nColumn;
    for(i=0; i<sAggInfo.nFunc; i++){
      if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
        goto select_end;
      }
    }
    if( sqlite3_malloc_failed ) goto select_end;
    if( sqlite3Tsd()->mallocFailed ) goto select_end;

    /* Processing for aggregates with GROUP BY is very different and
    ** much more complex tha aggregates without a GROUP BY.
    */
    if( pGroupBy ){
      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */

Changes to src/sqliteInt.h.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21













-
+







/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Internal interface definitions for SQLite.
**
** @(#) $Id: sqliteInt.h,v 1.428 2005/11/14 22:29:05 drh Exp $
** @(#) $Id: sqliteInt.h,v 1.429 2005/12/06 12:52:59 danielk1977 Exp $
*/
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

/*
** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
** Setting NDEBUG makes the code smaller and run faster.  So the following
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
259
260
261
262
263
264
265






266
267
268
269
270
271
272







-
-
-
-
-
-







# define sqliteMalloc        sqlite3Malloc
# define sqliteMallocRaw     sqlite3MallocRaw
# define sqliteRealloc       sqlite3Realloc
# define sqliteStrDup        sqlite3StrDup
# define sqliteStrNDup       sqlite3StrNDup
#endif

/*
** This variable gets set if malloc() ever fails.  After it gets set,
** the SQLite library shuts down permanently.
*/
extern int sqlite3_malloc_failed;

/*
** The following global variables are used for testing and debugging
** only.  They only work if SQLITE_DEBUG is defined.
*/
#ifdef SQLITE_MEMDEBUG
extern int sqlite3_nMalloc;      /* Number of sqliteMalloc() calls */
extern int sqlite3_nFree;        /* Number of sqliteFree() calls */
1381
1382
1383
1384
1385
1386
1387








1388
1389
1390
1391
1392
1393
1394
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396







+
+
+
+
+
+
+
+







** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
*/
typedef struct {
  sqlite3 *db;        /* The database being initialized */
  char **pzErrMsg;    /* Error message stored here */
} InitData;

/*
** An instance of this structure is allocated for each thread that uses SQLite.
*/
typedef struct SqliteTsd SqliteTsd;
struct SqliteTsd {
  int mallocFailed;               /* True after a malloc() has failed */
};

/*
 * This global flag is set for performance testing of triggers. When it is set
 * SQLite will perform the overhead of building new and old trigger references 
 * even when no triggers exist
 */
extern int sqlite3_always_code_trigger_setup;

1670
1671
1672
1673
1674
1675
1676


1677
1678
1679
1680
1681
1682
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686







+
+






void sqlite3Analyze(Parse*, Token*, Token*);
int sqlite3InvokeBusyHandler(BusyHandler*);
int sqlite3FindDb(sqlite3*, Token*);
void sqlite3AnalysisLoad(sqlite3*,int iDB);
void sqlite3DefaultRowEst(Index*);
void sqlite3RegisterLikeFunctions(sqlite3*, int);
int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
SqliteTsd *sqlite3Tsd();
void sqlite3ClearMallocFailed();

#ifdef SQLITE_SSE
#include "sseInt.h"
#endif

#endif
Changes to src/test1.c.
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the printf() interface to SQLite.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.170 2005/12/05 13:20:02 drh Exp $
** $Id: test1.c,v 1.171 2005/12/06 12:53:00 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include "os.h"
#include <stdlib.h>
#include <string.h>

783
784
785
786
787
788
789
790

791
792
793
794
795
796
797
783
784
785
786
787
788
789

790
791
792
793
794
795
796
797







-
+







**
** Rig sqliteMalloc() to fail on the N-th call and every REPEAT-INTERVAL call
** after that.  If REPEAT-INTERVAL is 0 or is omitted, then only a single
** malloc will fail.  If REPEAT-INTERVAL is 1 then all mallocs after the
** first failure will continue to fail on every call.  If REPEAT-INTERVAL is
** 2 then every other malloc will fail.  And so forth.
**
** Turn off this mechanism and reset the sqlite3_malloc_failed variable is N==0.
** Turn off this mechanism and reset the sqlite3Tsd()->mallocFailed variable is N==0.
*/
#ifdef SQLITE_MEMDEBUG
static int sqlite_malloc_fail(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
806
807
808
809
810
811
812
813

814
815
816
817
818
819
820
806
807
808
809
810
811
812

813
814
815
816
817
818
819
820







-
+







  if( argc==3 ){
    if( Tcl_GetInt(interp, argv[2], &rep) ) return TCL_ERROR;
  }else{
    rep = 0;
  }
  sqlite3_iMallocFail = n;
  sqlite3_iMallocReset = rep;
  sqlite3_malloc_failed = 0;
  sqlite3Tsd()->mallocFailed = 0;
  return TCL_OK;
}
#endif

/*
** Usage: sqlite_malloc_stat
**
948
949
950
951
952
953
954
955

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976



977

978
979
980

981
982
983
984
985
986
987
948
949
950
951
952
953
954

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974


975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990







-
+



















-
-
+
+
+

+



+







  if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite3_reset  STMT 
**
** Finalize a statement handle.
** Reset a statement handle.
*/
static int test_reset(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_stmt *pStmt;
  int rc;

  if( objc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
    return TCL_ERROR;
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;

  rc = sqlite3_reset(pStmt);
  if( pStmt && 
      sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){
    return TCL_ERROR;
  }
  Tcl_SetResult(interp, (char *)errorName(rc), TCL_STATIC);
/*
  if( rc ){
    return TCL_ERROR;
  }
*/
  return TCL_OK;
}

/*
** Usage:  sqlite3_expired STMT 
**
** Return TRUE if a recompilation of the statement is recommended.
Changes to src/tokenize.c.
11
12
13
14
15
16
17
18

19
20
21
22
23
24
25
11
12
13
14
15
16
17

18
19
20
21
22
23
24
25







-
+







*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
**
** $Id: tokenize.c,v 1.108 2005/10/23 11:29:40 drh Exp $
** $Id: tokenize.c,v 1.109 2005/12/06 12:53:00 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include <stdlib.h>

/*
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

363
364
365
366
367
368
369
344
345
346
347
348
349
350

351
352
353
354
355
356
357
358
359
360

361
362
363
364
365
366
367
368







-










-
+







  extern int sqlite3Parser(void*, int, Token, Parse*);

  db->flags &= ~SQLITE_Interrupt;
  pParse->rc = SQLITE_OK;
  i = 0;
  pEngine = sqlite3ParserAlloc((void*(*)(int))sqlite3MallocX);
  if( pEngine==0 ){
    sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
    return SQLITE_NOMEM;
  }
  assert( pParse->sLastToken.dyn==0 );
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
  assert( pParse->nVarExpr==0 );
  assert( pParse->nVarExprAlloc==0 );
  assert( pParse->apVarExpr==0 );
  pParse->zTail = pParse->zSql = zSql;
  while( sqlite3_malloc_failed==0 && zSql[i]!=0 ){
  while( sqlite3Tsd()->mallocFailed==0 && zSql[i]!=0 ){
    assert( i>=0 );
    pParse->sLastToken.z = &zSql[i];
    assert( pParse->sLastToken.dyn==0 );
    pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
    i += pParse->sLastToken.n;
    switch( tokenType ){
      case TK_SPACE:
403
404
405
406
407
408
409
410

411
412
413
414

415
416
417
418
419
420
421
422
402
403
404
405
406
407
408

409
410
411
412

413

414
415
416
417
418
419
420







-
+



-
+
-







    if( lastTokenParsed!=TK_SEMI ){
      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
      pParse->zTail = &zSql[i];
    }
    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  }
  sqlite3ParserFree(pEngine, sqlite3FreeX);
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc),
    sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
                    (char*)0);
  }
  if( pParse->zErrMsg ){
    if( pzErrMsg && *pzErrMsg==0 ){
      *pzErrMsg = pParse->zErrMsg;
    }else{
      sqliteFree(pParse->zErrMsg);
    }
Changes to src/trigger.c.
76
77
78
79
80
81
82
83

84
85
86
87
88
89
90

91
92
93
94
95
96
97
76
77
78
79
80
81
82

83
84
85
86
87
88
89

90
91
92
93
94
95
96
97







-
+






-
+







  }

  /* If the trigger name was unqualified, and the table is a temp table,
  ** then set iDb to 1 to create the trigger in the temporary database.
  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  ** exist, the error is caught by the block below.
  */
  if( !pTableName || sqlite3_malloc_failed ) goto trigger_cleanup;
  if( !pTableName || sqlite3Tsd()->mallocFailed ) goto trigger_cleanup;
  pTab = sqlite3SrcListLookup(pParse, pTableName);
  if( pName2->n==0 && pTab && pTab->iDb==1 ){
    iDb = 1;
  }

  /* Ensure the table name matches database name and that the table exists */
  if( sqlite3_malloc_failed ) goto trigger_cleanup;
  if( sqlite3Tsd()->mallocFailed ) goto trigger_cleanup;
  assert( pTableName->nSrc==1 );
  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
      sqlite3FixSrcList(&sFix, pTableName) ){
    goto trigger_cleanup;
  }
  pTab = sqlite3SrcListLookup(pParse, pTableName);
  if( !pTab ){
246
247
248
249
250
251
252
253

254
255
256
257
258
259
260
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260







-
+








  if( db->init.busy ){
    Table *pTab;
    Trigger *pDel;
    pDel = sqlite3HashInsert(&db->aDb[pTrig->iDb].trigHash, 
                     pTrig->name, strlen(pTrig->name)+1, pTrig);
    if( pDel ){
      assert( sqlite3_malloc_failed && pDel==pTrig );
      assert( sqlite3Tsd()->mallocFailed && pDel==pTrig );
      goto triggerfinish_cleanup;
    }
    pTab = sqlite3LocateTable(pParse,pTrig->table,db->aDb[pTrig->iTabDb].zName);
    assert( pTab!=0 );
    pTrig->pNext = pTab->pTrigger;
    pTab->pTrigger = pTrig;
    pTrig = 0;
426
427
428
429
430
431
432
433

434
435
436
437
438
439
440
426
427
428
429
430
431
432

433
434
435
436
437
438
439
440







-
+







  Trigger *pTrigger = 0;
  int i;
  const char *zDb;
  const char *zName;
  int nName;
  sqlite3 *db = pParse->db;

  if( sqlite3_malloc_failed ) goto drop_trigger_cleanup;
  if( sqlite3Tsd()->mallocFailed ) goto drop_trigger_cleanup;
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    goto drop_trigger_cleanup;
  }

  assert( pName->nSrc==1 );
  zDb = pName->a[0].zDatabase;
  zName = pName->a[0].zName;
Changes to src/update.c.
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle UPDATE statements.
**
** $Id: update.c,v 1.113 2005/11/14 22:29:05 drh Exp $
** $Id: update.c,v 1.114 2005/12/06 12:53:01 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** The most recently coded instruction was an OP_Column to retrieve the
** i-th column of table pTab. This routine sets the P3 parameter of the 
** OP_Column to the default value, if any.
95
96
97
98
99
100
101
102

103
104
105
106
107
108
109
95
96
97
98
99
100
101

102
103
104
105
106
107
108
109







-
+







  int triggers_exist = 0;      /* True if any row triggers exist */
#endif

  int newIdx      = -1;  /* index of trigger "new" temp table       */
  int oldIdx      = -1;  /* index of trigger "old" temp table       */

  sContext.pParse = 0;
  if( pParse->nErr || sqlite3_malloc_failed ) goto update_cleanup;
  if( pParse->nErr || sqlite3Tsd()->mallocFailed ) goto update_cleanup;
  db = pParse->db;
  assert( pTabList->nSrc==1 );

  /* Locate the table which we want to update. 
  */
  pTab = sqlite3SrcListLookup(pParse, pTabList);
  if( pTab==0 ) goto update_cleanup;
Changes to src/util.c.
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+







**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: util.c,v 1.148 2005/10/20 07:28:19 drh Exp $
** $Id: util.c,v 1.149 2005/12/06 12:53:01 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>
#include <ctype.h>

#if SQLITE_MEMDEBUG>2 && defined(__GLIBC__)
#include <execinfo.h>
33
34
35
36
37
38
39

40
41
42
43
44


45
46
47
48
49
50
51
33
34
35
36
37
38
39
40
41
42
43
44

45
46
47
48
49
50
51
52
53







+




-
+
+







  }
  fprintf(stderr, "\n");
}
#else
#define print_stack_trace()
#endif

#if 0
/*
** If malloc() ever fails, this global variable gets set to 1.
** This causes the library to abort and never again function.
*/
int sqlite3_malloc_failed = 0;
int sqlite3Tsd()->mallocFailed = 0;
#endif

/*
** If SQLITE_MEMDEBUG is defined, then use versions of malloc() and
** free() that track memory usage and check for buffer overruns.
*/
#ifdef SQLITE_MEMDEBUG

77
78
79
80
81
82
83
84

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103













104
105
106
107
108
109
110
111
112
113
114
115

116
117
118
119
120
121
122
79
80
81
82
83
84
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129

130
131
132
133
134
135
136
137







-
+



















+
+
+
+
+
+
+
+
+
+
+
+
+











-
+







** Check for a simulated memory allocation failure.  Return true if
** the failure should be simulated.  Return false to proceed as normal.
*/
static int simulatedMallocFailure(int n, char *zFile, int line){
  if( sqlite3_iMallocFail>=0 ){
    sqlite3_iMallocFail--;
    if( sqlite3_iMallocFail==0 ){
      sqlite3_malloc_failed++;
      sqlite3Tsd()->mallocFailed++;
#if SQLITE_MEMDEBUG>1
      fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
              n, zFile,line);
#endif
      sqlite3_iMallocFail = sqlite3_iMallocReset;
      return 1;
    }
  }
  return 0;
}

/*
** Allocate new memory and set it to zero.  Return NULL if
** no memory is available.
*/
void *sqlite3Malloc_(int n, int bZero, char *zFile, int line){
  void *p;
  int *pi;
  int i, k;

  /* Any malloc() calls between a malloc() failure and clearing the
  ** mallocFailed flag (done before returning control to the user)
  ** automatically fail. Although this restriction may have to be relaxed in
  ** the future, for now it makes the system easier to test.
  **
  ** TODO: This will eventually be done as part of the same wrapper that may
  ** call sqlite3_release_memory(). Above the sqlite3OsMalloc() level.
  */
  if( sqlite3Tsd()->mallocFailed ){
    return 0;
  }

  if( n==0 ){
    return 0;
  }
  if( simulatedMallocFailure(n, zFile, line) ){
    return 0;
  }
  sqlite3_memUsed += n;
  if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
  k = (n+sizeof(int)-1)/sizeof(int);
  pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
  if( pi==0 ){
    if( n>0 ) sqlite3_malloc_failed++;
    if( n>0 ) sqlite3Tsd()->mallocFailed++;
    return 0;
  }
  sqlite3_nMalloc++;
  for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  pi[N_GUARD] = n;
  for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
  p = &pi[N_GUARD+1];
224
225
226
227
228
229
230
231

232
233
234
235
236
237
238
239
240
241
242
243
244
245

246
247
248
249
250
251
252
253







-
+







              (int)oldP);
      return 0;
    }
  }
  k = (n + sizeof(int) - 1)/sizeof(int);
  pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
  if( pi==0 ){
    if( n>0 ) sqlite3_malloc_failed++;
    if( n>0 ) sqlite3Tsd()->mallocFailed++;
    return 0;
  }
  for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  pi[N_GUARD] = n;
  sqlite3_memUsed += n;
  if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
  for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
290
291
292
293
294
295
296
297

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

313
314
315
316
317
318
319
305
306
307
308
309
310
311

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326

327
328
329
330
331
332
333
334







-
+














-
+







** Allocate new memory and set it to zero.  Return NULL if
** no memory is available.  See also sqliteMallocRaw().
*/
void *sqlite3Malloc(int n){
  void *p;
  if( n==0 ) return 0;
  if( (p = malloc(n))==0 ){
    if( n>0 ) sqlite3_malloc_failed++;
    if( n>0 ) sqlite3Tsd()->mallocFailed++;
  }else{
    memset(p, 0, n);
  }
  return p;
}

/*
** Allocate new memory but do not set it to zero.  Return NULL if
** no memory is available.  See also sqliteMalloc().
*/
void *sqlite3MallocRaw(int n){
  void *p;
  if( n==0 ) return 0;
  if( (p = malloc(n))==0 ){
    if( n>0 ) sqlite3_malloc_failed++;
    if( n>0 ) sqlite3Tsd()->mallocFailed++;
  }
  return p;
}

/*
** Free memory previously obtained from sqliteMalloc()
*/
335
336
337
338
339
340
341
342

343
344
345
346
347
348
349
350
351
352
353
354
355
356

357
358
359
360
361
362
363
364







-
+







  }
  if( n==0 ){
    sqliteFree(p);
    return 0;
  }
  p2 = realloc(p, n);
  if( p2==0 ){
    if( n>0 ) sqlite3_malloc_failed++;
    if( n>0 ) sqlite3Tsd()->mallocFailed++;
  }
  return p2;
}

/*
** Make a copy of a string in memory obtained from sqliteMalloc()
*/
1003
1004
1005
1006
1007
1008
1009















1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
    assert( sizeof(p)==sizeof(v2) );
    v2 = (u32)v;
    p = *(void**)&v2;
  }
  return p;
}
#endif

/*
** Return a pointer to the SqliteTsd associated with the calling thread.
*/
static SqliteTsd tsd = { 0 };
SqliteTsd *sqlite3Tsd(){
  return &tsd;
}

void sqlite3ClearMallocFailed(){
  sqlite3Tsd()->mallocFailed = 0;
}



Changes to src/vacuum.c.
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+







**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
**
** $Id: vacuum.c,v 1.49 2005/11/30 03:20:32 drh Exp $
** $Id: vacuum.c,v 1.50 2005/12/06 12:53:01 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"

#ifndef SQLITE_OMIT_VACUUM
/*
** Generate a random name of 20 character in length.
166
167
168
169
170
171
172
173




174
175
176
177
178
179
180
166
167
168
169
170
171
172

173
174
175
176
177
178
179
180
181
182
183







-
+
+
+
+







  zSql = 0;
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
  pTemp = db->aDb[db->nDb-1].pBt;
  sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
     sqlite3BtreeGetReserve(pMain));
  assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
  execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
  rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
  if( rc!=SQLITE_OK ){
    goto end_of_vacuum;
  }

#ifndef SQLITE_OMIT_AUTOVACUUM
  sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain));
#endif

  /* Begin a transaction */
  rc = execSql(db, "BEGIN EXCLUSIVE;");
280
281
282
283
284
285
286








287
288
289
290
291
292
293
294
295
296
297








298
299
300




301
302
303
304
305
306
307
308
309
310
311
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331







+
+
+
+
+
+
+
+











+
+
+
+
+
+
+
+
-
-
-
+
+
+
+











    if( rc!=SQLITE_OK ) goto end_of_vacuum;
    rc = sqlite3BtreeCommit(pTemp);
    if( rc!=SQLITE_OK ) goto end_of_vacuum;
    rc = sqlite3BtreeCommit(pMain);
  }

end_of_vacuum:
  /* If one of the execSql() calls above returned SQLITE_NOMEM, then the
  ** mallocFailed flag will be clear (because execSql() calls sqlite3_exec()).
  ** Fix this so the flag and return code match.
  */
  if( rc==SQLITE_NOMEM ){
    sqlite3Tsd()->mallocFailed = 1;
  }

  /* Restore the original value of db->flags */
  db->flags = saved_flags;

  /* Currently there is an SQL level transaction open on the vacuum
  ** database. No locks are held on any other files (since the main file
  ** was committed at the btree level). So it safe to end the transaction
  ** by manually setting the autoCommit flag to true and detaching the
  ** vacuum database. The vacuum_db journal file is deleted when the pager
  ** is closed by the DETACH.
  */
  db->autoCommit = 1;

  /* TODO: We need to detach vacuum_db (if it is attached) even if malloc()
  ** failed. Right now trying to do so will cause an assert() to fail in **
  **_prepare() (because it should be impossible to call _prepare() with the **
  ** mallocFailed flag set). So really, we need to be able to detach a database
  ** without calling malloc(). Which seems plausible.
  */
  if( !sqlite3Tsd()->mallocFailed ){
  rc2 = execSql(db, "DETACH vacuum_db;");
  if( rc==SQLITE_OK ){
    rc = rc2;
    rc2 = execSql(db, "DETACH vacuum_db;");
    if( rc==SQLITE_OK ){
      rc = rc2;
    }
  }
  if( zTemp ){
    sqlite3Os.xDelete(zTemp);
    sqliteFree(zTemp);
  }
  sqliteFree( zSql );
  sqlite3ResetInternalSchema(db, 0);
#endif

  return rc;
}
Changes to src/vdbe.c.
39
40
41
42
43
44
45
46

47
48
49
50
51
52
53
39
40
41
42
43
44
45

46
47
48
49
50
51
52
53







-
+







**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.501 2005/11/30 03:20:32 drh Exp $
** $Id: vdbe.c,v 1.502 2005/12/06 12:53:01 danielk1977 Exp $
*/
#include "sqliteInt.h"
#include "os.h"
#include <ctype.h>
#include "vdbeInt.h"

/*
390
391
392
393
394
395
396
397

398
399
400
401
402
403
404
405
406
407
408

409
410
411
412
413
414
415
390
391
392
393
394
395
396

397
398
399
400
401
402
403
404
405
406
407

408
409
410
411
412
413
414
415







-
+










-
+








  if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
  assert( db->magic==SQLITE_MAGIC_BUSY );
  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  p->rc = SQLITE_OK;
  assert( p->explain==0 );
  pTos = p->pTos;
  if( sqlite3_malloc_failed ) goto no_mem;
  if( sqlite3Tsd()->mallocFailed ) goto no_mem;
  if( p->popStack ){
    popStack(&pTos, p->popStack);
    p->popStack = 0;
  }
  p->resOnStack = 0;
  db->busyHandler.nBusy = 0;
  CHECK_FOR_INTERRUPT;
  for(pc=p->pc; rc==SQLITE_OK; pc++){
    assert( pc>=0 && pc<p->nOp );
    assert( pTos<=&p->aStack[pc] );
    if( sqlite3_malloc_failed ) goto no_mem;
    if( sqlite3Tsd()->mallocFailed ) goto no_mem;
#ifdef VDBE_PROFILE
    origPc = pc;
    start = hwtime();
#endif
    pOp = &p->aOp[pc];

    /* Only allow tracing if SQLITE_DEBUG is defined.
1131
1132
1133
1134
1135
1136
1137
1138

1139
1140
1141
1142
1143
1144
1145
1131
1132
1133
1134
1135
1136
1137

1138
1139
1140
1141
1142
1143
1144
1145







-
+







    assert( pOp[-1].p3type==P3_COLLSEQ );
    assert( pOp[-1].opcode==OP_CollSeq );
    ctx.pColl = (CollSeq *)pOp[-1].p3;
  }
  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  if( sqlite3_malloc_failed ) goto no_mem;
  if( sqlite3Tsd()->mallocFailed ) goto no_mem;
  popStack(&pTos, n);

  /* If any auxilary data functions have been called by this user function,
  ** immediately call the destructor for any non-static values.
  */
  if( ctx.pVdbeFunc ){
    sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
3109
3110
3111
3112
3113
3114
3115
3116




3117
3118
3119
3120
3121
3122
3123
3109
3110
3111
3112
3113
3114
3115

3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126







-
+
+
+
+







#   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
#endif

    if( !pC->useRandomRowid ){
      if( pC->nextRowidValid ){
        v = pC->nextRowid;
      }else{
        rx = sqlite3BtreeLast(pC->pCursor, &res);
        rc = sqlite3BtreeLast(pC->pCursor, &res);
        if( rc!=SQLITE_OK ){
          goto abort_due_to_error;
        }
        if( res ){
          v = 1;
        }else{
          sqlite3BtreeKeySize(pC->pCursor, &v);
          v = keyToInt(v);
          if( v==MAX_ROWID ){
            pC->useRandomRowid = 1;
3889
3890
3891
3892
3893
3894
3895

3896
3897
3898




3899
3900
3901
3902
3903
3904
3905
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913







+



+
+
+
+







  zSql = sqlite3MPrintf(
     "SELECT name, rootpage, sql, %d FROM '%q'.%s WHERE %s",
     pOp->p1, db->aDb[iDb].zName, zMaster, pOp->p3);
  if( zSql==0 ) goto no_mem;
  sqlite3SafetyOff(db);
  assert( db->init.busy==0 );
  db->init.busy = 1;
  assert(0==sqlite3Tsd()->mallocFailed);
  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  db->init.busy = 0;
  sqlite3SafetyOn(db);
  if( rc==SQLITE_NOMEM ){
    sqlite3Tsd()->mallocFailed = 1;
    goto no_mem;
  }
  sqliteFree(zSql);
  break;  
}

#ifndef SQLITE_OMIT_ANALYZE
/* Opcode: LoadAnalysis P1 * *
**
4429
4430
4431
4432
4433
4434
4435
4436

4437
4438
4439
4440
4441
4442
4443
4437
4438
4439
4440
4441
4442
4443

4444
4445
4446
4447
4448
4449
4450
4451







-
+







  /* Fall thru into abort_due_to_error */

  /* Jump to here for any other kind of fatal error.  The "rc" variable
  ** should hold the error number.
  */
abort_due_to_error:
  if( p->zErrMsg==0 ){
    if( sqlite3_malloc_failed ) rc = SQLITE_NOMEM;
    if( sqlite3Tsd()->mallocFailed ) rc = SQLITE_NOMEM;
    sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
  }
  goto vdbe_halt;

  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  ** flag.
  */
Changes to src/vdbeapi.c.
151
152
153
154
155
156
157


158
159
160
161
162
163
164
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166







+
+







** Execute the statement pStmt, either until a row of data is ready, the
** statement is completely executed or an error occurs.
*/
int sqlite3_step(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe*)pStmt;
  sqlite3 *db;
  int rc;

  assert(!sqlite3Tsd()->mallocFailed);

  if( p==0 || p->magic!=VDBE_MAGIC_RUN ){
    return SQLITE_MISUSE;
  }
  if( p->aborted ){
    return SQLITE_ABORT;
  }
235
236
237
238
239
240
241

242
243
244
245
246
247
248
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251







+







    assert( p->aOp[p->nOp-1].p3!=0 );
    assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
    db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
  }
#endif

  sqlite3Error(p->db, rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  sqlite3ClearMallocFailed();
  return rc;
}

/*
** Extract the user data from a sqlite3_context structure and return a
** pointer to it.
*/
Changes to src/vdbeaux.c.
98
99
100
101
102
103
104
105

106
107
108
109
110
111
112
98
99
100
101
102
103
104

105
106
107
108
109
110
111
112







-
+







  int i;
  VdbeOp *pOp;

  i = p->nOp;
  p->nOp++;
  assert( p->magic==VDBE_MAGIC_INIT );
  resizeOpArray(p, i+1);
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return 0;
  }
  pOp = &p->aOp[i];
  pOp->opcode = op;
  pOp->p1 = p1;
  pOp->p2 = p2;
  pOp->p3 = 0;
297
298
299
300
301
302
303
304

305
306
307
308
309
310
311
297
298
299
300
301
302
303

304
305
306
307
308
309
310
311







-
+







** Add a whole list of operations to the operation stack.  Return the
** address of the first operation added.
*/
int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  int addr;
  assert( p->magic==VDBE_MAGIC_INIT );
  resizeOpArray(p, p->nOp + nOp);
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    return 0;
  }
  addr = p->nOp;
  if( nOp>0 ){
    int i;
    VdbeOpList const *pIn = aOp;
    for(i=0; i<nOp; i++, pIn++){
412
413
414
415
416
417
418

419


420
421
422
423
424
425
426
412
413
414
415
416
417
418
419

420
421
422
423
424
425
426
427
428







+
-
+
+







**
** If addr<0 then change P3 on the most recently inserted instruction.
*/
void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
  Op *pOp;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( p==0 || p->aOp==0 ){
    if (n != P3_KEYINFO) {
    freeP3(n, (void*)*(char**)&zP3);
      freeP3(n, (void*)*(char**)&zP3);
    }
    return;
  }
  if( addr<0 || addr>=p->nOp ){
    addr = p->nOp - 1;
    if( addr<0 ) return;
  }
  pOp = &p->aOp[addr];
730
731
732
733
734
735
736
737

738
739
740
741
742
743
744
732
733
734
735
736
737
738

739
740
741
742
743
744
745
746







-
+







        nStack*sizeof(p->aStack[0])    /* aStack */
      + nArg*sizeof(Mem*)              /* apArg */
      + nVar*sizeof(Mem)               /* aVar */
      + nVar*sizeof(char*)             /* azVar */
      + nMem*sizeof(Mem)               /* aMem */
      + nCursor*sizeof(Cursor*)        /* apCsr */
    );
    if( !sqlite3_malloc_failed ){
    if( !sqlite3Tsd()->mallocFailed ){
      p->aMem = &p->aStack[nStack];
      p->nMem = nMem;
      p->aVar = &p->aMem[nMem];
      p->nVar = nVar;
      p->okVar = 0;
      p->apArg = (Mem**)&p->aVar[nVar];
      p->azVar = (char**)&p->apArg[nArg];
880
881
882
883
884
885
886
887

888
889
890
891
892
893
894
882
883
884
885
886
887
888

889
890
891
892
893
894
895
896







-
+







** the string is freed using sqliteFree() when the vdbe is finished with
** it. Otherwise, N bytes of zName are copied.
*/
int sqlite3VdbeSetColName(Vdbe *p, int idx, const char *zName, int N){
  int rc;
  Mem *pColName;
  assert( idx<(2*p->nResColumn) );
  if( sqlite3_malloc_failed ) return SQLITE_NOMEM;
  if( sqlite3Tsd()->mallocFailed ) return SQLITE_NOMEM;
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx]);
  if( N==P3_DYNAMIC || N==P3_STATIC ){
    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
  }else{
    rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
  }
1143
1144
1145
1146
1147
1148
1149




1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160

1161

1162
1163
1164
1165
1166
1167
1168
1169
1170
1171


1172
1173
1174
1175
1176





































1177
1178
1179
1180
1181
1182
1183
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167

1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229







+
+
+
+











+
-
+










+
+





+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
int sqlite3VdbeHalt(Vdbe *p){
  sqlite3 *db = p->db;
  int i;
  int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */

  if( sqlite3Tsd()->mallocFailed ){
    p->rc = SQLITE_NOMEM;
  }

  if( p->magic!=VDBE_MAGIC_RUN ){
    /* Already halted.  Nothing to do. */
    assert( p->magic==VDBE_MAGIC_HALT );
    return SQLITE_OK;
  }
  closeAllCursors(p);
  checkActiveVdbeCnt(db);
  if( p->pc<0 ){
    /* No commit or rollback needed if the program never started */
  }else if( db->autoCommit && db->activeVdbeCnt==1 ){

    if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && p->rc!=SQLITE_NOMEM)){
      /* The auto-commit flag is true, there are no other active queries
      ** using this handle and the vdbe program was successful or hit an
      ** 'OR FAIL' constraint. This means a commit is required.
      */
      int rc = vdbeCommit(db);
      if( rc==SQLITE_BUSY ){
        return SQLITE_BUSY;
      }else if( rc!=SQLITE_OK ){
        p->rc = rc;
        xFunc = sqlite3BtreeRollback;
      }else{
        sqlite3CommitInternalChanges(db);
      }
    }else{
      xFunc = sqlite3BtreeRollback;
    }
  }else{

    if( p->rc==SQLITE_NOMEM ){
      /* This loop does static analysis of the query to see which of the
      ** following three categories it falls into:
      **
      **     Read-only
      **     Query with statement journal          -> rollback statement
      **     Query without statement journal       -> rollback transaction
      **
      ** We could do something more elegant than this static analysis (i.e.
      ** store the type of query as part of the compliation phase), but 
      ** handling malloc() failure is a fairly obscure edge case so this is
      ** probably easier.
      **
      ** Todo: This means we always override the p->errorAction value for a
      ** malloc() failure. Is there any other choice here though?
      */
      int isReadOnly = 1;
      int isStatement = 0;
      assert(p->aOp || p->nOp==0);
      for(i=0; i<p->nOp; i++){ 
        switch( p->aOp[i].opcode ){
          case OP_Transaction:
            isReadOnly = 0;
            break;
          case OP_Statement:
            isStatement = 1;
            break;
        }
      }
      if( (isReadOnly||isStatement) && p->errorAction!=OE_Rollback ){
        p->errorAction = OE_Abort;
      }else{ 
        p->errorAction = OE_Rollback;
      }
    }

    if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
      xFunc = sqlite3BtreeCommitStmt;
    }else if( p->errorAction==OE_Abort ){
      xFunc = sqlite3BtreeRollbackStmt;
    }else{
      xFunc = sqlite3BtreeRollback;
      db->autoCommit = 1;
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215




1216

1217
1218
1219
1220
1221
1222
1223
1252
1253
1254
1255
1256
1257
1258



1259
1260
1261
1262

1263
1264
1265
1266
1267
1268
1269
1270







-
-
-
+
+
+
+
-
+







    }else{
      sqlite3VdbeSetChanges(db, 0);
    }
    p->nChange = 0;
  }

  /* Rollback or commit any schema changes that occurred. */
  if( p->rc!=SQLITE_OK ){
    sqlite3RollbackInternalChanges(db);
  }else if( db->flags & SQLITE_InternChanges ){
  if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
    sqlite3ResetInternalSchema(db, 0);
    if( xFunc!=sqlite3BtreeRollback ){
      db->flags = (db->flags | SQLITE_InternChanges);
    sqlite3CommitInternalChanges(db);
    }
  }

  /* We have successfully halted and closed the VM.  Record this fact. */
  if( p->pc>=0 ){
    db->activeVdbeCnt--;
  }
  p->magic = VDBE_MAGIC_HALT;
1274
1275
1276
1277
1278
1279
1280
1281

1282
1283
1284
1285
1286
1287
1288
1321
1322
1323
1324
1325
1326
1327

1328
1329
1330
1331
1332
1333
1334
1335







-
+








  /* Reclaim all memory used by the VDBE
  */
  Cleanup(p);

  /* Save profiling information from this VDBE run.
  */
  assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || sqlite3_malloc_failed==1 );
  assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
#ifdef VDBE_PROFILE
  {
    FILE *out = fopen("vdbe_profile.out", "a");
    if( out ){
      int i;
      fprintf(out, "---- ");
      for(i=0; i<p->nOp; i++){
Changes to src/where.c.
12
13
14
15
16
17
18
19

20
21
22
23
24
25
26
12
13
14
15
16
17
18

19
20
21
22
23
24
25
26







-
+







** This module contains C code that generates VDBE code used to process
** the WHERE clause of SQL statements.  This module is reponsible for
** generating the code that loops through a table looking for applicable
** rows.  Indices are selected and used to speed the search when doing
** so is applicable.  Because this module is responsible for selecting
** indices, you might also think of this module as the "query optimizer".
**
** $Id: where.c,v 1.185 2005/11/26 14:24:41 drh Exp $
** $Id: where.c,v 1.186 2005/12/06 12:53:01 danielk1977 Exp $
*/
#include "sqliteInt.h"

/*
** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
*/
#define BMS  (sizeof(Bitmask)*8)
563
564
565
566
567
568
569
570

571
572
573
574
575
576
577
563
564
565
566
567
568
569

570
571
572
573
574
575
576
577







-
+







  WhereTerm *pTerm = &pWC->a[idxTerm];
  Expr *pExpr = pTerm->pExpr;
  Bitmask prereqLeft;
  Bitmask prereqAll;
  int nPattern;
  int isComplete;

  if( sqlite3_malloc_failed ) return;
  if( sqlite3Tsd()->mallocFailed ) return;
  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  if( pExpr->op==TK_IN ){
    assert( pExpr->pRight==0 );
    pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
                          | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
  }else{
    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1428
1429
1430
1431
1432
1433
1434
1435

1436
1437
1438
1439
1440
1441
1442
1428
1429
1430
1431
1432
1433
1434

1435
1436
1437
1438
1439
1440
1441
1442







-
+







  whereClauseInit(&wc, pParse);
  whereSplit(&wc, pWhere, TK_AND);
    
  /* Allocate and initialize the WhereInfo structure that will become the
  ** return value.
  */
  pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    goto whereBeginNoMem;
  }
  pWInfo->pParse = pParse;
  pWInfo->pTabList = pTabList;
  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);

  /* Special case: a WHERE clause that is constant.  Evaluate the
1452
1453
1454
1455
1456
1457
1458
1459

1460
1461
1462
1463
1464
1465
1466
1452
1453
1454
1455
1456
1457
1458

1459
1460
1461
1462
1463
1464
1465
1466







-
+







  ** want to analyze these virtual terms, so start analyzing at the end
  ** and work forward so that the added virtual terms are never processed.
  */
  for(i=0; i<pTabList->nSrc; i++){
    createMask(&maskSet, pTabList->a[i].iCursor);
  }
  exprAnalyzeAll(pTabList, &maskSet, &wc);
  if( sqlite3_malloc_failed ){
  if( sqlite3Tsd()->mallocFailed ){
    goto whereBeginNoMem;
  }

  /* Chose the best index to use for each table in the FROM clause.
  **
  ** This loop fills in the following fields:
  **
Changes to test/malloc.test.
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
25

26
27
28
29
30
31
32
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24

25
26
27
28
29
30
31
32







-
+







-
+







#***********************************************************************
# This file attempts to check the library in an out-of-memory situation.
# When compiled with -DSQLITE_DEBUG=1, the SQLite library accepts a special
# command (sqlite_malloc_fail N) which causes the N-th malloc to fail.  This
# special feature is used to see what happens in the library if a malloc
# were to really fail due to an out-of-memory situation.
#
# $Id: malloc.test,v 1.24 2005/09/08 00:13:28 drh Exp $
# $Id: malloc.test,v 1.25 2005/12/06 12:53:01 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if memory debugging is turned on.
#
if {[info command sqlite_malloc_stat]==""} {
   puts "Skipping malloc tests: not compiled with -DSQLITE_DEBUG..."
   puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

# Usage: do_malloc_test <test number> <options...>
#
# The first argument, <test number>, is an integer used to name the
48
49
50
51
52
53
54

55
56
57
58

59
60



61
62
63
64
65
66
67
68


69
70
71
72
73
74
75



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
48
49
50
51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

93
94
95
96
97
98
99







+



-
+


+
+
+








+
+







+
+
+








-







# to the -tclbody switch, followed by the SQL commands in any argument
# passed to the -sqlbody switch are executed. Each iteration the
# Nth call to sqliteMalloc() is made to fail, where N is increased
# each time the loop runs starting from 1. When all commands execute
# successfully, the loop ends.
#
proc do_malloc_test {tn args} {
  array unset ::mallocopts 
  array set ::mallocopts $args

  set ::go 1
  for {set ::n 1} {$::go} {incr ::n} {
  for {set ::n 1} {$::go && $::n < 50000} {incr ::n} {
    do_test malloc-$tn.$::n {

      # Remove all traces of database files test.db and test2.db from the files
      # system. Then open (empty database) "test.db" with the handle [db].
      # 
      sqlite_malloc_fail 0
      catch {db close}
      catch {file delete -force test.db}
      catch {file delete -force test.db-journal}
      catch {file delete -force test2.db}
      catch {file delete -force test2.db-journal}
      set ::DB [sqlite3 db test.db]

      # Execute any -tclprep and -sqlprep scripts.
      #
      if {[info exists ::mallocopts(-tclprep)]} {
        eval $::mallocopts(-tclprep)
      }
      if {[info exists ::mallocopts(-sqlprep)]} {
        execsql $::mallocopts(-sqlprep)
      }

      # Now set the ${::n}th malloc() to fail and execute the -tclbody and
      # -sqlbody scripts.
      #
      sqlite_malloc_fail $::n
      set ::mallocbody {}
      if {[info exists ::mallocopts(-tclbody)]} {
        append ::mallocbody "$::mallocopts(-tclbody)\n"
      }
      if {[info exists ::mallocopts(-sqlbody)]} {
        append ::mallocbody "db eval {$::mallocopts(-sqlbody)}"
      }

      set v [catch $::mallocbody msg]

      set leftover [lindex [sqlite_malloc_stat] 2]
      if {$leftover>0} {
        if {$leftover>1} {puts "\nLeftover: $leftover\nReturn=$v  Message=$msg"}
        set ::go 0
        set v {1 1}
Changes to test/malloc2.test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21













-
+







# 2005 March 18
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file attempts to check that the library can recover from a malloc()
# failure when sqlite3_global_recover() is invoked.
#
# $Id: malloc2.test,v 1.3 2005/06/06 14:45:43 drh Exp $
# $Id: malloc2.test,v 1.4 2005/12/06 12:53:01 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Only run these tests if memory debugging is turned on.
#
if {[info command sqlite_malloc_stat]==""} {
83
84
85
86
87
88
89




90
91
92
93


94





95
96
97
98
99
100
101
102
103
104








105
106
107
108
109
110
111
83
84
85
86
87
88
89
90
91
92
93
94
95
96

97
98
99
100
101
102
103
104
105









106
107
108
109
110
111
112
113
114
115
116
117
118
119
120







+
+
+
+



-
+
+

+
+
+
+
+

-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+







    if {[lindex [sqlite_malloc_stat] 2]>0} {
      sqlite_malloc_fail -1
      break
    }

    # Nothing should work now, because the allocator should refuse to
    # allocate any memory.
    #
    # Update: SQLite now automatically recovers from a malloc() failure.
    # So the statement in the test below would work. 
if 0 {
    do_test malloc2-$tn.$::n.3 {
      catchsql {SELECT 'nothing should work'}
    } {1 {out of memory}}

}

    # Recover from the malloc failure.
    #
    # Update: The new malloc() failure handling means that a transaction may
    # still be active even if a malloc() has failed. But when these tests were
    # written this was not the case. So do a manual ROLLBACK here so that the
    # tests pass.
    do_test malloc2-$tn.$::n.4 {
      if 0 {
        db close
        sqlite_malloc_fail -1
        set ::DB [sqlite3 db test.db]
        set dummy SQLITE_OK
      } else {
        sqlite3_global_recover
      }
    } {SQLITE_OK}
      sqlite3_global_recover
      catch {
        execsql {
          ROLLBACK;
        }
      }
      expr 0
    } {0}

    # Checksum the database.
    do_test malloc2-$tn.$::n.5 {
      cksum db
    } $sum

    integrity_check malloc2-$tn.$::n.6
260
261
262
263
264
265
266




267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

















284
285
286
287
288
289
290
291
292
293
294











295
296
297
298
299
300
301
302
303
304
305











306
307
308
309




310
311
312
313
314
315
316
317
318









319
320
321
322
323
324
325
326








327
328
329
330
331
332
333
334
335
336
337











338
339
340




341
342
269
270
271
272
273
274
275
276
277
278
279

















280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296











297
298
299
300
301
302
303
304
305
306
307











308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326









327
328
329
330
331
332
333
334
335








336
337
338
339
340
341
342
343











344
345
346
347
348
349
350
351
352
353
354



355
356
357
358

359







+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+




+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
-

  sqlite db1 test.db
  db1 close
} {}

########################################################################
# Check that if a statement is active sqlite3_global_recover doesn't reset
# the sqlite3_malloc_failed variable.
#
# Update: There is now no sqlite3_malloc_failed variable, so these tests 
# are not run.
#
do_test malloc2-6.1 {
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM def} -1 DUMMY]
  sqlite3_step $::STMT
} {SQLITE_ROW}
do_test malloc2-6.2 {
  sqlite3 db1 test.db
  sqlite_malloc_fail 100
  catchsql {
    SELECT * FROM def;
  } db1
} {1 {out of memory}}
do_test malloc2-6.3 {
  sqlite3_global_recover
} {SQLITE_BUSY}
do_test malloc2-6.4 {
  catchsql {
    SELECT 'hello';
# do_test malloc2-6.1 {
#   set ::STMT [sqlite3_prepare $::DB {SELECT * FROM def} -1 DUMMY]
#   sqlite3_step $::STMT
# } {SQLITE_ROW}
# do_test malloc2-6.2 {
#   sqlite3 db1 test.db
#   sqlite_malloc_fail 100
#   catchsql {
#     SELECT * FROM def;
#   } db1
# } {1 {out of memory}}
# do_test malloc2-6.3 {
#   sqlite3_global_recover
# } {SQLITE_BUSY}
# do_test malloc2-6.4 {
#   catchsql {
#     SELECT 'hello';
  }
} {1 {out of memory}}
do_test malloc2-6.5 {
  sqlite3_reset $::STMT
} {SQLITE_OK}
do_test malloc2-6.6 {
  sqlite3_global_recover
} {SQLITE_OK}
do_test malloc2-6.7 {
  catchsql {
    SELECT 'hello';
#   }
# } {1 {out of memory}}
# do_test malloc2-6.5 {
#   sqlite3_reset $::STMT
# } {SQLITE_OK}
# do_test malloc2-6.6 {
#   sqlite3_global_recover
# } {SQLITE_OK}
# do_test malloc2-6.7 {
#   catchsql {
#     SELECT 'hello';
  }
} {0 hello}
do_test malloc2-6.8 {
  sqlite3_step $::STMT
} {SQLITE_ERROR}
do_test malloc2-6.9 {
  sqlite3_finalize $::STMT
} {SQLITE_SCHEMA}
do_test malloc2-6.10 {
  db1 close
} {}
#   }
# } {0 hello}
# do_test malloc2-6.8 {
#   sqlite3_step $::STMT
# } {SQLITE_ERROR}
# do_test malloc2-6.9 {
#   sqlite3_finalize $::STMT
# } {SQLITE_SCHEMA}
# do_test malloc2-6.10 {
#   db1 close
# } {}

########################################################################
# Check that if an in-memory database is being used it is not possible
# to recover from a malloc() failure.
#
# Update: An in-memory database can now survive a malloc() failure, so these
# tests are not run.
#
ifcapable memorydb {
  do_test malloc2-7.1 {
    sqlite3 db1 :memory:
    list
  } {}
  do_test malloc2-7.2 {
    sqlite_malloc_fail 100
    catchsql {
      SELECT * FROM def;
# ifcapable memorydb {
#   do_test malloc2-7.1 {
#     sqlite3 db1 :memory:
#     list
#   } {}
#   do_test malloc2-7.2 {
#     sqlite_malloc_fail 100
#     catchsql {
#       SELECT * FROM def;
    } 
  } {1 {out of memory}}
  do_test malloc2-7.3 {
    sqlite3_global_recover
  } {SQLITE_ERROR}
  do_test malloc2-7.4 {
    catchsql {
      SELECT 'hello';
#     } 
#   } {1 {out of memory}}
#   do_test malloc2-7.3 {
#     sqlite3_global_recover
#   } {SQLITE_ERROR}
#   do_test malloc2-7.4 {
#     catchsql {
#       SELECT 'hello';
    }
  } {1 {out of memory}}
  do_test malloc2-7.5 {
    db1 close
  } {}
  do_test malloc2-7.6 {
    sqlite3_global_recover
  } {SQLITE_OK}
  do_test malloc2-7.7 {
    catchsql {
      SELECT 'hello';
#     }
#   } {1 {out of memory}}
#   do_test malloc2-7.5 {
#     db1 close
#   } {}
#   do_test malloc2-7.6 {
#     sqlite3_global_recover
#   } {SQLITE_OK}
#   do_test malloc2-7.7 {
#     catchsql {
#       SELECT 'hello';
    }
  } {0 hello}
}
#     }
#   } {0 hello}
# }


finish_test
Changes to test/schema.test.
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


32
33
34
35
36
37
38

39
40
41
42
43
44
45







-
+















-
-







-







#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file tests the various conditions under which an SQLITE_SCHEMA
# error should be returned.
#
# $Id: schema.test,v 1.4 2005/01/29 01:54:18 danielk1977 Exp $
# $Id: schema.test,v 1.5 2005/12/06 12:53:01 danielk1977 Exp $

#---------------------------------------------------------------------
# When any of the following types of SQL statements or actions are 
# executed, all pre-compiled statements are invalidated. An attempt
# to execute an invalidated statement always returns SQLITE_SCHEMA.
#
# CREATE/DROP TABLE...................................schema-1.*
# CREATE/DROP VIEW....................................schema-2.*
# CREATE/DROP TRIGGER.................................schema-3.*
# CREATE/DROP INDEX...................................schema-4.*
# DETACH..............................................schema-5.*
# Deleting a user-function............................schema-6.*
# Deleting a collation sequence.......................schema-7.*
# Setting or changing the authorization function......schema-8.*
#
# Note: Test cases schema-6.* are missing right now.
#
# Test cases schema-9.* and schema-10.* test some specific bugs
# that came up during development.
#
# Test cases schema-11.* test that it is impossible to delete or
# change a collation sequence or user-function while SQL statements
# are executing. Adding new collations or functions is allowed.
#
# Note: Test cases schema-11.* are also missing right now.

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test schema-1.1 {
  set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL]
  execsql {
Changes to tool/memleak3.tcl.
194
195
196
197
198
199
200

201
202
203
204
205
206
207
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208







+








  foreach key [array names ::memmap] {
    set stack [lindex $::memmap($key) 2]
    set bytes [lindex $::memmap($key) 0]
    lappend summarymap($stack) $bytes
  }

  set sorted [list]
  foreach stack [array names summarymap] {
    set allocs $summarymap($stack)
    set sum 0
    foreach a $allocs {
      incr sum $a
    }
    lappend sorted [list $sum $stack]