SQLite4
Check-in [949cb749fe]
Not logged in

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

Overview
Comment:Modify sqlite4_mem_methods to remove xRoundup, add the Benign methods, and for all methods to take an environment pointer as their first argument.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 949cb749fea9f1d14fa46464ce291486c1f009b5
User & Date: drh 2012-06-22 16:55:08
Context
2012-06-25
19:34
Merge the sqlite4_env api changes onto trunk. There is still a lot of work to be done, but it at least now passes most tests. check-in: 4192f826d1 user: drh tags: trunk
2012-06-22
20:29
Continuing work on sqlite4_env and getting it to be used everywhere. The changes here are mostly having to do with mutexes. They compile, but there are errors. This is an incremental check-in so that I can change to work on another project where an issue has just come up. check-in: 1d65209131 user: drh tags: sqlite4_env
18:06
Merge trunk changes. check-in: df818c275b user: dan tags: embedded-btree
16:55
Modify sqlite4_mem_methods to remove xRoundup, add the Benign methods, and for all methods to take an environment pointer as their first argument. check-in: 949cb749fe user: drh tags: trunk
14:58
Add the sqlite4_env parameter to sqlite4_threadsafe(). check-in: d3fa91fcba user: drh tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/main.c.

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
...
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.
  */
  MUTEX_LOGIC( pMaster = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  sqlite4_mutex_enter(pMaster);
  pEnv->isMutexInit = 1;
  if( !pEnv->isMallocInit ){
    rc = sqlite4MallocInit();
  }
  if( rc==SQLITE_OK ){
    pEnv->isMallocInit = 1;
    if( !pEnv->pInitMutex ){
      pEnv->pInitMutex =
           sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
      if( pEnv->bCoreMutex && !pEnv->pInitMutex ){
................................................................................
    SQLITE_EXTRA_SHUTDOWN();
#endif
    /*sqlite4_os_end();*/
    /* sqlite4_reset_auto_extension(); */
    pEnv->isInit = 0;
  }
  if( pEnv->isMallocInit ){
    sqlite4MallocEnd();
    pEnv->isMallocInit = 0;
  }
  if( pEnv->isMutexInit ){
    sqlite4MutexEnd();
    pEnv->isMutexInit = 0;
  }

  return SQLITE_OK;
}

/*
** This API allows applications to modify the configuration described by
** an sqlite4_env object.







|







 







|


<
<
<
<







131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
...
236
237
238
239
240
241
242
243
244
245




246
247
248
249
250
251
252
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.
  */
  MUTEX_LOGIC( pMaster = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  sqlite4_mutex_enter(pMaster);
  pEnv->isMutexInit = 1;
  if( !pEnv->isMallocInit ){
    rc = sqlite4MallocInit(pEnv);
  }
  if( rc==SQLITE_OK ){
    pEnv->isMallocInit = 1;
    if( !pEnv->pInitMutex ){
      pEnv->pInitMutex =
           sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
      if( pEnv->bCoreMutex && !pEnv->pInitMutex ){
................................................................................
    SQLITE_EXTRA_SHUTDOWN();
#endif
    /*sqlite4_os_end();*/
    /* sqlite4_reset_auto_extension(); */
    pEnv->isInit = 0;
  }
  if( pEnv->isMallocInit ){
    sqlite4MallocEnd(pEnv);
    pEnv->isMallocInit = 0;
  }





  return SQLITE_OK;
}

/*
** This API allows applications to modify the configuration described by
** an sqlite4_env object.

Changes to src/malloc.c.

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
49
50
51
..
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
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145

146
147
148
149
150
151
152
153
154
155
156
...
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
...
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
240
241
242
243
244
245
246
247
248
249
250

251
252
253
254
255
256
257
258
static SQLITE_WSD struct Mem0Global {
  sqlite4_mutex *mutex;         /* Mutex to serialize access */
} mem0 = { 0 };

/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(void){
  if( sqlite4DefaultEnv.m.xMalloc==0 ){
    sqlite4MemSetDefault(0);
  }
  memset(&mem0, 0, sizeof(mem0));
  if( sqlite4DefaultEnv.bCoreMutex ){
    mem0.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return sqlite4DefaultEnv.m.xInit(sqlite4DefaultEnv.m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(void){
  if( sqlite4DefaultEnv.m.xShutdown ){
    sqlite4DefaultEnv.m.xShutdown(sqlite4DefaultEnv.m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
................................................................................
    /* A memory allocation of a number of bytes which is near the maximum
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull;
    sqlite4_mutex_enter(mem0.mutex);
    nFull = pEnv->m.xRoundup(n);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    p = pEnv->m.xMalloc(nFull);
    if( p ){
      nFull = sqlite4MallocSize(pEnv, p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }

    sqlite4_mutex_leave(mem0.mutex);
  }else{
    p = pEnv->m.xMalloc(n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
void *sqlite4_malloc(sqlite4_env *pEnv, int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif

  return sqlite4Malloc(pEnv, n);
}


/*
** TRUE if p is a lookaside memory allocation from db
*/
#ifndef SQLITE_OMIT_LOOKASIDE
................................................................................
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(sqlite4_env *pEnv, void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->m.xSize(p);
}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{

    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return db->pEnv->m.xSize(p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(sqlite4_env *pEnv, void *p){
................................................................................
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED,
                     -sqlite4MallocSize(pEnv, p));
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(p);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pEnv->m.xFree(p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
    return 0;
  }
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pEnv, pOld);
  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  ** argument to xRealloc is always a value returned by a prior call to
  ** xRoundup. */
  nNew = pEnv->m.xRoundup(nBytes);
  if( nOld==nNew ){
    pNew = pOld;
  }else if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pEnv, pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pNew = pEnv->m.xRealloc(pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
void *sqlite4_realloc(sqlite4_env *pEnv, void *pOld, int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif

  return sqlite4Realloc(pEnv, pOld, n);
}


/*
** Allocate and zero memory.
*/ 
void *sqlite4MallocZero(sqlite4_env *pEnv, int n){







|
|
|


|


|





|
|
|







 







|

<
<
|





>


|










|



>
|







 







|






>



|







 







|


|







 







|
<
<
<
<
<
|




|






|









|



>
|







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
49
50
51
..
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
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
...
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
static SQLITE_WSD struct Mem0Global {
  sqlite4_mutex *mutex;         /* Mutex to serialize access */
} mem0 = { 0 };

/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(sqlite4_env *pEnv){
  if( pEnv->m.xMalloc==0 ){
    sqlite4MemSetDefault(pEnv);
  }
  memset(&mem0, 0, sizeof(mem0));
  if( pEnv->bCoreMutex ){
    mem0.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return pEnv->m.xInit(pEnv->m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(sqlite4_env *pEnv){
  if( pEnv->m.xShutdown ){
    pEnv->m.xShutdown(pEnv->m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
................................................................................
    /* A memory allocation of a number of bytes which is near the maximum
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull = (n + 7)&~7;
    sqlite4_mutex_enter(mem0.mutex);


    p = pEnv->m.xMalloc(pEnv->m.pAppData, nFull);
    if( p ){
      nFull = sqlite4MallocSize(pEnv, p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    p = pEnv->m.xMalloc(pEnv->m.pAppData, n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
void *sqlite4_malloc(sqlite4_env *pEnv, sqlite4_size_t n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  if( n>0x7fff0000 ) return 0;
  return sqlite4Malloc(pEnv, (int)n);
}


/*
** TRUE if p is a lookaside memory allocation from db
*/
#ifndef SQLITE_OMIT_LOOKASIDE
................................................................................
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(sqlite4_env *pEnv, void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->m.xSize(pEnv->m.pAppData, p);
}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{
    sqlite4_env *pEnv = db->pEnv;
    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return pEnv->m.xSize(pEnv->m.pAppData, p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(sqlite4_env *pEnv, void *p){
................................................................................
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED,
                     -sqlite4MallocSize(pEnv, p));
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(pEnv->m.pAppData, p);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pEnv->m.xFree(pEnv->m.pAppData, p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
    return 0;
  }
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pEnv, pOld);
  nNew = (nBytes + 7)&~7;





  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pEnv, pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
void *sqlite4_realloc(sqlite4_env *pEnv, void *pOld, sqlite4_size_t n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  if( n>0x7fff0000 ) return 0;
  return sqlite4Realloc(pEnv, pOld, (int)n);
}


/*
** Allocate and zero memory.
*/ 
void *sqlite4MallocZero(sqlite4_env *pEnv, int n){

Changes to src/mem0.c.

24
25
26
27
28
29
30
31
32
33
34

35
36
37
38
39
40
41
42
..
44
45
46
47
48
49
50
51
52
53
54


55
56

57
58
59
** macros.
*/
#ifdef SQLITE_ZERO_MALLOC

/*
** No-op versions of all memory allocation routines
*/
static void *sqlite4MemMalloc(int nByte){ return 0; }
static void sqlite4MemFree(void *pPrior){ return; }
static void *sqlite4MemRealloc(void *pPrior, int nByte){ return 0; }
static int sqlite4MemSize(void *pPrior){ return 0; }

static int sqlite4MemRoundup(int n){ return n; }
static int sqlite4MemInit(void *NotUsed){ return SQLITE_OK; }
static void sqlite4MemShutdown(void *NotUsed){ return; }

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

#endif /* SQLITE_ZERO_MALLOC */







|
|
|
|
>
|







 







<


|
>
>

<
>



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
..
45
46
47
48
49
50
51

52
53
54
55
56
57

58
59
60
61
** macros.
*/
#ifdef SQLITE_ZERO_MALLOC

/*
** No-op versions of all memory allocation routines
*/
static void *sqlite4MemMalloc(void *p, sqlite4_size_t nByte){ return 0; }
static void sqlite4MemFree(void *p, void *pPrior){ return; }
static void *sqlite4MemRealloc(void *p, void *pPrior, sqlite4_size_t nByte){
  return 0;
}
static int sqlite4MemSize(void*p, void *pPrior){ return 0; }
static int sqlite4MemInit(void *NotUsed){ return SQLITE_OK; }
static void sqlite4MemShutdown(void *NotUsed){ return; }

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0, 
     0,
     0
  };

  pEnv->m = defaultMethods;
}

#endif /* SQLITE_ZERO_MALLOC */

Changes to src/mem1.c.

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
...
138
139
140
141
142
143
144
145
146

147
148
149

150
151
152
153
154
155
156
157
158
159
160
161

162
163
164

165
166
167
168
169
170
171
172
173
174
175
176
177
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
...
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
267
268
269
270
271
272
273
274
275
276
277


278
279

280
281
282
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite4MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
static void *sqlite4MemMalloc(int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );

  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );

  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
** Like free() but works for allocations obtained from sqlite4MemMalloc()
** or sqlite4MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
static void sqlite4MemFree(void *pPrior){
#ifdef SQLITE_MALLOCSIZE

  SQLITE_FREE(pPrior);
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;

  assert( pPrior!=0 );
  p--;
  SQLITE_FREE(p);
#endif
}

/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static int sqlite4MemSize(void *pPrior){
#ifdef SQLITE_MALLOCSIZE

  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
#else
  sqlite4_int64 *p;

  if( pPrior==0 ) return 0;
  p = (sqlite4_int64*)pPrior;
  p--;
  return (int)p[0];
#endif
}

/*
** Like realloc().  Resize an allocation previously obtained from
** sqlite4MemMalloc().
**
** For this low-level interface, we know that pPrior!=0.  Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static void *sqlite4MemRealloc(void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);

  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */

  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite4MemRoundup(int n){
  return ROUND8(n);
}

/*
** Initialize this module.
*/
static int sqlite4MemInit(void *NotUsed){
#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  int cpuCount;
  size_t len;
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

#endif /* SQLITE_SYSTEM_MALLOC */







|


>








>







 







|

>



>










|

>



>



|













|


>











>







 







<
<
<
<
<
<
<







 







<


|
>
>

<
>



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
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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
...
212
213
214
215
216
217
218







219
220
221
222
223
224
225
...
268
269
270
271
272
273
274

275
276
277
278
279
280

281
282
283
284
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite4MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
static void *sqlite4MemMalloc(void *NotUsed, sqlite4_size_t nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );
  UNUSED_PARAMETER(NotUsed);
  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
** Like free() but works for allocations obtained from sqlite4MemMalloc()
** or sqlite4MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
static void sqlite4MemFree(void *NotUsed, void *pPrior){
#ifdef SQLITE_MALLOCSIZE
  UNUSED_PARAMETER(NotUsed);
  SQLITE_FREE(pPrior);
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  UNUSED_PARAMETER(NotUsed);
  assert( pPrior!=0 );
  p--;
  SQLITE_FREE(p);
#endif
}

/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static sqlite4_size_t sqlite4MemSize(void *NotUsed, void *pPrior){
#ifdef SQLITE_MALLOCSIZE
  UNUSED_PARAMETER(NotUsed);
  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
#else
  sqlite4_int64 *p;
  UNUSED_PARAMETER(NotUsed);
  if( pPrior==0 ) return 0;
  p = (sqlite4_int64*)pPrior;
  p--;
  return (sqlite4_size_t)p[0];
#endif
}

/*
** Like realloc().  Resize an allocation previously obtained from
** sqlite4MemMalloc().
**
** For this low-level interface, we know that pPrior!=0.  Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static void *sqlite4MemRealloc(void *NotUsed, void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  UNUSED_PARAMETER(NotUsed);
  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}








/*
** Initialize this module.
*/
static int sqlite4MemInit(void *NotUsed){
#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  int cpuCount;
  size_t len;
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     0
  };

  pEnv->m = defaultMethods;
}

#endif /* SQLITE_SYSTEM_MALLOC */

Changes to src/mem2.c.

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
169
170
171
172
173
174
175
176
177

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
...
235
236
237
238
239
240
241
242
243
244
245
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
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
360
361
362
...
363
364
365
366
367
368
369
370
371
372
373


374
375

376
377
378
379
380
381
382
...
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
...
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  ** bytes.  i==NCSIZE is the number of allocation attempts for
  ** sizes more than NCSIZE*8 bytes.
  */
  int nAlloc[NCSIZE];      /* Total number of allocations */
  int nCurrent[NCSIZE];    /* Current number of allocations */
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */

} mem;


/*
** Adjust memory usage statistics
*/
static void adjustStats(int iSize, int increment){
  int i = ROUND8(iSize)/8;
  if( i>NCSIZE-1 ){
    i = NCSIZE - 1;
  }
  if( increment>0 ){
    mem.nAlloc[i]++;
    mem.nCurrent[i]++;
    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
      mem.mxCurrent[i] = mem.nCurrent[i];
    }
  }else{
    mem.nCurrent[i]--;
    assert( mem.nCurrent[i]>=0 );
  }
}

/*
** Given an allocation, find the MemBlockHdr for that allocation.
**
** This routine checks the guards at either end of the allocation and
................................................................................
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  return p;
}

/*
** Return the number of bytes currently allocated at address p.
*/
static int sqlite4MemSize(void *p){
  struct MemBlockHdr *pHdr;

  if( !p ){
    return 0;
  }
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite4DefaultEnv.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  mem.mutex = 0;
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite4MemRoundup(int n){
  return ROUND8(n);
}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
*/
................................................................................
    *(pBuf++) = r & 0xff;
  }
}

/*
** Allocate nByte bytes of memory.
*/
static void *sqlite4MemMalloc(int nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  int *pInt;
  void *p = 0;
  int totalSize;
  int nReserve;
  sqlite4_mutex_enter(mem.mutex);
  assert( mem.disallow==0 );
  nReserve = ROUND8(nByte);
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
               mem.nBacktrace*sizeof(void*) + mem.nTitle;

  p = malloc(totalSize);
  if( p ){
    z = p;
    pBt = (void**)&z[mem.nTitle];
    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
    pHdr->pNext = 0;
    pHdr->pPrev = mem.pLast;
    if( mem.pLast ){
      mem.pLast->pNext = pHdr;
    }else{
      mem.pFirst = pHdr;
    }
    mem.pLast = pHdr;
    pHdr->iForeGuard = FOREGUARD;
    pHdr->eType = MEMTYPE_HEAP;
    pHdr->nBacktraceSlots = mem.nBacktrace;
    pHdr->nTitle = mem.nTitle;
    if( mem.nBacktrace ){
      void *aAddr[40];
      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
      assert(pBt[0]);
      if( mem.xBacktrace ){
        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
      }
    }else{
      pHdr->nBacktrace = 0;
    }
    if( mem.nTitle ){
      memcpy(z, mem.zTitle, mem.nTitle);
    }
    pHdr->iSize = nByte;
    adjustStats(nByte, +1);
    pInt = (int*)&pHdr[1];
    pInt[nReserve/sizeof(int)] = REARGUARD;
    randomFill((char*)pInt, nByte);
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
    p = (void*)pInt;
  }
  sqlite4_mutex_leave(mem.mutex);
  return p; 
}

/*
** Free memory.
*/
static void sqlite4MemFree(void *pPrior){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;

  assert( sqlite4DefaultEnv.bMemstat || sqlite4DefaultEnv.bCoreMutex==0 
       || mem.mutex!=0 );
  pHdr = sqlite4MemsysGetHeader(pPrior);
  pBt = (void**)pHdr;
  pBt -= pHdr->nBacktraceSlots;
  sqlite4_mutex_enter(mem.mutex);
  if( pHdr->pPrev ){
    assert( pHdr->pPrev->pNext==pHdr );
    pHdr->pPrev->pNext = pHdr->pNext;
  }else{
    assert( mem.pFirst==pHdr );
    mem.pFirst = pHdr->pNext;
  }
  if( pHdr->pNext ){
    assert( pHdr->pNext->pPrev==pHdr );
    pHdr->pNext->pPrev = pHdr->pPrev;
  }else{
    assert( mem.pLast==pHdr );
    mem.pLast = pHdr->pPrev;
  }
  z = (char*)pBt;
  z -= pHdr->nTitle;
  adjustStats(pHdr->iSize, -1);
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
  free(z);
  sqlite4_mutex_leave(mem.mutex);  
}

/*
** Change the size of an existing memory allocation.
**
** 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.
*/
static void *sqlite4MemRealloc(void *pPrior, int nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;

  assert( mem.disallow==0 );
  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
  pOldHdr = sqlite4MemsysGetHeader(pPrior);
  pNew = sqlite4MemMalloc(nByte);
  if( pNew ){
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
    if( nByte>pOldHdr->iSize ){
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
    }
    sqlite4MemFree(pPrior);
  }
  return pNew;
}

/*
** Populate the low-level memory allocation function pointers in
** sqlite4DefaultEnv.m with pointers to the routines in this file.
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

/*
** Set the "type" of an allocation.
*/
void sqlite4MemdebugSetType(void *p, u8 eType){
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
................................................................................
** A value of zero turns off backtracing.  The number is always rounded
** up to a multiple of 2.
*/
void sqlite4MemdebugBacktrace(int depth){
  if( depth<0 ){ depth = 0; }
  if( depth>20 ){ depth = 20; }
  depth = (depth+1)&0xfe;
  mem.nBacktrace = depth;
}

void sqlite4MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  mem.xBacktrace = xBacktrace;
}

/*
** Set the title string for subsequent allocations.
*/
void sqlite4MemdebugSettitle(const char *zTitle){
  unsigned int n = sqlite4Strlen30(zTitle) + 1;
  sqlite4_mutex_enter(mem.mutex);
  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  memcpy(mem.zTitle, zTitle, n);
  mem.zTitle[n] = 0;
  mem.nTitle = ROUND8(n);
  sqlite4_mutex_leave(mem.mutex);
}

void sqlite4MemdebugSync(){
  struct MemBlockHdr *pHdr;
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    void **pBt = (void**)pHdr;
    pBt -= pHdr->nBacktraceSlots;
    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  }
}

/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
................................................................................
  int i;
  out = fopen(zFilename, "w");
  if( out==0 ){
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                    zFilename);
    return;
  }
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    char *z = (char*)pHdr;
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
    if( pHdr->nBacktrace ){
      fflush(out);
      pBt = (void**)pHdr;
................................................................................
      pBt -= pHdr->nBacktraceSlots;
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
      fprintf(out, "\n");
    }
  }
  fprintf(out, "COUNTS:\n");
  for(i=0; i<NCSIZE-1; i++){
    if( mem.nAlloc[i] ){
      fprintf(out, "   %5d: %10d %10d %10d\n", 
            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
    }
  }
  if( mem.nAlloc[NCSIZE-1] ){
    fprintf(out, "   %5d: %10d %10d %10d\n",
             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  }
  fclose(out);
}

/*
** Return the number of times sqlite4MemMalloc() has been called.
*/
int sqlite4MemdebugMallocCount(){
  int i;
  int nTotal = 0;
  for(i=0; i<NCSIZE; i++){
    nTotal += mem.nAlloc[i];
  }
  return nTotal;
}


#endif /* SQLITE_MEMDEBUG */







|











|
|
|
|


|
|







 







|

>










|
|




|







|
|
|
<
<
<
<
<
<
<







 







|







|
|


|
>



|
|

|
|
|

|

|


|
|
|

|


|
|




|
|









|






|



>

|



|




|
|





|
|







|











|


>
|


|





|







 







<


|
>
>

<
>







 







|



|







|
|
|
|
|
|




|


|







 







|







 







|

|


|

|
|











|






116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
169
170
171
172
173
174
175
176
177
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
...
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
254
255
256
257
258
259
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
343
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
370
371
372

373
374
375
376
377
378
379
380
...
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
...
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
...
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  ** bytes.  i==NCSIZE is the number of allocation attempts for
  ** sizes more than NCSIZE*8 bytes.
  */
  int nAlloc[NCSIZE];      /* Total number of allocations */
  int nCurrent[NCSIZE];    /* Current number of allocations */
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */

} mem2;


/*
** Adjust memory usage statistics
*/
static void adjustStats(int iSize, int increment){
  int i = ROUND8(iSize)/8;
  if( i>NCSIZE-1 ){
    i = NCSIZE - 1;
  }
  if( increment>0 ){
    mem2.nAlloc[i]++;
    mem2.nCurrent[i]++;
    if( mem2.nCurrent[i]>mem2.mxCurrent[i] ){
      mem2.mxCurrent[i] = mem2.nCurrent[i];
    }
  }else{
    mem2.nCurrent[i]--;
    assert( mem2.nCurrent[i]>=0 );
  }
}

/*
** Given an allocation, find the MemBlockHdr for that allocation.
**
** This routine checks the guards at either end of the allocation and
................................................................................
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  return p;
}

/*
** Return the number of bytes currently allocated at address p.
*/
static int sqlite4MemSize(void *pMem, void *p){
  struct MemBlockHdr *pHdr;
  assert( pMem==(void*)&mem2 );
  if( !p ){
    return 0;
  }
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *pMem){
  assert( pMem==(void*)&mem2 );
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite4DefaultEnv.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem2.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *pMem){
  assert( pMem==(void*)&mem2 );
  mem2.mutex = 0;







}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
*/
................................................................................
    *(pBuf++) = r & 0xff;
  }
}

/*
** Allocate nByte bytes of memory.
*/
static void *sqlite4MemMalloc(void *pMem, sqlite4_size_t nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  int *pInt;
  void *p = 0;
  int totalSize;
  int nReserve;
  sqlite4_mutex_enter(mem2.mutex);
  assert( mem2.disallow==0 );
  nReserve = ROUND8(nByte);
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
               mem2.nBacktrace*sizeof(void*) + mem2.nTitle;
  assert( pMem==(void*)&mem2 );
  p = malloc(totalSize);
  if( p ){
    z = p;
    pBt = (void**)&z[mem2.nTitle];
    pHdr = (struct MemBlockHdr*)&pBt[mem2.nBacktrace];
    pHdr->pNext = 0;
    pHdr->pPrev = mem2.pLast;
    if( mem2.pLast ){
      mem2.pLast->pNext = pHdr;
    }else{
      mem2.pFirst = pHdr;
    }
    mem2.pLast = pHdr;
    pHdr->iForeGuard = FOREGUARD;
    pHdr->eType = MEMTYPE_HEAP;
    pHdr->nBacktraceSlots = mem2.nBacktrace;
    pHdr->nTitle = mem2.nTitle;
    if( mem2.nBacktrace ){
      void *aAddr[40];
      pHdr->nBacktrace = backtrace(aAddr, mem2.nBacktrace+1)-1;
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
      assert(pBt[0]);
      if( mem2.xBacktrace ){
        mem2.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
      }
    }else{
      pHdr->nBacktrace = 0;
    }
    if( mem2.nTitle ){
      memcpy(z, mem2.zTitle, mem2.nTitle);
    }
    pHdr->iSize = nByte;
    adjustStats(nByte, +1);
    pInt = (int*)&pHdr[1];
    pInt[nReserve/sizeof(int)] = REARGUARD;
    randomFill((char*)pInt, nByte);
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
    p = (void*)pInt;
  }
  sqlite4_mutex_leave(mem2.mutex);
  return p; 
}

/*
** Free memory.
*/
static void sqlite4MemFree(void *pMem, void *pPrior){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  assert( pMem==(void*)&mem2 );
  assert( sqlite4DefaultEnv.bMemstat || sqlite4DefaultEnv.bCoreMutex==0 
       || mem2.mutex!=0 );
  pHdr = sqlite4MemsysGetHeader(pPrior);
  pBt = (void**)pHdr;
  pBt -= pHdr->nBacktraceSlots;
  sqlite4_mutex_enter(mem2.mutex);
  if( pHdr->pPrev ){
    assert( pHdr->pPrev->pNext==pHdr );
    pHdr->pPrev->pNext = pHdr->pNext;
  }else{
    assert( mem2.pFirst==pHdr );
    mem2.pFirst = pHdr->pNext;
  }
  if( pHdr->pNext ){
    assert( pHdr->pNext->pPrev==pHdr );
    pHdr->pNext->pPrev = pHdr->pPrev;
  }else{
    assert( mem2.pLast==pHdr );
    mem2.pLast = pHdr->pPrev;
  }
  z = (char*)pBt;
  z -= pHdr->nTitle;
  adjustStats(pHdr->iSize, -1);
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
  free(z);
  sqlite4_mutex_leave(mem2.mutex);  
}

/*
** Change the size of an existing memory allocation.
**
** 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.
*/
static void *sqlite4MemRealloc(void *p, void *pPrior, sqlite4_size_t nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;
  assert( p==(void*)&mem2 );
  assert( mem2.disallow==0 );
  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
  pOldHdr = sqlite4MemsysGetHeader(pPrior);
  pNew = sqlite4MemMalloc(p, nByte);
  if( pNew ){
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
    if( nByte>pOldHdr->iSize ){
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
    }
    sqlite4MemFree(p, pPrior);
  }
  return pNew;
}

/*
** Populate the low-level memory allocation function pointers in
** sqlite4DefaultEnv.m with pointers to the routines in this file.
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     &mem2
  };

  pEnv->m = defaultMethods;
}

/*
** Set the "type" of an allocation.
*/
void sqlite4MemdebugSetType(void *p, u8 eType){
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
................................................................................
** A value of zero turns off backtracing.  The number is always rounded
** up to a multiple of 2.
*/
void sqlite4MemdebugBacktrace(int depth){
  if( depth<0 ){ depth = 0; }
  if( depth>20 ){ depth = 20; }
  depth = (depth+1)&0xfe;
  mem2.nBacktrace = depth;
}

void sqlite4MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  mem2.xBacktrace = xBacktrace;
}

/*
** Set the title string for subsequent allocations.
*/
void sqlite4MemdebugSettitle(const char *zTitle){
  unsigned int n = sqlite4Strlen30(zTitle) + 1;
  sqlite4_mutex_enter(mem2.mutex);
  if( n>=sizeof(mem2.zTitle) ) n = sizeof(mem2.zTitle)-1;
  memcpy(mem2.zTitle, zTitle, n);
  mem2.zTitle[n] = 0;
  mem2.nTitle = ROUND8(n);
  sqlite4_mutex_leave(mem2.mutex);
}

void sqlite4MemdebugSync(){
  struct MemBlockHdr *pHdr;
  for(pHdr=mem2.pFirst; pHdr; pHdr=pHdr->pNext){
    void **pBt = (void**)pHdr;
    pBt -= pHdr->nBacktraceSlots;
    mem2.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  }
}

/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
................................................................................
  int i;
  out = fopen(zFilename, "w");
  if( out==0 ){
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                    zFilename);
    return;
  }
  for(pHdr=mem2.pFirst; pHdr; pHdr=pHdr->pNext){
    char *z = (char*)pHdr;
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
    if( pHdr->nBacktrace ){
      fflush(out);
      pBt = (void**)pHdr;
................................................................................
      pBt -= pHdr->nBacktraceSlots;
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
      fprintf(out, "\n");
    }
  }
  fprintf(out, "COUNTS:\n");
  for(i=0; i<NCSIZE-1; i++){
    if( mem2.nAlloc[i] ){
      fprintf(out, "   %5d: %10d %10d %10d\n", 
            i*8, mem2.nAlloc[i], mem2.nCurrent[i], mem2.mxCurrent[i]);
    }
  }
  if( mem2.nAlloc[NCSIZE-1] ){
    fprintf(out, "   %5d: %10d %10d %10d\n",
             NCSIZE*8-8, mem2.nAlloc[NCSIZE-1],
             mem2.nCurrent[NCSIZE-1], mem2.mxCurrent[NCSIZE-1]);
  }
  fclose(out);
}

/*
** Return the number of times sqlite4MemMalloc() has been called.
*/
int sqlite4MemdebugMallocCount(){
  int i;
  int nTotal = 0;
  for(i=0; i<NCSIZE; i++){
    nTotal += mem2.nAlloc[i];
  }
  return nTotal;
}


#endif /* SQLITE_MEMDEBUG */

Changes to src/printf.c.

885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
** Oops:  The first two arguments of sqlite4_snprintf() are backwards
** from the snprintf() standard.  Unfortunately, it is too late to change
** this without breaking compatibility, so we just have to live with the
** mistake.
**
** sqlite4_vsnprintf() is the varargs version.
*/
sqlite_size_t sqlite4_vsnprintf(
  char *zBuf,              /* Write results here */
  sqlite_size_t n,         /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */
  va_list ap               /* Arguments */
){
  StrAccum acc;
  if( n<=0 ) return 0;
  sqlite4StrAccumInit(&acc, zBuf, n, 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  sqlite4StrAccumFinish(&acc);
  return acc.nChar;
}
sqlite_size_t sqlite4_snprintf(
  char *zBuf,              /* Write results here */
  sqlite_size_t n,         /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */
  ...                      /* Arguments */
){
  va_list ap;
  va_start(ap,zFormat);
  n = sqlite4_vsnprintf(zBuf, n, zFormat, ap);
  va_end(ap);







|

|











|

|







885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
** Oops:  The first two arguments of sqlite4_snprintf() are backwards
** from the snprintf() standard.  Unfortunately, it is too late to change
** this without breaking compatibility, so we just have to live with the
** mistake.
**
** sqlite4_vsnprintf() is the varargs version.
*/
sqlite4_size_t sqlite4_vsnprintf(
  char *zBuf,              /* Write results here */
  sqlite4_size_t n,        /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */
  va_list ap               /* Arguments */
){
  StrAccum acc;
  if( n<=0 ) return 0;
  sqlite4StrAccumInit(&acc, zBuf, n, 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  sqlite4StrAccumFinish(&acc);
  return acc.nChar;
}
sqlite4_size_t sqlite4_snprintf(
  char *zBuf,              /* Write results here */
  sqlite4_size_t n,        /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */
  ...                      /* Arguments */
){
  va_list ap;
  va_start(ap,zFormat);
  n = sqlite4_vsnprintf(zBuf, n, zFormat, ap);
  va_end(ap);

Changes to src/sqlite.h.in.

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
...
703
704
705
706
707
708
709
710
711
712
713
714
715
716


717
718
719
720
721
722
723
724
....
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
....
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315

/*
** CAPIREF: String length type
**
** A type for measuring the length of the string.  Like size_t but
** does not require &lt;stddef.h&gt;
*/
typedef int sqlite_size_t;

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite4_int64
................................................................................
** serialization.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
*/
typedef struct sqlite4_mem_methods sqlite4_mem_methods;
struct sqlite4_mem_methods {
  void *(*xMalloc)(int);         /* Memory allocation function */
  void (*xFree)(void*);          /* Free a prior allocation */
  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  int (*xSize)(void*);           /* Return the size of an allocation */
  int (*xRoundup)(int);          /* Round up request size to allocation size */
  int (*xInit)(void*);           /* Initialize the memory allocator */
  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */


  void *pAppData;                /* Argument to xInit() and xShutdown() */
};

/*
** CAPIREF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
................................................................................
**
** ^(The "%z" formatting option works like "%s" but with the
** addition that after the string has been read and copied into
** the result, [sqlite4_free()] is called on the input string.)^
*/
char *sqlite4_mprintf(sqlite4_env*, const char*,...);
char *sqlite4_vmprintf(sqlite4_env*, const char*, va_list);
sqlite_size_t sqlite4_snprintf(char*,sqlite_size_t,const char*, ...);
sqlite_size_t sqlite4_vsnprintf(char*,sqlite_size_t,const char*, va_list);

/*
** CAPIREF: Memory Allocation Subsystem
**
** The SQLite core uses these three routines for all of its own
** internal memory allocation needs.
**
................................................................................
** invocation of [sqlite4_malloc()] or [sqlite4_realloc()] that have
** not yet been released.
**
** The application must not read or write any part of
** a block of memory after it has been released using
** [sqlite4_free()] or [sqlite4_realloc()].
*/
void *sqlite4_malloc(sqlite4_env*, int);
void *sqlite4_realloc(sqlite4_env*, void*, int);
void sqlite4_free(sqlite4_env*, void*);

/*
** CAPIREF: Memory Allocator Statistics
**
** SQLite provides these two interfaces for reporting on the status
** of the [sqlite4_malloc()], [sqlite4_free()], and [sqlite4_realloc()]







|







 







|
|
|
|
<
|
|
>
>
|







 







|
|







 







|
|







284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
...
703
704
705
706
707
708
709
710
711
712
713

714
715
716
717
718
719
720
721
722
723
724
725
....
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
....
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316

/*
** CAPIREF: String length type
**
** A type for measuring the length of the string.  Like size_t but
** does not require &lt;stddef.h&gt;
*/
typedef int sqlite4_size_t;

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite4_int64
................................................................................
** serialization.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
*/
typedef struct sqlite4_mem_methods sqlite4_mem_methods;
struct sqlite4_mem_methods {
  void *(*xMalloc)(void*,sqlite4_size_t); /* Memory allocation function */
  void (*xFree)(void*,void*);             /* Free a prior allocation */
  void *(*xRealloc)(void*,void*,int);     /* Resize an allocation */
  sqlite4_size_t (*xSize)(void*,void*);   /* Return the size of an allocation */

  int (*xInit)(void*);                    /* Initialize the memory allocator */
  void (*xShutdown)(void*);               /* Deinitialize the allocator */
  void (*xBeginBenign)(void*);            /* Enter a benign malloc region */
  void (*xEndBenign)(void*);              /* Leave a benign malloc region */
  void *pAppData;                         /* 1st argument to all routines */
};

/*
** CAPIREF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
................................................................................
**
** ^(The "%z" formatting option works like "%s" but with the
** addition that after the string has been read and copied into
** the result, [sqlite4_free()] is called on the input string.)^
*/
char *sqlite4_mprintf(sqlite4_env*, const char*,...);
char *sqlite4_vmprintf(sqlite4_env*, const char*, va_list);
sqlite4_size_t sqlite4_snprintf(char*,sqlite4_size_t,const char*, ...);
sqlite4_size_t sqlite4_vsnprintf(char*,sqlite4_size_t,const char*, va_list);

/*
** CAPIREF: Memory Allocation Subsystem
**
** The SQLite core uses these three routines for all of its own
** internal memory allocation needs.
**
................................................................................
** invocation of [sqlite4_malloc()] or [sqlite4_realloc()] that have
** not yet been released.
**
** The application must not read or write any part of
** a block of memory after it has been released using
** [sqlite4_free()] or [sqlite4_realloc()].
*/
void *sqlite4_malloc(sqlite4_env*, sqlite4_size_t);
void *sqlite4_realloc(sqlite4_env*, void*, sqlite4_size_t);
void sqlite4_free(sqlite4_env*, void*);

/*
** CAPIREF: Memory Allocator Statistics
**
** SQLite provides these two interfaces for reporting on the status
** of the [sqlite4_malloc()], [sqlite4_free()], and [sqlite4_realloc()]

Changes to src/sqliteInt.h.

2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
/*
** Internal function prototypes
*/
int sqlite4StrICmp(const char *, const char *);
int sqlite4Strlen30(const char*);
#define sqlite4StrNICmp sqlite4_strnicmp

int sqlite4MallocInit(void);
void sqlite4MallocEnd(void);
void *sqlite4Malloc(sqlite4_env*, int);
void *sqlite4MallocZero(sqlite4_env*, int);
void *sqlite4DbMallocZero(sqlite4*, int);
void *sqlite4DbMallocRaw(sqlite4*, int);
char *sqlite4DbStrDup(sqlite4*,const char*);
char *sqlite4DbStrNDup(sqlite4*,const char*, int);
void *sqlite4Realloc(sqlite4_env*, void*, int);
void *sqlite4DbReallocOrFree(sqlite4 *, void *, int);
void *sqlite4DbRealloc(sqlite4 *, void *, int);
void sqlite4DbFree(sqlite4*, void*);
int sqlite4MallocSize(sqlite4_env*, void*);
int sqlite4DbMallocSize(sqlite4*, void*);
void *sqlite4ScratchMalloc(int);
void sqlite4ScratchFree(void*);
void *sqlite4PageMalloc(int);
void sqlite4PageFree(void*);
void sqlite4MemSetDefault(sqlite4_env*);
void sqlite4BenignMallocHooks(sqlite4_env*,void (*)(void), void (*)(void));

/*
** On systems with ample stack space and that support alloca(), make
** use of alloca() to obtain space for large automatic objects.  By default,
** obtain space from malloc().







|
|












<
<
<
<







2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542




2543
2544
2545
2546
2547
2548
2549
/*
** Internal function prototypes
*/
int sqlite4StrICmp(const char *, const char *);
int sqlite4Strlen30(const char*);
#define sqlite4StrNICmp sqlite4_strnicmp

int sqlite4MallocInit(sqlite4_env*);
void sqlite4MallocEnd(sqlite4_env*);
void *sqlite4Malloc(sqlite4_env*, int);
void *sqlite4MallocZero(sqlite4_env*, int);
void *sqlite4DbMallocZero(sqlite4*, int);
void *sqlite4DbMallocRaw(sqlite4*, int);
char *sqlite4DbStrDup(sqlite4*,const char*);
char *sqlite4DbStrNDup(sqlite4*,const char*, int);
void *sqlite4Realloc(sqlite4_env*, void*, int);
void *sqlite4DbReallocOrFree(sqlite4 *, void *, int);
void *sqlite4DbRealloc(sqlite4 *, void *, int);
void sqlite4DbFree(sqlite4*, void*);
int sqlite4MallocSize(sqlite4_env*, void*);
int sqlite4DbMallocSize(sqlite4*, void*);




void sqlite4MemSetDefault(sqlite4_env*);
void sqlite4BenignMallocHooks(sqlite4_env*,void (*)(void), void (*)(void));

/*
** On systems with ample stack space and that support alloca(), make
** use of alloca() to obtain space for large automatic objects.  By default,
** obtain space from malloc().

Changes to src/status.c.

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

      db->pnBytesFreed = &nByte;
      for(i=0; i<db->nDb; i++){
        Schema *pSchema = db->aDb[i].pSchema;
        if( ALWAYS(pSchema!=0) ){
          HashElem *p;

          nByte += pEnv->m.xRoundup(sizeof(HashElem)) * (
              pSchema->tblHash.count 
            + pSchema->trigHash.count
            + pSchema->idxHash.count
            + pSchema->fkeyHash.count
          );
          nByte += sqlite4MallocSize(pEnv, pSchema->tblHash.ht);
          nByte += sqlite4MallocSize(pEnv, pSchema->trigHash.ht);







|







128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

      db->pnBytesFreed = &nByte;
      for(i=0; i<db->nDb; i++){
        Schema *pSchema = db->aDb[i].pSchema;
        if( ALWAYS(pSchema!=0) ){
          HashElem *p;

          nByte += sizeof(HashElem) * (
              pSchema->tblHash.count 
            + pSchema->trigHash.count
            + pSchema->idxHash.count
            + pSchema->fkeyHash.count
          );
          nByte += sqlite4MallocSize(pEnv, pSchema->tblHash.ht);
          nByte += sqlite4MallocSize(pEnv, pSchema->trigHash.ht);

Changes to test/test_main.c.

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

/*
** Check a return value to make sure it agrees with the results
** from sqlite4_errcode.
*/
int sqlite4TestErrCode(Tcl_Interp *interp, sqlite4 *db, int rc){
  sqlite4_env *pEnv = sqlite4_db_env(db);
  if( sqlite4_threadsafe(pEnv)==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK
   && sqlite4_errcode(db)!=rc ){
    char zBuf[200];
    int r2 = sqlite4_errcode(db);
    sprintf(zBuf, "error code %s (%d) does not match sqlite4_errcode %s (%d)",
       t1ErrorName(rc), rc, t1ErrorName(r2), r2);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, zBuf, 0);
    return 1;







<
|







181
182
183
184
185
186
187

188
189
190
191
192
193
194
195

/*
** Check a return value to make sure it agrees with the results
** from sqlite4_errcode.
*/
int sqlite4TestErrCode(Tcl_Interp *interp, sqlite4 *db, int rc){
  sqlite4_env *pEnv = sqlite4_db_env(db);

  if( rc!=SQLITE_MISUSE && rc!=SQLITE_OK && sqlite4_errcode(db)!=rc ){
    char zBuf[200];
    int r2 = sqlite4_errcode(db);
    sprintf(zBuf, "error code %s (%d) does not match sqlite4_errcode %s (%d)",
       t1ErrorName(rc), rc, t1ErrorName(r2), r2);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, zBuf, 0);
    return 1;

Changes to test/test_malloc.c.

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
102
103
104
105

106
107
108

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
...
166
167
168
169
170
171
172
173
174
175
176
177
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
  return 1;  
}

/*
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(int n){
  void *p = 0;

  if( !faultsimStep() ){
    p = memfault.m.xMalloc(n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pOld, int n){
  void *p = 0;

  if( !faultsimStep() ){
    p = memfault.m.xRealloc(pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
**
**     xFree
**     xSize
**     xRoundup
**     xInit
**     xShutdown
*/
static void faultsimFree(void *p){

  memfault.m.xFree(p);
}
static int faultsimSize(void *p){

  return memfault.m.xSize(p);
}
static int faultsimRoundup(int n){
  return memfault.m.xRoundup(n);
}
static int faultsimInit(void *p){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *p){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
................................................................................
    return memfault.iCountdown;
  }else{
    return -1;
  }
}


static void faultsimBeginBenign(void){
  memfault.isBenignMode++;
}
static void faultsimEndBenign(void){
  memfault.isBenignMode--;
}

/*
** Add or remove the fault-simulation layer using sqlite4_env_config(). If
** the argument is non-zero, the 
*/
static int faultsimInstall(int install){
  static struct sqlite4_mem_methods m = {
    faultsimMalloc,                   /* xMalloc */
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */
    faultsimRoundup,                  /* xRoundup */
    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */


    0                                 /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
    return SQLITE_ERROR;
  }

  if( install ){

    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign







|

>

|









|

>

|










<



|
>
|

|
>
|

<
<
<
|


|







 







|


|













<


>
>
|











>







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
102

103
104
105
106
107
108
109
110
111
112
113



114
115
116
117
118
119
120
121
122
123
124
...
166
167
168
169
170
171
172
173
174
175
176
177
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
  return 1;  
}

/*
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(void *pMem, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xMalloc(memfault.m.pAppData, n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pMem, void *pOld, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xRealloc(memfault.m.pAppData, pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
**
**     xFree
**     xSize

**     xInit
**     xShutdown
*/
static void faultsimFree(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  memfault.m.xFree(memfault.m.pAppData, p);
}
static sqlite4_size_t faultsimSize(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  return memfault.m.xSize(memfault.m.pAppData, p);
}



static int faultsimInit(void *pMem){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *pMem){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
................................................................................
    return memfault.iCountdown;
  }else{
    return -1;
  }
}


static void faultsimBeginBenign(void *pMem){
  memfault.isBenignMode++;
}
static void faultsimEndBenign(void *pMem){
  memfault.isBenignMode--;
}

/*
** Add or remove the fault-simulation layer using sqlite4_env_config(). If
** the argument is non-zero, the 
*/
static int faultsimInstall(int install){
  static struct sqlite4_mem_methods m = {
    faultsimMalloc,                   /* xMalloc */
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */

    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */
    faultsimBeginBenign,              /* xBeginBenign */
    faultsimEndBenign,                /* xEndBenign */
    (void*)&memfault                  /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
    return SQLITE_ERROR;
  }

  if( install ){
    sqlite4_initialize(0);
    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign