SQLite

Check-in [db818430e9]
Login

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

Overview
Comment:The malloc.test script now passes all tests with no errors. (CVS 4271)
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: db818430e9ea4ef4a4af575784009d5acae785a3
User & Date: drh 2007-08-22 20:18:22.000
Context
2007-08-22
22:04
All of the malloc test cases run. Still seeing failures in malloc4.test. (CVS 4272) (check-in: 205d0b881d user: drh tags: trunk)
20:18
The malloc.test script now passes all tests with no errors. (CVS 4271) (check-in: db818430e9 user: drh tags: trunk)
18:54
Fix a bug in the logic for journaling pages when the device sector-size is greater than the page size. (CVS 4270) (check-in: b6399dff13 user: danielk1977 tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to src/build.c.
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.437 2007/08/21 19:33:56 drh 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.







|







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.438 2007/08/22 20:18:22 drh 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.
86
87
88
89
90
91
92



93
94
95
96
97
98
99
      sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
  if( pParse->aTableLock ){
    p = &pParse->aTableLock[pParse->nTableLock++];
    p->iDb = iDb;
    p->iTab = iTab;
    p->isWriteLock = isWriteLock;
    p->zName = zName;



  }
}

/*
** Code an OP_TableLock instruction for each table locked by the
** statement (configured by calls to sqlite3TableLock()).
*/







>
>
>







86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
      sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
  if( pParse->aTableLock ){
    p = &pParse->aTableLock[pParse->nTableLock++];
    p->iDb = iDb;
    p->iTab = iTab;
    p->isWriteLock = isWriteLock;
    p->zName = zName;
  }else{
    pParse->nTableLock = 0;
    pParse->db->mallocFailed = 1;
  }
}

/*
** Code an OP_TableLock instruction for each table locked by the
** statement (configured by calls to sqlite3TableLock()).
*/
Changes to src/callback.c.
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.21 2007/08/21 19:33:56 drh Exp $
*/

#include "sqliteInt.h"

/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the database text encoding of name zName, length nName.







|







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.22 2007/08/22 20:18:22 drh Exp $
*/

#include "sqliteInt.h"

/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the database text encoding of name zName, length nName.
175
176
177
178
179
180
181
182
183

184
185
186
187
188
189
190
      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 || (db->mallocFailed && pDel==pColl) );
      if( pDel ){

        sqlite3_free(pDel);
        pColl = 0;
      }
    }
  }
  return pColl;
}







|
|
>







175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
      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==0 || pDel==pColl );
      if( pDel!=0 ){
        db->mallocFailed = 1;
        sqlite3_free(pDel);
        pColl = 0;
      }
    }
  }
  return pColl;
}
306
307
308
309
310
311
312

313
314
315
316
317
318
319
      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
    pBest->nArg = nArg;
    pBest->pNext = pFirst;
    pBest->iPrefEnc = enc;
    memcpy(pBest->zName, zName, nName);
    pBest->zName[nName] = 0;
    if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){

      sqlite3_free(pBest);
      return 0;
    }
  }

  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
    return pBest;







>







307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
    pBest->nArg = nArg;
    pBest->pNext = pFirst;
    pBest->iPrefEnc = enc;
    memcpy(pBest->zName, zName, nName);
    pBest->zName[nName] = 0;
    if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
      db->mallocFailed = 1;
      sqlite3_free(pBest);
      return 0;
    }
  }

  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
    return pBest;
Changes to src/expr.c.
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.307 2007/08/16 12:24:02 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** Return the 'affinity' of the expression pExpr if any.
**







|







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.308 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** Return the 'affinity' of the expression pExpr if any.
**
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
  int op,                 /* Expression opcode */
  Expr *pLeft,            /* Left operand */
  Expr *pRight,           /* Right operand */
  const Token *pToken     /* Argument token */
){
  Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
  if( pNew==0 ){
    sqlite3ExprDelete(pLeft);
    sqlite3ExprDelete(pRight);
    pParse->db->mallocFailed = 1;
  }
  return pNew;
}

/*
** When doing a nested parse, you can include terms in an expression







<
<







271
272
273
274
275
276
277


278
279
280
281
282
283
284
  int op,                 /* Expression opcode */
  Expr *pLeft,            /* Left operand */
  Expr *pRight,           /* Right operand */
  const Token *pToken     /* Argument token */
){
  Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
  if( pNew==0 ){


    pParse->db->mallocFailed = 1;
  }
  return pNew;
}

/*
** When doing a nested parse, you can include terms in an expression
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
** 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( 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;
    }







|







333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
** 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( pExpr && 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;
    }
Changes to src/legacy.c.
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.20 2007/08/21 10:44:16 drh Exp $
*/

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

/*
** Execute SQL code.  Return one of the SQLITE_ success/failure







|







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.21 2007/08/22 20:18:22 drh Exp $
*/

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

/*
** Execute SQL code.  Return one of the SQLITE_ success/failure
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    azCols = 0;
  }

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

  rc = sqlite3ApiExit(0, rc);
  if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
    int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
    *pzErrMsg = sqlite3_malloc(nErrMsg);
    if( *pzErrMsg ){
      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  assert( (rc&db->errMask)==rc );
  return rc;
}







|













111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    azCols = 0;
  }

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

  rc = sqlite3ApiExit(db, rc);
  if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
    int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
    *pzErrMsg = sqlite3_malloc(nErrMsg);
    if( *pzErrMsg ){
      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  assert( (rc&db->errMask)==rc );
  return rc;
}
Changes to src/main.c.
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.395 2007/08/22 02:56:44 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** The version of the library
*/







|







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.396 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>

/*
** The version of the library
*/
1072
1073
1074
1075
1076
1077
1078

1079

1080
1081
1082
1083
1084
1085
1086
#ifdef SQLITE_DEFAULT_LOCKING_MODE
  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
                          SQLITE_DEFAULT_LOCKING_MODE);
#endif

opendb_out:

  sqlite3_mutex_leave(db->mutex);

  if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
    sqlite3_close(db);
    db = 0;
  }
  *ppDb = db;
  return sqlite3ApiExit(0, rc);
}







>
|
>







1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
#ifdef SQLITE_DEFAULT_LOCKING_MODE
  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
                          SQLITE_DEFAULT_LOCKING_MODE);
#endif

opendb_out:
  if( db ){
    sqlite3_mutex_leave(db->mutex);
  }
  if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
    sqlite3_close(db);
    db = 0;
  }
  *ppDb = db;
  return sqlite3ApiExit(0, rc);
}
Changes to src/malloc.c.
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.
**
*************************************************************************
** Memory allocation functions used throughout sqlite.
**
**
** $Id: malloc.c,v 1.9 2007/08/22 00:39:20 drh Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>
#include <ctype.h>

/*
** This routine runs when the memory allocator sees that the







|







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.
**
*************************************************************************
** Memory allocation functions used throughout sqlite.
**
**
** $Id: malloc.c,v 1.10 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include <stdarg.h>
#include <ctype.h>

/*
** This routine runs when the memory allocator sees that the
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

/*
** Allocate and zero memory.  If the allocation fails, make
** the mallocFailed flag in the connection pointer.
*/
void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
  void *p = sqlite3_malloc(n);
  if( !p ){
    db->mallocFailed = 1;
  }
  return p;
}

/*
** Attempt to reallocate p.  If the reallocation fails, then free p







|







93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

/*
** Allocate and zero memory.  If the allocation fails, make
** the mallocFailed flag in the connection pointer.
*/
void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
  void *p = sqlite3_malloc(n);
  if( !p && db ){
    db->mallocFailed = 1;
  }
  return p;
}

/*
** Attempt to reallocate p.  If the reallocation fails, then free p
Changes to src/mem1.c.
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 the C functions that implement a memory
** allocation subsystem for use by SQLite.  
**
** $Id: mem1.c,v 1.6 2007/08/17 15:53:36 danielk1977 Exp $
*/

/*
** This version of the memory allocator is the default.  It is
** used when no other memory allocator is specified using compile-time
** macros.
*/







|







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 the C functions that implement a memory
** allocation subsystem for use by SQLite.  
**
** $Id: mem1.c,v 1.7 2007/08/22 20:18:22 drh Exp $
*/

/*
** This version of the memory allocator is the default.  It is
** used when no other memory allocator is specified using compile-time
** macros.
*/
144
145
146
147
148
149
150
151
152



153
154
155
156
157
158
159
  sqlite3_mutex_enter(mem.mutex);
  mem.alarmBusy = 0;
}

/*
** Allocate nBytes of memory
*/
void *sqlite3_malloc(unsigned int nBytes){
  sqlite3_uint64 *p;



  if( mem.mutex==0 ){
    mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
  }
  sqlite3_mutex_enter(mem.mutex);
  if( mem.nowUsed+nBytes>=mem.alarmThreshold ){
    sqlite3MemsysAlarm(nBytes);
  }







|

>
>
>







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
  sqlite3_mutex_enter(mem.mutex);
  mem.alarmBusy = 0;
}

/*
** Allocate nBytes of memory
*/
void *sqlite3_malloc(int nBytes){
  sqlite3_uint64 *p;
  if( nBytes<=0 ){
    return 0;
  }
  if( mem.mutex==0 ){
    mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
  }
  sqlite3_mutex_enter(mem.mutex);
  if( mem.nowUsed+nBytes>=mem.alarmThreshold ){
    sqlite3MemsysAlarm(nBytes);
  }
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  free(p);
  sqlite3_mutex_leave(mem.mutex);  
}

/*
** Change the size of an existing memory allocation
*/
void *sqlite3_realloc(void *pPrior, unsigned int nBytes){
  unsigned nOld;
  sqlite3_uint64 *p;
  if( pPrior==0 ){
    return sqlite3_malloc(nBytes);
  }
  if( nBytes==0 ){
    sqlite3_free(pPrior);
    return 0;
  }
  p = pPrior;
  p--;
  nOld = (unsigned int)p[0];
  assert( mem.mutex!=0 );







|





|







195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
  free(p);
  sqlite3_mutex_leave(mem.mutex);  
}

/*
** Change the size of an existing memory allocation
*/
void *sqlite3_realloc(void *pPrior, int nBytes){
  unsigned nOld;
  sqlite3_uint64 *p;
  if( pPrior==0 ){
    return sqlite3_malloc(nBytes);
  }
  if( nBytes<=0 ){
    sqlite3_free(pPrior);
    return 0;
  }
  p = pPrior;
  p--;
  nOld = (unsigned int)p[0];
  assert( mem.mutex!=0 );
Changes to src/mem2.c.
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 the C functions that implement a memory
** allocation subsystem for use by SQLite.  
**
** $Id: mem2.c,v 1.5 2007/08/20 22:48:43 drh Exp $
*/

/*
** This version of the memory allocator is used only if the
** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION
** is not defined.
*/







|







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 the C functions that implement a memory
** allocation subsystem for use by SQLite.  
**
** $Id: mem2.c,v 1.6 2007/08/22 20:18:22 drh Exp $
*/

/*
** This version of the memory allocator is used only if the
** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION
** is not defined.
*/
245
246
247
248
249
250
251
252
253
254
255
256
257
258



259
260
261
262
263
264
265
static void sqlite3MemsysFailed(void){
  mem.iFailCnt = 0;
}

/*
** Allocate nByte bytes of memory.
*/
void *sqlite3_malloc(unsigned int nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  unsigned int *pInt;
  void *p;
  unsigned int totalSize;




  if( mem.mutex==0 ){
    mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
  }
  sqlite3_mutex_enter(mem.mutex);
  assert( mem.disallow==0 );
  if( mem.nowUsed+nByte>=mem.alarmThreshold ){
    sqlite3MemsysAlarm(nByte);







|






>
>
>







245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
static void sqlite3MemsysFailed(void){
  mem.iFailCnt = 0;
}

/*
** Allocate nByte bytes of memory.
*/
void *sqlite3_malloc(int nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  unsigned int *pInt;
  void *p;
  unsigned int totalSize;

  if( nByte<=0 ){
    return 0;
  }
  if( mem.mutex==0 ){
    mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
  }
  sqlite3_mutex_enter(mem.mutex);
  assert( mem.disallow==0 );
  if( mem.nowUsed+nByte>=mem.alarmThreshold ){
    sqlite3MemsysAlarm(nByte);
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
**
** For this debugging implementation, we *always* make a copy of the
** allocation into a new place in memory.  In this way, if the 
** higher level code is using pointer to the old allocation, it is 
** much more likely to break and we are much more liking to find
** the error.
*/
void *sqlite3_realloc(void *pPrior, unsigned int nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;
  if( pPrior==0 ){
    return sqlite3_malloc(nByte);
  }
  if( nByte==0 ){
    sqlite3_free(pPrior);
    return 0;
  }
  assert( mem.disallow==0 );
  pOldHdr = sqlite3MemsysGetHeader(pPrior);
  pNew = sqlite3_malloc(nByte);
  if( pNew ){







|





|







363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
**
** For this debugging implementation, we *always* make a copy of the
** allocation into a new place in memory.  In this way, if the 
** higher level code is using pointer to the old allocation, it is 
** much more likely to break and we are much more liking to find
** the error.
*/
void *sqlite3_realloc(void *pPrior, int nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;
  if( pPrior==0 ){
    return sqlite3_malloc(nByte);
  }
  if( nByte<=0 ){
    sqlite3_free(pPrior);
    return 0;
  }
  assert( mem.disallow==0 );
  pOldHdr = sqlite3MemsysGetHeader(pPrior);
  pNew = sqlite3_malloc(nByte);
  if( pNew ){
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
  fclose(out);
}

/*
** This routine is used to simulate malloc failures.
**
** After calling this routine, there will be iFail successful
** memory allocations and then a failure.  If iRepeat is true,
** all subsequent memory allocations will fail.  If iRepeat is
** false, only a single allocation will fail.

**
** Each call to this routine overrides the previous.  To disable
** the simulated allocation failure mechanism, set iFail to -1.
**
** This routine returns the number of simulated failures that have
** occurred since the previous call.
*/
int sqlite3_memdebug_fail(int iFail, int iRepeat){
  int n = mem.iFailCnt;
  mem.iFail = iFail+1;

  mem.iReset = iRepeat;

  mem.iFailCnt = 0;
  return n;
}

/*
** The following two routines are used to assert that no memory
** allocations occur between one call and the next.  The use of







|

|
>










>
|
>







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
459
  fclose(out);
}

/*
** This routine is used to simulate malloc failures.
**
** After calling this routine, there will be iFail successful
** memory allocations and then a failure.  If iRepeat is 1
** all subsequent memory allocations will fail.  If iRepeat is
** 0, only a single allocation will fail.  If iRepeat is negative
** then the previous setting for iRepeat is unchanged.
**
** Each call to this routine overrides the previous.  To disable
** the simulated allocation failure mechanism, set iFail to -1.
**
** This routine returns the number of simulated failures that have
** occurred since the previous call.
*/
int sqlite3_memdebug_fail(int iFail, int iRepeat){
  int n = mem.iFailCnt;
  mem.iFail = iFail+1;
  if( iRepeat>=0 ){
    mem.iReset = iRepeat;
  }
  mem.iFailCnt = 0;
  return n;
}

/*
** The following two routines are used to assert that no memory
** allocations occur between one call and the next.  The use of
Changes to src/os_unix.c.
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
** value.
**
** If SQLITE_OK is returned, the caller is responsible for closing
** the file descriptor *pFd using close().
*/
static int openDirectory(const char *zFilename, int *pFd){
  char *zDirname;
  int ii;
  int fd;

  zDirname = (char *)sqlite3_malloc(MAX_PATHNAME);
  if( !zDirname ){
    return SQLITE_NOMEM;
  }
  strncpy(zDirname, zFilename, MAX_PATHNAME);
  zDirname[MAX_PATHNAME-1] = '\0';
  for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
  if( ii>0 ){
    zDirname[ii] = '\0';
    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
    if( fd>0 ){
#ifdef FD_CLOEXEC
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
#endif
      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
    }
  }
  sqlite3_free(zDirname);
  *pFd = fd;
  return (fd>0?SQLITE_OK:SQLITE_CANTOPEN);
}

/*
** Open the file zPath.
** 







<


<
<
|
<
|













<







2313
2314
2315
2316
2317
2318
2319

2320
2321


2322

2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336

2337
2338
2339
2340
2341
2342
2343
** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
** value.
**
** If SQLITE_OK is returned, the caller is responsible for closing
** the file descriptor *pFd using close().
*/
static int openDirectory(const char *zFilename, int *pFd){

  int ii;
  int fd;


  char zDirname[MAX_PATHNAME+1];


  strncpy(zDirname, zFilename, MAX_PATHNAME);
  zDirname[MAX_PATHNAME-1] = '\0';
  for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
  if( ii>0 ){
    zDirname[ii] = '\0';
    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
    if( fd>0 ){
#ifdef FD_CLOEXEC
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
#endif
      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
    }
  }

  *pFd = fd;
  return (fd>0?SQLITE_OK:SQLITE_CANTOPEN);
}

/*
** Open the file zPath.
** 
Changes to src/printf.c.
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
*/
struct sgMprintf {
  char *zBase;     /* A base allocation */
  char *zText;     /* The string collected so far */
  int  nChar;      /* Length of the string so far */
  int  nTotal;     /* Output size if unconstrained */
  int  nAlloc;     /* Amount of space allocated in zText */
  void *(*xRealloc)(void*, unsigned int);  /* Function used to realloc memory */
};

/* 
** This function implements the callback from vxprintf. 
**
** This routine add nNewChar characters of text in zNewText to
** the sgMprintf structure pointed to by "arg".







|







713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
*/
struct sgMprintf {
  char *zBase;     /* A base allocation */
  char *zText;     /* The string collected so far */
  int  nChar;      /* Length of the string so far */
  int  nTotal;     /* Output size if unconstrained */
  int  nAlloc;     /* Amount of space allocated in zText */
  void *(*xRealloc)(void*,int);  /* Function used to realloc memory */
};

/* 
** This function implements the callback from vxprintf. 
**
** This routine add nNewChar characters of text in zNewText to
** the sgMprintf structure pointed to by "arg".
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
}

/*
** This routine is a wrapper around xprintf() that invokes mout() as
** the consumer.  
*/
static char *base_vprintf(
  void *(*xRealloc)(void*, unsigned int), /* realloc() function. May be NULL */
  int useInternal,                /* Use internal %-conversions if true */
  char *zInitBuf,                 /* Initially write here, before mallocing */
  int nInitBuf,                   /* Size of zInitBuf[] */
  const char *zFormat,            /* format string */
  va_list ap                      /* arguments */
){
  struct sgMprintf sM;







|







765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
}

/*
** This routine is a wrapper around xprintf() that invokes mout() as
** the consumer.  
*/
static char *base_vprintf(
  void *(*xRealloc)(void*, int),  /* realloc() function. May be NULL */
  int useInternal,                /* Use internal %-conversions if true */
  char *zInitBuf,                 /* Initially write here, before mallocing */
  int nInitBuf,                   /* Size of zInitBuf[] */
  const char *zFormat,            /* format string */
  va_list ap                      /* arguments */
){
  struct sgMprintf sM;
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
  }
  return sM.zText;
}

/*
** Realloc that is a real function, not a macro.
*/
static void *printf_realloc(void *old, unsigned int size){
  return sqlite3_realloc(old, size);
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/







|







797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
  }
  return sM.zText;
}

/*
** Realloc that is a real function, not a macro.
*/
static void *printf_realloc(void *old, int size){
  return sqlite3_realloc(old, size);
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
Changes to src/sqlite.h.in.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
** on how SQLite interfaces are suppose to operate.
**
** The name of this file under configuration management is "sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "sqlite3.h" as
** part of the build process.
**
** @(#) $Id: sqlite.h.in,v 1.236 2007/08/22 00:39:20 drh Exp $
*/
#ifndef _SQLITE3_H_
#define _SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.







|







26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
** on how SQLite interfaces are suppose to operate.
**
** The name of this file under configuration management is "sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "sqlite3.h" as
** part of the build process.
**
** @(#) $Id: sqlite.h.in,v 1.237 2007/08/22 20:18:22 drh Exp $
*/
#ifndef _SQLITE3_H_
#define _SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
**
** <blockquote> SQLITE_OMIT_MEMORY_ALLOCATION </blockquote>
**
** then no implementation is provided for these routines by
** SQLite.  The application that links against SQLite is
** expected to provide its own implementation.
*/
void *sqlite3_malloc(unsigned int);
void *sqlite3_realloc(void*, unsigned int);
void sqlite3_free(void*);

/*
** CAPI3REF: Memory Allocator Statistics
**
** In addition to the basic three allocation routines 
** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],







|
|







1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
**
** <blockquote> SQLITE_OMIT_MEMORY_ALLOCATION </blockquote>
**
** then no implementation is provided for these routines by
** SQLite.  The application that links against SQLite is
** expected to provide its own implementation.
*/
void *sqlite3_malloc(int);
void *sqlite3_realloc(void*, int);
void sqlite3_free(void*);

/*
** CAPI3REF: Memory Allocator Statistics
**
** In addition to the basic three allocation routines 
** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
Changes to src/sqlite3ext.h.
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
**
** @(#) $Id: sqlite3ext.h,v 1.13 2007/08/16 10:09:03 danielk1977 Exp $
*/
#ifndef _SQLITE3EXT_H_
#define _SQLITE3EXT_H_
#include "sqlite3.h"

typedef struct sqlite3_api_routines sqlite3_api_routines;








|







11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
**
** @(#) $Id: sqlite3ext.h,v 1.14 2007/08/22 20:18:22 drh Exp $
*/
#ifndef _SQLITE3EXT_H_
#define _SQLITE3EXT_H_
#include "sqlite3.h"

typedef struct sqlite3_api_routines sqlite3_api_routines;

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  void * (*get_auxdata)(sqlite3_context*,int);
  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  int  (*global_recover)(void);
  void  (*interruptx)(sqlite3*);
  sqlite_int64  (*last_insert_rowid)(sqlite3*);
  const char * (*libversion)(void);
  int  (*libversion_number)(void);
  void *(*malloc)(unsigned int);
  char * (*mprintf)(const char*,...);
  int  (*open)(const char*,sqlite3**);
  int  (*open16)(const void*,sqlite3**);
  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  void *(*realloc)(void*,unsigned int);
  int  (*reset)(sqlite3_stmt*pStmt);
  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_double)(sqlite3_context*,double);
  void  (*result_error)(sqlite3_context*,const char*,int);
  void  (*result_error16)(sqlite3_context*,const void*,int);
  void  (*result_int)(sqlite3_context*,int);
  void  (*result_int64)(sqlite3_context*,sqlite_int64);







|







|







98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  void * (*get_auxdata)(sqlite3_context*,int);
  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  int  (*global_recover)(void);
  void  (*interruptx)(sqlite3*);
  sqlite_int64  (*last_insert_rowid)(sqlite3*);
  const char * (*libversion)(void);
  int  (*libversion_number)(void);
  void *(*malloc)(int);
  char * (*mprintf)(const char*,...);
  int  (*open)(const char*,sqlite3**);
  int  (*open16)(const void*,sqlite3**);
  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  void *(*realloc)(void*,int);
  int  (*reset)(sqlite3_stmt*pStmt);
  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  void  (*result_double)(sqlite3_context*,double);
  void  (*result_error)(sqlite3_context*,const char*,int);
  void  (*result_error16)(sqlite3_context*,const void*,int);
  void  (*result_int)(sqlite3_context*,int);
  void  (*result_int64)(sqlite3_context*,sqlite_int64);
Changes to src/tclsqlite.c.
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.
**
*************************************************************************
** A TCL Interface to SQLite.  Append this file to sqlite3.c and
** compile the whole thing to build a TCL-enabled version of SQLite.
**
** $Id: tclsqlite.c,v 1.197 2007/08/22 00:39:21 drh Exp $
*/
#include "tcl.h"
#include <errno.h>

/*
** Some additional include files are needed if this file is not
** appended to the amalgamation.







|







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.
**
*************************************************************************
** A TCL Interface to SQLite.  Append this file to sqlite3.c and
** compile the whole thing to build a TCL-enabled version of SQLite.
**
** $Id: tclsqlite.c,v 1.198 2007/08/22 20:18:22 drh Exp $
*/
#include "tcl.h"
#include <errno.h>

/*
** Some additional include files are needed if this file is not
** appended to the amalgamation.
2346
2347
2348
2349
2350
2351
2352










2353

2354

2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
  sqlite3_open(zFile, &p->db);
  Tcl_DStringFree(&translatedFilename);
  if( SQLITE_OK!=sqlite3_errcode(p->db) ){
    zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
    sqlite3_close(p->db);
    p->db = 0;
  }










#ifdef SQLITE_HAS_CODEC

  sqlite3_key(p->db, pKey, nKey);

#endif
  if( p->db==0 ){
    Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
    Tcl_Free((char*)p);
    sqlite3_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->interp = interp;
  zArg = Tcl_GetStringFromObj(objv[1], 0);
  Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);

  /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
  ** SQL function.
  */
#ifdef SQLITE_TEST
  {
    extern void Md5_Register(sqlite3*);
#if 0
    int mallocfail = sqlite3_iMallocFail;
    sqlite3_iMallocFail = 0;
#endif
    Md5_Register(p->db);
#if 0
    sqlite3_iMallocFail = mallocfail;
#endif
  }
#endif  
  return TCL_OK;
}

/*
** Provide a dummy Tcl_InitStubs if we are using this as a static
** library.
*/







>
>
>
>
>
>
>
>
>
>

>
|
>











<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377

















2378
2379
2380
2381
2382
2383
2384
  sqlite3_open(zFile, &p->db);
  Tcl_DStringFree(&translatedFilename);
  if( SQLITE_OK!=sqlite3_errcode(p->db) ){
    zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
    sqlite3_close(p->db);
    p->db = 0;
  }
#ifdef SQLITE_TEST
  if( p->db ){
    extern int Md5_Register(sqlite3*);
    if( Md5_Register(p->db)==SQLITE_NOMEM ){
      zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
      sqlite3_close(p->db);
      p->db = 0;
    }
  }
#endif  
#ifdef SQLITE_HAS_CODEC
  if( p->db ){
    sqlite3_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){
    Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
    Tcl_Free((char*)p);
    sqlite3_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->interp = interp;
  zArg = Tcl_GetStringFromObj(objv[1], 0);
  Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);

















  return TCL_OK;
}

/*
** Provide a dummy Tcl_InitStubs if we are using this as a static
** library.
*/
Changes to src/test1.c.
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 all sorts of SQLite interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.269 2007/08/22 02:56:44 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*







|







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 all sorts of SQLite interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** $Id: test1.c,v 1.270 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
951
952
953
954
955
956
957

958
959



960
961
962

963

964
965
966
967
968
969
970
  }

#ifndef SQLITE_OMIT_UTF16
  /* Use the sqlite3_create_function16() API here. Mainly for fun, but also 
  ** because it is not tested anywhere else. */
  if( rc==SQLITE_OK ){
    sqlite3_value *pVal;

    pVal = sqlite3ValueNew(0);
    sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC);



    rc = sqlite3_create_function16(db, 
              sqlite3ValueText(pVal, SQLITE_UTF16NATIVE),
              1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0);

    sqlite3ValueFree(pVal);

  }
#endif

  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}







>
|

>
>
>
|


>

>







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
  }

#ifndef SQLITE_OMIT_UTF16
  /* Use the sqlite3_create_function16() API here. Mainly for fun, but also 
  ** because it is not tested anywhere else. */
  if( rc==SQLITE_OK ){
    sqlite3_value *pVal;
    sqlite3_mutex_enter(db->mutex);
    pVal = sqlite3ValueNew(db);
    sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC);
    if( db->mallocFailed ){
      rc = SQLITE_NOMEM;
    }else{
      rc = sqlite3_create_function16(db, 
              sqlite3ValueText(pVal, SQLITE_UTF16NATIVE),
              1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0);
    }
    sqlite3ValueFree(pVal);
    sqlite3_mutex_leave(db->mutex);
  }
#endif

  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
  return TCL_OK;
}
2130
2131
2132
2133
2134
2135
2136

2137
2138



2139
2140
2141

2142

2143
2144
2145
2146
2147
2148
2149
    if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;

#if 0
    if( sqlite3_iMallocFail>0 ){
      sqlite3_iMallocFail++;
    }
#endif

    pVal = sqlite3ValueNew(0);
    sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC);



    rc = sqlite3_create_collation16(db, 
          sqlite3ValueText(pVal, SQLITE_UTF16NATIVE), SQLITE_UTF16BE, 
          (void *)SQLITE_UTF16BE, val?test_collate_func:0);

    sqlite3ValueFree(pVal);

  }
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
    return TCL_ERROR;
  }







>
|

>
>
>
|


>

>







2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
    if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;

#if 0
    if( sqlite3_iMallocFail>0 ){
      sqlite3_iMallocFail++;
    }
#endif
    sqlite3_mutex_enter(db->mutex);
    pVal = sqlite3ValueNew(db);
    sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC);
    if( db->mallocFailed ){
      rc = SQLITE_NOMEM;
    }else{
      rc = sqlite3_create_collation16(db, 
          sqlite3ValueText(pVal, SQLITE_UTF16NATIVE), SQLITE_UTF16BE, 
          (void *)SQLITE_UTF16BE, val?test_collate_func:0);
    }
    sqlite3ValueFree(pVal);
    sqlite3_mutex_leave(db->mutex);
  }
  if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
  
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
    return TCL_ERROR;
  }
Changes to src/test_config.c.
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
** 
** This file contains code used for testing the SQLite system.
** None of the code in this file goes into a deliverable build.
** 
** The focus of this file is providing the TCL testing layer
** access to compile-time constants.
**
** $Id: test_config.c,v 1.11 2007/08/21 10:44:16 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*







|







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
** 
** This file contains code used for testing the SQLite system.
** None of the code in this file goes into a deliverable build.
** 
** The focus of this file is providing the TCL testing layer
** access to compile-time constants.
**
** $Id: test_config.c,v 1.12 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

/*
54
55
56
57
58
59
60






61
62
63
64
65
66
67
#endif

#ifdef SQLITE_DISABLE_LFS
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "1", TCL_GLOBAL_ONLY);
#endif







#ifdef SQLITE_OMIT_ALTERTABLE
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "1", TCL_GLOBAL_ONLY);
#endif








>
>
>
>
>
>







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#endif

#ifdef SQLITE_DISABLE_LFS
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "lfs", "1", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_MEMDEBUG
  Tcl_SetVar2(interp, "sqlite_options", "memdebug", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "memdebug", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_OMIT_ALTERTABLE
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "altertable", "1", TCL_GLOBAL_ONLY);
#endif

Changes to src/test_md5.c.
378
379
380
381
382
383
384
385
386
387
388
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite3_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  DigestToBase16(digest, zBuf);
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
}
void Md5_Register(sqlite3 *db){
  sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0, 
      md5step, md5finalize);
}







|
|
|

378
379
380
381
382
383
384
385
386
387
388
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite3_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  DigestToBase16(digest, zBuf);
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
}
int Md5_Register(sqlite3 *db){
  return sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0, 
                                 md5step, md5finalize);
}
Changes to src/tokenize.c.
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.134 2007/08/21 10:44:16 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>
#include <stdlib.h>

/*
** The charMap() macro maps alphabetic characters into their







|







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.135 2007/08/22 20:18:22 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>
#include <stdlib.h>

/*
** The charMap() macro maps alphabetic characters into their
397
398
399
400
401
402
403

404
405
406
407
408
409
410
  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  i = 0;
  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc);
  if( pEngine==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 );







>







397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  i = 0;
  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc);
  if( pEngine==0 ){
    db->mallocFailed = 1;
    return SQLITE_NOMEM;
  }
  assert( pParse->sLastToken.dyn==0 );
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
  assert( pParse->nVarExpr==0 );
Changes to src/trigger.c.
261
262
263
264
265
266
267

268
269
270
271
272
273
274
275
  if( db->init.busy ){
    int n;
    Table *pTab;
    Trigger *pDel;
    pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
                     pTrig->name, strlen(pTrig->name), pTrig);
    if( pDel ){

      assert( db->mallocFailed && pDel==pTrig );
      goto triggerfinish_cleanup;
    }
    n = strlen(pTrig->table) + 1;
    pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
    assert( pTab!=0 );
    pTrig->pNext = pTab->pTrigger;
    pTab->pTrigger = pTrig;







>
|







261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
  if( db->init.busy ){
    int n;
    Table *pTab;
    Trigger *pDel;
    pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
                     pTrig->name, strlen(pTrig->name), pTrig);
    if( pDel ){
      assert( pDel==pTrig );
      db->mallocFailed = 1;
      goto triggerfinish_cleanup;
    }
    n = strlen(pTrig->table) + 1;
    pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
    assert( pTab!=0 );
    pTrig->pNext = pTab->pTrigger;
    pTab->pTrigger = pTrig;
352
353
354
355
356
357
358
359
360
361
362
363

364
365
366
367
368
369
370
  sqlite3 *db,        /* The database connection */
  Token *pTableName,  /* Name of the table into which we insert */
  IdList *pColumn,    /* List of columns in pTableName to insert into */
  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
  Select *pSelect,    /* A SELECT statement that supplies values */
  int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
){
  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));

  assert(pEList == 0 || pSelect == 0);
  assert(pEList != 0 || pSelect != 0);


  if( pTriggerStep ){
    pTriggerStep->op = TK_INSERT;
    pTriggerStep->pSelect = pSelect;
    pTriggerStep->target  = *pTableName;
    pTriggerStep->pIdList = pColumn;
    pTriggerStep->pExprList = pEList;
    pTriggerStep->orconf = orconf;







|


|

>







353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
  sqlite3 *db,        /* The database connection */
  Token *pTableName,  /* Name of the table into which we insert */
  IdList *pColumn,    /* List of columns in pTableName to insert into */
  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
  Select *pSelect,    /* A SELECT statement that supplies values */
  int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
){
  TriggerStep *pTriggerStep;

  assert(pEList == 0 || pSelect == 0);
  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);

  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  if( pTriggerStep ){
    pTriggerStep->op = TK_INSERT;
    pTriggerStep->pSelect = pSelect;
    pTriggerStep->target  = *pTableName;
    pTriggerStep->pIdList = pColumn;
    pTriggerStep->pExprList = pEList;
    pTriggerStep->orconf = orconf;
Changes to src/vdbemem.c.
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
*/
sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  Mem *p = sqlite3MallocZero(sizeof(*p));
  if( p ){
    p->flags = MEM_Null;
    p->type = SQLITE_NULL;
    p->db = db;
  }else{
    db->mallocFailed = 1;
  }
  return p;
}

/*
** Create a new sqlite3_value object, containing the value of pExpr.







|







904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
*/
sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  Mem *p = sqlite3MallocZero(sizeof(*p));
  if( p ){
    p->flags = MEM_Null;
    p->type = SQLITE_NULL;
    p->db = db;
  }else if( db ){
    db->mallocFailed = 1;
  }
  return p;
}

/*
** Create a new sqlite3_value object, containing the value of pExpr.
Changes to test/malloc.test.
1
2
3
4
5
6
7
8
9
10

11
12

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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.
#
#***********************************************************************

# 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.43 2007/08/16 04:39: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_MEMDEBUG..."
   finish_test
   return
}

source $testdir/malloc_common.tcl











>
|
|
>
|
|
|

|






|







1
2
3
4
5
6
7
8
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
# 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.
#
#***********************************************************************
#
# This file attempts to check the behavior of the SQLite library in 
# an out-of-memory situation. When compiled with -DSQLITE_DEBUG=1, 
# the SQLite library accepts a special command (sqlite3_memdebug_fail N C)
# 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.44 2007/08/22 20:18:22 drh Exp $

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

# Only run these tests if memory debugging is turned on.
#
ifcapable !memdebug {
   puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
   finish_test
   return
}

source $testdir/malloc_common.tcl

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

221

222


223
224
225
226
227
228
229
  INSERT INTO t1 VALUES(3, 4);
  INSERT INTO t1 VALUES(5, 6);
  INSERT INTO t1 VALUES(7, randstr(1200,1200));
} -sqlbody {
  SELECT min(a) FROM t1 WHERE a<6 GROUP BY b;
  SELECT a FROM t1 WHERE a<6 ORDER BY a;
  SELECT b FROM t1 WHERE a>6;
} 

# This block is designed to test that some malloc failures that may
# occur in vdbeapi.c. Specifically, if a malloc failure that occurs
# when converting UTF-16 text to integers and real numbers is handled
# correctly. 
#
# This is done by retrieving a string from the database engine and
# manipulating it using the sqlite3_column_*** APIs. This doesn't 
# actually return an error to the user when a malloc() fails.. That 
# could be viewed as a bug.
#
# These tests only run if UTF-16 support is compiled in.
#
if {$::sqlite_options(utf16)} {

  do_malloc_test 8 -tclprep {
    set sql "SELECT '[string repeat abc 20]', '[string repeat def 20]', ?"
    set ::STMT [sqlite3_prepare $::DB $sql -1 X]
    sqlite3_step $::STMT
    if { $::tcl_platform(byteOrder)=="littleEndian" } {
      set ::bomstr "\xFF\xFE"
    } else {
      set ::bomstr "\xFE\xFF"
    }
    append ::bomstr [encoding convertto unicode "123456789_123456789_12345678"]
  } -tclbody {
    sqlite3_column_text16 $::STMT 0
    sqlite3_column_int $::STMT 0
    sqlite3_column_text16 $::STMT 1
    sqlite3_column_double $::STMT 1
    sqlite3_reset $::STMT
    sqlite3_bind_text16 $::STMT 1 $::bomstr 60
    catch {sqlite3_finalize $::STMT}
    if {[lindex [sqlite_malloc_stat] 2]<=0} {
      error "out of memory"
    }

  } -cleanup {

    sqlite3_finalize $::STMT


  }
}

# This block tests that malloc() failures that occur whilst commiting
# a multi-file transaction are handled correctly.
#
do_malloc_test 9 -sqlprep {







|














>


|














|
|
|
<
>

>
|
>
>







180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235
  INSERT INTO t1 VALUES(3, 4);
  INSERT INTO t1 VALUES(5, 6);
  INSERT INTO t1 VALUES(7, randstr(1200,1200));
} -sqlbody {
  SELECT min(a) FROM t1 WHERE a<6 GROUP BY b;
  SELECT a FROM t1 WHERE a<6 ORDER BY a;
  SELECT b FROM t1 WHERE a>6;
}

# This block is designed to test that some malloc failures that may
# occur in vdbeapi.c. Specifically, if a malloc failure that occurs
# when converting UTF-16 text to integers and real numbers is handled
# correctly. 
#
# This is done by retrieving a string from the database engine and
# manipulating it using the sqlite3_column_*** APIs. This doesn't 
# actually return an error to the user when a malloc() fails.. That 
# could be viewed as a bug.
#
# These tests only run if UTF-16 support is compiled in.
#
if {$::sqlite_options(utf16)} {
  set ::STMT {}
  do_malloc_test 8 -tclprep {
    set sql "SELECT '[string repeat abc 20]', '[string repeat def 20]', ?"
    set ::STMT [sqlite3_prepare db $sql -1 X]
    sqlite3_step $::STMT
    if { $::tcl_platform(byteOrder)=="littleEndian" } {
      set ::bomstr "\xFF\xFE"
    } else {
      set ::bomstr "\xFE\xFF"
    }
    append ::bomstr [encoding convertto unicode "123456789_123456789_12345678"]
  } -tclbody {
    sqlite3_column_text16 $::STMT 0
    sqlite3_column_int $::STMT 0
    sqlite3_column_text16 $::STMT 1
    sqlite3_column_double $::STMT 1
    sqlite3_reset $::STMT
    sqlite3_bind_text16 $::STMT 1 $::bomstr 60
    #catch {sqlite3_finalize $::STMT}
    #if {[lindex [sqlite_malloc_stat] 2]<=0} {
    #  error "out of memory"

    #}
  } -cleanup {
    if {$::STMT!=""} {
      sqlite3_finalize $::STMT
      set ::STMT {}
    }
  }
}

# This block tests that malloc() failures that occur whilst commiting
# a multi-file transaction are handled correctly.
#
do_malloc_test 9 -sqlprep {
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  sqlite3 db2 test.db
  db2 eval {SELECT * FROM sqlite_master}
  db2 close
} 

# This block tests malloc() failures that occur within calls to
# sqlite3_create_function().
do_malloc_test 11  -tclbody {
  set rc [sqlite3_create_function $::DB]
  if {[string match $rc SQLITE_NOMEM]} {
    error "out of memory"
  }
}

do_malloc_test 12 -tclbody {
  set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"]
  append sql16 "\00\00"
  set ::STMT [sqlite3_prepare16 $::DB $sql16 -1 DUMMY]
  sqlite3_finalize $::STMT
}

# Test malloc errors when replaying two hot journals from a 2-file 
# transaction.
ifcapable crashtest {
  do_malloc_test 13 -tclprep {







|
|








|







252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
  sqlite3 db2 test.db
  db2 eval {SELECT * FROM sqlite_master}
  db2 close
} 

# This block tests malloc() failures that occur within calls to
# sqlite3_create_function().
do_malloc_test 11 -tclbody {
  set rc [sqlite3_create_function db]
  if {[string match $rc SQLITE_NOMEM]} {
    error "out of memory"
  }
}

do_malloc_test 12 -tclbody {
  set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"]
  append sql16 "\00\00"
  set ::STMT [sqlite3_prepare16 db $sql16 -1 DUMMY]
  sqlite3_finalize $::STMT
}

# Test malloc errors when replaying two hot journals from a 2-file 
# transaction.
ifcapable crashtest {
  do_malloc_test 13 -tclprep {
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
proc string_compare {a b} {
  return [string compare $a $b]
}

# Test for malloc() failures in sqlite3_create_collation() and 
# sqlite3_create_collation16().
#
do_malloc_test 15 -tclbody {
  db collate string_compare string_compare
  if {[catch {add_test_collate $::DB 1 1 1} msg]} {
    if {$msg=="SQLITE_NOMEM"} {set msg "out of memory"}
    error $msg
  }

  db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;}
  db complete {-- Useful comment}








|

|







322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
proc string_compare {a b} {
  return [string compare $a $b]
}

# Test for malloc() failures in sqlite3_create_collation() and 
# sqlite3_create_collation16().
#
do_malloc_test 15 -start 4 -tclbody {
  db collate string_compare string_compare
  if {[catch {add_test_collate db 1 1 1} msg]} {
    if {$msg=="SQLITE_NOMEM"} {set msg "out of memory"}
    error $msg
  }

  db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;}
  db complete {-- Useful comment}

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
  execsql {
    PRAGMA encoding = "UTF16be";
    CREATE TABLE abc(a, b, c);
  }
} -tclbody {
  unset -nocomplain ::STMT
  set r [catch {
    set ::STMT [sqlite3_prepare $::DB {SELECT ?} -1 DUMMY]
    sqlite3_bind_text16 -static $::STMT 1 $static_string 112
  } msg]
  if {$r} {error [string range $msg 4 end]}
  set msg
} -cleanup {
  if {[info exists ::STMT]} {
    sqlite3_finalize $::STMT







|







425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
  execsql {
    PRAGMA encoding = "UTF16be";
    CREATE TABLE abc(a, b, c);
  }
} -tclbody {
  unset -nocomplain ::STMT
  set r [catch {
    set ::STMT [sqlite3_prepare db {SELECT ?} -1 DUMMY]
    sqlite3_bind_text16 -static $::STMT 1 $static_string 112
  } msg]
  if {$r} {error [string range $msg 4 end]}
  set msg
} -cleanup {
  if {[info exists ::STMT]} {
    sqlite3_finalize $::STMT
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

# Test malloc failure in an sqlite3_prepare_v2() call.
#
do_malloc_test 22 -tclbody {
  set ::STMT ""
  set r [catch {
    set ::STMT [
      sqlite3_prepare_v2 $::DB "SELECT * FROM sqlite_master" -1 DUMMY
    ]
  } msg]
  if {$r} {error [string range $msg 4 end]}
} -cleanup {
  if {$::STMT ne ""} {
    sqlite3_finalize $::STMT
    set ::STMT ""
  }
}

# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

puts open-file-count=$sqlite_open_file_count
sqlite_malloc_fail 0
finish_test







|

















<

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492

493

# Test malloc failure in an sqlite3_prepare_v2() call.
#
do_malloc_test 22 -tclbody {
  set ::STMT ""
  set r [catch {
    set ::STMT [
      sqlite3_prepare_v2 db "SELECT * FROM sqlite_master" -1 DUMMY
    ]
  } msg]
  if {$r} {error [string range $msg 4 end]}
} -cleanup {
  if {$::STMT ne ""} {
    sqlite3_finalize $::STMT
    set ::STMT ""
  }
}

# Ensure that no file descriptors were leaked.
do_test malloc-99.X {
  catch {db close}
  set sqlite_open_file_count
} {0}

puts open-file-count=$sqlite_open_file_count

finish_test
Changes to test/malloc_common.tcl.
26
27
28
29
30
31
32




33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
100
101
proc do_malloc_test {tn args} {
  array unset ::mallocopts 
  array set ::mallocopts $args

  if {[string is integer $tn]} {
    set tn malloc-$tn
  }






  set ::go 1
  for {set ::n 1} {$::go && $::n < 50000} {incr ::n} {
    do_test $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}
      catch {sqlite3 db test.db} 
      set ::DB [sqlite3_connection_pointer 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]

      # If the test fails (if $v!=0) and the database connection actually
      # exists, make sure the failure code is SQLITE_NOMEM.
      if {$v && [info command db]=="db" && [info exists ::mallocopts(-sqlbody)]
              && [db errorcode]!=7} {
        set v 999
      }

      set leftover [lindex [sqlite_malloc_stat] 2]
      if {$leftover>0} {
        if {$leftover>1} {puts "\nLeftover: $leftover\nReturn=$v  Message=$msg"}
        set ::go 0
        if {$v} {
          puts "\nError message returned: $msg"
        } else {
          set v {1 1}

        }
      } else {


        set v2 [expr {$msg=="" || $msg=="out of memory"}]
        if {!$v2} {puts "\nError message returned: $msg"}
        lappend v $v2


      }

    } {1 1}

    if {[info exists ::mallocopts(-cleanup)]} {
      catch [list uplevel #0 $::mallocopts(-cleanup)] msg
    }
  }
  unset ::mallocopts
}








>
>
>
>
|
>

|





<






<













|








|
<
<
<
<
|
|

<
|
<
<

|

|
>

|
>
>
|
<
|
>
>

>








<
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

46
47
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
100
101

proc do_malloc_test {tn args} {
  array unset ::mallocopts 
  array set ::mallocopts $args

  if {[string is integer $tn]} {
    set tn malloc-$tn
  }
  if {[info exists ::mallocopts(-start)]} {
    set start $::mallocopts(-start)
  } else {
    set start 1
  }

  set ::go 1
  for {set ::n $start} {$::go && $::n < 50000} {incr ::n} {
    do_test $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].
      # 

      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}
      catch {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.
      #
      sqlite3_memdebug_fail $::n 1
      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 failFlag [sqlite3_memdebug_fail -1 0]




      set go [expr {$failFlag>0}]



      if {$failFlag==0} {


        if {$v} {
          set v2 $msg
        } else {
          set v 1
          set v2 1
        }
      } elseif {!$v} {
        set v2 $msg
      } elseif {[info command db]=="" || [db errorcode]==7
                   || $msg=="out of memory"} {

        set v2 1
      } else {
        set v2 $msg
      }
      lappend v $v2
    } {1 1}

    if {[info exists ::mallocopts(-cleanup)]} {
      catch [list uplevel #0 $::mallocopts(-cleanup)] msg
    }
  }
  unset ::mallocopts
}

Changes to test/misc7.test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 2006 September 4
#
# 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 implements regression tests for SQLite library.
#
# $Id: misc7.test,v 1.14 2007/06/27 23:52:18 drh Exp $

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

do_test misc7-1 {
  c_misuse_test
} {}

do_test misc7-2 {
  c_realloc_test
} {}

do_test misc7-3 {
  c_collation_test












|




|
|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 2006 September 4
#
# 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 implements regression tests for SQLite library.
#
# $Id: misc7.test,v 1.15 2007/08/22 20:18:22 drh Exp $

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

#do_test misc7-1 {
#  c_misuse_test
#} {}

do_test misc7-2 {
  c_realloc_test
} {}

do_test misc7-3 {
  c_collation_test
Changes to test/tester.tcl.
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.
#
#***********************************************************************
# This file implements some common TCL routines used for regression
# testing the SQLite library
#
# $Id: tester.tcl,v 1.84 2007/08/20 14:23:44 danielk1977 Exp $

# Make sure tclsqlite3 was compiled correctly.  Abort now with an
# error message if not.
#
if {[sqlite3 -tcl-uses-utf]} {
  if {"\u1234"=="u1234"} {
    puts stderr "***** BUILD PROBLEM *****"













|







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.
#
#***********************************************************************
# This file implements some common TCL routines used for regression
# testing the SQLite library
#
# $Id: tester.tcl,v 1.85 2007/08/22 20:18:22 drh Exp $

# Make sure tclsqlite3 was compiled correctly.  Abort now with an
# error message if not.
#
if {[sqlite3 -tcl-uses-utf]} {
  if {"\u1234"=="u1234"} {
    puts stderr "***** BUILD PROBLEM *****"
204
205
206
207
208
209
210

211

212
213
214
215
216
217
218
219
220
221
222
223







224
225
226
227
228
229
230
          from $::soft_limit to $heaplimit"
  } elseif {$heaplimit!="" && $heaplimit>0} {
    puts "soft-heap-limit set to $heaplimit"
  }
  sqlite3_soft_heap_limit 0
  incr nTest
  puts "$nErr errors out of $nTest tests"

  puts "Failures on these tests: $::failList"

  if {$nErr>0 && ![working_64bit_int]} {
    puts "******************************************************************"
    puts "N.B.:  The version of TCL that you used to build this test harness"
    puts "is defective in that it does not support 64-bit integers.  Some or"
    puts "all of the test failures above might be a result from this defect"
    puts "in your TCL build."
    puts "******************************************************************"
  }
  if {$sqlite_open_file_count} {
    puts "$sqlite_open_file_count files were left open"
    incr nErr
  }







  foreach f [glob -nocomplain test.db-*-journal] {
    file delete -force $f
  }
  foreach f [glob -nocomplain test.db-mj*] {
    file delete -force $f
  }
  exit [expr {$nErr>0}]







>
|
>












>
>
>
>
>
>
>







204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
          from $::soft_limit to $heaplimit"
  } elseif {$heaplimit!="" && $heaplimit>0} {
    puts "soft-heap-limit set to $heaplimit"
  }
  sqlite3_soft_heap_limit 0
  incr nTest
  puts "$nErr errors out of $nTest tests"
  if {$nErr>0} {
    puts "Failures on these tests: $::failList"
  }
  if {$nErr>0 && ![working_64bit_int]} {
    puts "******************************************************************"
    puts "N.B.:  The version of TCL that you used to build this test harness"
    puts "is defective in that it does not support 64-bit integers.  Some or"
    puts "all of the test failures above might be a result from this defect"
    puts "in your TCL build."
    puts "******************************************************************"
  }
  if {$sqlite_open_file_count} {
    puts "$sqlite_open_file_count files were left open"
    incr nErr
  }
  if {[sqlite3_memory_used]>0} {
    puts "Unfreed memory: [sqlite3_memory_used] bytes"
    incr nErr
  } else {
    puts "All memory allocations freed - no leaks"
  }
  puts "Maximum memory usage: [sqlite3_memory_highwater] bytes"
  foreach f [glob -nocomplain test.db-*-journal] {
    file delete -force $f
  }
  foreach f [glob -nocomplain test.db-mj*] {
    file delete -force $f
  }
  exit [expr {$nErr>0}]
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
    fconfigure $t -translation binary
    puts -nonewline $t [read $f [file size $from]]
    close $t
    close $f
  }
}

# This command checks for outstanding calls to sqliteMalloc() from within
# the current thread. A list is returned with one entry for each outstanding
# malloc. Each list entry is itself a list of 5 items, as follows:
#
#     { <number-bytes> <file-name> <line-number> <test-case> <stack-dump> }
#
proc check_for_leaks {} {
  set ret [list]
  set cnt 0







|
|







567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    fconfigure $t -translation binary
    puts -nonewline $t [read $f [file size $from]]
    close $t
    close $f
  }
}

# This command checks for outstanding calls to sqlite3_malloc()
# A list is returned with one entry for each outstanding
# malloc. Each list entry is itself a list of 5 items, as follows:
#
#     { <number-bytes> <file-name> <line-number> <test-case> <stack-dump> }
#
proc check_for_leaks {} {
  set ret [list]
  set cnt 0