xref: /sqlite-3.40.0/src/malloc.c (revision ccd4ad3e)
1a3152895Sdrh /*
2a3152895Sdrh ** 2001 September 15
3a3152895Sdrh **
4a3152895Sdrh ** The author disclaims copyright to this source code.  In place of
5a3152895Sdrh ** a legal notice, here is a blessing:
6a3152895Sdrh **
7a3152895Sdrh **    May you do good and not evil.
8a3152895Sdrh **    May you find forgiveness for yourself and forgive others.
9a3152895Sdrh **    May you share freely, never taking more than you give.
10a3152895Sdrh **
11a3152895Sdrh *************************************************************************
12fec00eabSdrh **
13a3152895Sdrh ** Memory allocation functions used throughout sqlite.
14a3152895Sdrh */
15a3152895Sdrh #include "sqliteInt.h"
16a3152895Sdrh #include <stdarg.h>
17a3152895Sdrh 
18a3152895Sdrh /*
19b21c8cd4Sdrh ** This routine runs when the memory allocator sees that the
20b21c8cd4Sdrh ** total memory allocation is about to exceed the soft heap
21b21c8cd4Sdrh ** limit.
22b21c8cd4Sdrh */
23b21c8cd4Sdrh static void softHeapLimitEnforcer(
24b21c8cd4Sdrh   void *NotUsed,
2562c14b34Sdanielk1977   sqlite3_int64 NotUsed2,
26153c62c4Sdrh   int allocSize
27b21c8cd4Sdrh ){
2862c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
29b21c8cd4Sdrh   sqlite3_release_memory(allocSize);
30b21c8cd4Sdrh }
31b21c8cd4Sdrh 
32b21c8cd4Sdrh /*
338468024dSdanielk1977 ** Set the soft heap-size limit for the library. Passing a zero or
348468024dSdanielk1977 ** negative value indicates no limit.
35a3152895Sdrh */
36a3152895Sdrh void sqlite3_soft_heap_limit(int n){
37b21c8cd4Sdrh   sqlite3_uint64 iLimit;
38b21c8cd4Sdrh   int overage;
39b21c8cd4Sdrh   if( n<0 ){
40b21c8cd4Sdrh     iLimit = 0;
41b21c8cd4Sdrh   }else{
42b21c8cd4Sdrh     iLimit = n;
43a3152895Sdrh   }
449ac06509Sdrh #ifndef SQLITE_OMIT_AUTOINIT
459ac3fe97Sdrh   sqlite3_initialize();
469ac06509Sdrh #endif
47b21c8cd4Sdrh   if( iLimit>0 ){
484a27a286Sshane     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
49b21c8cd4Sdrh   }else{
504a27a286Sshane     sqlite3MemoryAlarm(0, 0, 0);
51b21c8cd4Sdrh   }
521bd10f8aSdrh   overage = (int)(sqlite3_memory_used() - (i64)n);
53b21c8cd4Sdrh   if( overage>0 ){
54b21c8cd4Sdrh     sqlite3_release_memory(overage);
55b21c8cd4Sdrh   }
56a3152895Sdrh }
57a3152895Sdrh 
58a3152895Sdrh /*
598468024dSdanielk1977 ** Attempt to release up to n bytes of non-essential memory currently
608468024dSdanielk1977 ** held by SQLite. An example of non-essential memory is memory used to
618468024dSdanielk1977 ** cache database pages that are not currently in use.
62a3152895Sdrh */
63a3152895Sdrh int sqlite3_release_memory(int n){
6486f8c197Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
6567e3da7aSdanielk1977   int nRet = 0;
6667e3da7aSdanielk1977   nRet += sqlite3PcacheReleaseMemory(n-nRet);
67dfb316d4Sdanielk1977   return nRet;
681e536953Sdanielk1977 #else
6962c14b34Sdanielk1977   UNUSED_PARAMETER(n);
701e536953Sdanielk1977   return SQLITE_OK;
711e536953Sdanielk1977 #endif
72a3152895Sdrh }
73a3152895Sdrh 
74fec00eabSdrh /*
75fec00eabSdrh ** State information local to the memory allocation subsystem.
76fec00eabSdrh */
775c8f8587Sdanielk1977 static SQLITE_WSD struct Mem0Global {
7823bf0f41Sdanielk1977   /* Number of free pages for scratch and page-cache memory */
7923bf0f41Sdanielk1977   u32 nScratchFree;
8023bf0f41Sdanielk1977   u32 nPageFree;
8123bf0f41Sdanielk1977 
82fec00eabSdrh   sqlite3_mutex *mutex;         /* Mutex to serialize access */
83fec00eabSdrh 
84fec00eabSdrh   /*
85fec00eabSdrh   ** The alarm callback and its arguments.  The mem0.mutex lock will
86fec00eabSdrh   ** be held while the callback is running.  Recursive calls into
87fec00eabSdrh   ** the memory subsystem are allowed, but no new callbacks will be
88e64ca7baSdrh   ** issued.
89fec00eabSdrh   */
90fec00eabSdrh   sqlite3_int64 alarmThreshold;
91fec00eabSdrh   void (*alarmCallback)(void*, sqlite3_int64,int);
92fec00eabSdrh   void *alarmArg;
93fec00eabSdrh 
94fec00eabSdrh   /*
95075c23afSdanielk1977   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
96075c23afSdanielk1977   ** sqlite3GlobalConfig.pPage to a block of memory that records
979ac3fe97Sdrh   ** which pages are available.
989ac3fe97Sdrh   */
999ac3fe97Sdrh   u32 *aScratchFree;
1009ac3fe97Sdrh   u32 *aPageFree;
101e64ca7baSdrh } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
1025c8f8587Sdanielk1977 
1035c8f8587Sdanielk1977 #define mem0 GLOBAL(struct Mem0Global, mem0)
104fec00eabSdrh 
105fec00eabSdrh /*
106fec00eabSdrh ** Initialize the memory allocation subsystem.
107fec00eabSdrh */
108fec00eabSdrh int sqlite3MallocInit(void){
109075c23afSdanielk1977   if( sqlite3GlobalConfig.m.xMalloc==0 ){
110fec00eabSdrh     sqlite3MemSetDefault();
111fec00eabSdrh   }
112fec00eabSdrh   memset(&mem0, 0, sizeof(mem0));
113075c23afSdanielk1977   if( sqlite3GlobalConfig.bCoreMutex ){
11459f8c08eSdanielk1977     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
115fec00eabSdrh   }
116075c23afSdanielk1977   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
117075c23afSdanielk1977       && sqlite3GlobalConfig.nScratch>=0 ){
1189ac3fe97Sdrh     int i;
119bc73971dSdanielk1977     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
120075c23afSdanielk1977     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
121075c23afSdanielk1977                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
122075c23afSdanielk1977     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
123075c23afSdanielk1977     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
1249ac3fe97Sdrh   }else{
125075c23afSdanielk1977     sqlite3GlobalConfig.pScratch = 0;
126075c23afSdanielk1977     sqlite3GlobalConfig.szScratch = 0;
1279ac3fe97Sdrh   }
128075c23afSdanielk1977   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
129075c23afSdanielk1977       && sqlite3GlobalConfig.nPage>=1 ){
1309ac3fe97Sdrh     int i;
1310a60a384Sdrh     int overhead;
132bc73971dSdanielk1977     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
133075c23afSdanielk1977     int n = sqlite3GlobalConfig.nPage;
1340a60a384Sdrh     overhead = (4*n + sz - 1)/sz;
135075c23afSdanielk1977     sqlite3GlobalConfig.nPage -= overhead;
136075c23afSdanielk1977     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
137075c23afSdanielk1977                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
138075c23afSdanielk1977     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
139075c23afSdanielk1977     mem0.nPageFree = sqlite3GlobalConfig.nPage;
1409ac3fe97Sdrh   }else{
141075c23afSdanielk1977     sqlite3GlobalConfig.pPage = 0;
142075c23afSdanielk1977     sqlite3GlobalConfig.szPage = 0;
1439ac3fe97Sdrh   }
144075c23afSdanielk1977   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
145fec00eabSdrh }
146fec00eabSdrh 
147fec00eabSdrh /*
148fec00eabSdrh ** Deinitialize the memory allocation subsystem.
149fec00eabSdrh */
150fec00eabSdrh void sqlite3MallocEnd(void){
1510a549071Sdanielk1977   if( sqlite3GlobalConfig.m.xShutdown ){
152075c23afSdanielk1977     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
1530a549071Sdanielk1977   }
1549ac3fe97Sdrh   memset(&mem0, 0, sizeof(mem0));
155fec00eabSdrh }
156fec00eabSdrh 
157fec00eabSdrh /*
158fec00eabSdrh ** Return the amount of memory currently checked out.
159fec00eabSdrh */
160fec00eabSdrh sqlite3_int64 sqlite3_memory_used(void){
161f7141990Sdrh   int n, mx;
162c376a198Sdrh   sqlite3_int64 res;
163f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
164c376a198Sdrh   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
165c376a198Sdrh   return res;
166fec00eabSdrh }
167fec00eabSdrh 
168fec00eabSdrh /*
169fec00eabSdrh ** Return the maximum amount of memory that has ever been
170fec00eabSdrh ** checked out since either the beginning of this process
171fec00eabSdrh ** or since the most recent reset.
172fec00eabSdrh */
173fec00eabSdrh sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
174f7141990Sdrh   int n, mx;
175c376a198Sdrh   sqlite3_int64 res;
176f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
1777986a71aSdrh   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
178c376a198Sdrh   return res;
179fec00eabSdrh }
180fec00eabSdrh 
181fec00eabSdrh /*
182fec00eabSdrh ** Change the alarm callback
183fec00eabSdrh */
1844a27a286Sshane int sqlite3MemoryAlarm(
185fec00eabSdrh   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
186fec00eabSdrh   void *pArg,
187fec00eabSdrh   sqlite3_int64 iThreshold
188fec00eabSdrh ){
189fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
190fec00eabSdrh   mem0.alarmCallback = xCallback;
191fec00eabSdrh   mem0.alarmArg = pArg;
192fec00eabSdrh   mem0.alarmThreshold = iThreshold;
193fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
194fec00eabSdrh   return SQLITE_OK;
195fec00eabSdrh }
196fec00eabSdrh 
197eec556d3Sshane #ifndef SQLITE_OMIT_DEPRECATED
198fec00eabSdrh /*
1994a27a286Sshane ** Deprecated external interface.  Internal/core SQLite code
2004a27a286Sshane ** should call sqlite3MemoryAlarm.
2014a27a286Sshane */
2024a27a286Sshane int sqlite3_memory_alarm(
2034a27a286Sshane   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
2044a27a286Sshane   void *pArg,
2054a27a286Sshane   sqlite3_int64 iThreshold
2064a27a286Sshane ){
2074a27a286Sshane   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
2084a27a286Sshane }
209eec556d3Sshane #endif
2104a27a286Sshane 
2114a27a286Sshane /*
212fec00eabSdrh ** Trigger the alarm
213fec00eabSdrh */
214fec00eabSdrh static void sqlite3MallocAlarm(int nByte){
215fec00eabSdrh   void (*xCallback)(void*,sqlite3_int64,int);
216fec00eabSdrh   sqlite3_int64 nowUsed;
217fec00eabSdrh   void *pArg;
218e64ca7baSdrh   if( mem0.alarmCallback==0 ) return;
219fec00eabSdrh   xCallback = mem0.alarmCallback;
220f7141990Sdrh   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
221fec00eabSdrh   pArg = mem0.alarmArg;
222e64ca7baSdrh   mem0.alarmCallback = 0;
223fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
224fec00eabSdrh   xCallback(pArg, nowUsed, nByte);
225fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
226e64ca7baSdrh   mem0.alarmCallback = xCallback;
227e64ca7baSdrh   mem0.alarmArg = pArg;
228fec00eabSdrh }
229fec00eabSdrh 
230fec00eabSdrh /*
231f7141990Sdrh ** Do a memory allocation with statistics and alarms.  Assume the
232f7141990Sdrh ** lock is already held.
233fec00eabSdrh */
234f7141990Sdrh static int mallocWithAlarm(int n, void **pp){
235fec00eabSdrh   int nFull;
236f7141990Sdrh   void *p;
237f7141990Sdrh   assert( sqlite3_mutex_held(mem0.mutex) );
238075c23afSdanielk1977   nFull = sqlite3GlobalConfig.m.xRoundup(n);
239f7141990Sdrh   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
240f7141990Sdrh   if( mem0.alarmCallback!=0 ){
241f7141990Sdrh     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
242f7141990Sdrh     if( nUsed+nFull >= mem0.alarmThreshold ){
243fec00eabSdrh       sqlite3MallocAlarm(nFull);
244fec00eabSdrh     }
245f7141990Sdrh   }
246075c23afSdanielk1977   p = sqlite3GlobalConfig.m.xMalloc(nFull);
247d09414cdSdanielk1977   if( p==0 && mem0.alarmCallback ){
248fec00eabSdrh     sqlite3MallocAlarm(nFull);
249075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(nFull);
250fec00eabSdrh   }
251c702c7ccSdrh   if( p ){
252c702c7ccSdrh     nFull = sqlite3MallocSize(p);
253c702c7ccSdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
254c702c7ccSdrh   }
255f7141990Sdrh   *pp = p;
256f7141990Sdrh   return nFull;
257fec00eabSdrh }
258f7141990Sdrh 
259f7141990Sdrh /*
260f7141990Sdrh ** Allocate memory.  This routine is like sqlite3_malloc() except that it
261f7141990Sdrh ** assumes the memory subsystem has already been initialized.
262f7141990Sdrh */
263f7141990Sdrh void *sqlite3Malloc(int n){
264f7141990Sdrh   void *p;
265e08ed7e7Sdrh   if( n<=0 || n>=0x7fffff00 ){
266e08ed7e7Sdrh     /* A memory allocation of a number of bytes which is near the maximum
267e08ed7e7Sdrh     ** signed integer value might cause an integer overflow inside of the
268e08ed7e7Sdrh     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
269e08ed7e7Sdrh     ** 255 bytes of overhead.  SQLite itself will never use anything near
270e08ed7e7Sdrh     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
271f7141990Sdrh     p = 0;
272075c23afSdanielk1977   }else if( sqlite3GlobalConfig.bMemstat ){
273f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
274f7141990Sdrh     mallocWithAlarm(n, &p);
275fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
276fec00eabSdrh   }else{
277075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(n);
278fec00eabSdrh   }
279fec00eabSdrh   return p;
280fec00eabSdrh }
281fec00eabSdrh 
282fec00eabSdrh /*
283fec00eabSdrh ** This version of the memory allocation is for use by the application.
284fec00eabSdrh ** First make sure the memory subsystem is initialized, then do the
285fec00eabSdrh ** allocation.
286fec00eabSdrh */
287fec00eabSdrh void *sqlite3_malloc(int n){
288fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
289fec00eabSdrh   if( sqlite3_initialize() ) return 0;
290fec00eabSdrh #endif
291fec00eabSdrh   return sqlite3Malloc(n);
292fec00eabSdrh }
293fec00eabSdrh 
294fec00eabSdrh /*
295e5ae5735Sdrh ** Each thread may only have a single outstanding allocation from
296facf0307Sdrh ** xScratchMalloc().  We verify this constraint in the single-threaded
297facf0307Sdrh ** case by setting scratchAllocOut to 1 when an allocation
298e5ae5735Sdrh ** is outstanding clearing it when the allocation is freed.
299e5ae5735Sdrh */
300e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
301facf0307Sdrh static int scratchAllocOut = 0;
302e5ae5735Sdrh #endif
303e5ae5735Sdrh 
304e5ae5735Sdrh 
305e5ae5735Sdrh /*
306e5ae5735Sdrh ** Allocate memory that is to be used and released right away.
307e5ae5735Sdrh ** This routine is similar to alloca() in that it is not intended
308e5ae5735Sdrh ** for situations where the memory might be held long-term.  This
309e5ae5735Sdrh ** routine is intended to get memory to old large transient data
310e5ae5735Sdrh ** structures that would not normally fit on the stack of an
311e5ae5735Sdrh ** embedded processor.
312e5ae5735Sdrh */
313facf0307Sdrh void *sqlite3ScratchMalloc(int n){
314e5ae5735Sdrh   void *p;
315e5ae5735Sdrh   assert( n>0 );
3169ac3fe97Sdrh 
317e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
31837f99187Sdrh   /* Verify that no more than two scratch allocation per thread
3199ac3fe97Sdrh   ** is outstanding at one time.  (This is only checked in the
3209ac3fe97Sdrh   ** single-threaded case since checking in the multi-threaded case
3219ac3fe97Sdrh   ** would be much more complicated.) */
32237f99187Sdrh   assert( scratchAllocOut<=1 );
323e5ae5735Sdrh #endif
3249ac3fe97Sdrh 
325075c23afSdanielk1977   if( sqlite3GlobalConfig.szScratch<n ){
326f7141990Sdrh     goto scratch_overflow;
327f7141990Sdrh   }else{
328e5ae5735Sdrh     sqlite3_mutex_enter(mem0.mutex);
329f7141990Sdrh     if( mem0.nScratchFree==0 ){
330f7141990Sdrh       sqlite3_mutex_leave(mem0.mutex);
331f7141990Sdrh       goto scratch_overflow;
332e5ae5735Sdrh     }else{
3339ac3fe97Sdrh       int i;
3349ac3fe97Sdrh       i = mem0.aScratchFree[--mem0.nScratchFree];
335075c23afSdanielk1977       i *= sqlite3GlobalConfig.szScratch;
336f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
337e50135e2Sdrh       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
3388183e339Sdanielk1977       sqlite3_mutex_leave(mem0.mutex);
339075c23afSdanielk1977       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
34015301596Sshane       assert(  (((u8*)p - (u8*)0) & 7)==0 );
341e5ae5735Sdrh     }
342f7141990Sdrh   }
343f7141990Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
344f7141990Sdrh   scratchAllocOut = p!=0;
345f7141990Sdrh #endif
346f7141990Sdrh 
347f7141990Sdrh   return p;
348f7141990Sdrh 
349f7141990Sdrh scratch_overflow:
350075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
351f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
352e50135e2Sdrh     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
353f7141990Sdrh     n = mallocWithAlarm(n, &p);
354f7141990Sdrh     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
3559ac3fe97Sdrh     sqlite3_mutex_leave(mem0.mutex);
356f7141990Sdrh   }else{
357075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(n);
358f7141990Sdrh   }
359107b56e8Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
360f7141990Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
361f7141990Sdrh   scratchAllocOut = p!=0;
362f7141990Sdrh #endif
363e5ae5735Sdrh   return p;
364e5ae5735Sdrh }
365facf0307Sdrh void sqlite3ScratchFree(void *p){
366e5ae5735Sdrh   if( p ){
367075c23afSdanielk1977     if( sqlite3GlobalConfig.pScratch==0
368075c23afSdanielk1977            || p<sqlite3GlobalConfig.pScratch
3699ac3fe97Sdrh            || p>=(void*)mem0.aScratchFree ){
370107b56e8Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
371174b9a16Sdrh       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
372107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
373075c23afSdanielk1977       if( sqlite3GlobalConfig.bMemstat ){
374f7141990Sdrh         int iSize = sqlite3MallocSize(p);
375f7141990Sdrh         sqlite3_mutex_enter(mem0.mutex);
376f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
377f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
378075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
379f7141990Sdrh         sqlite3_mutex_leave(mem0.mutex);
380f7141990Sdrh       }else{
381075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
382f7141990Sdrh       }
3839ac3fe97Sdrh     }else{
3849ac3fe97Sdrh       int i;
3851bd10f8aSdrh       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
386075c23afSdanielk1977       i /= sqlite3GlobalConfig.szScratch;
387075c23afSdanielk1977       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
388f7141990Sdrh       sqlite3_mutex_enter(mem0.mutex);
38900e13613Sdanielk1977       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
3909ac3fe97Sdrh       mem0.aScratchFree[mem0.nScratchFree++] = i;
391f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
3929ac3fe97Sdrh       sqlite3_mutex_leave(mem0.mutex);
39337f99187Sdrh 
39437f99187Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
39537f99187Sdrh     /* Verify that no more than two scratch allocation per thread
39637f99187Sdrh     ** is outstanding at one time.  (This is only checked in the
39737f99187Sdrh     ** single-threaded case since checking in the multi-threaded case
39837f99187Sdrh     ** would be much more complicated.) */
39937f99187Sdrh     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
40037f99187Sdrh     scratchAllocOut = 0;
40137f99187Sdrh #endif
40237f99187Sdrh 
4039ac3fe97Sdrh     }
404e5ae5735Sdrh   }
405e5ae5735Sdrh }
406e5ae5735Sdrh 
407e5ae5735Sdrh /*
408633e6d57Sdrh ** TRUE if p is a lookaside memory allocation from db
409633e6d57Sdrh */
4104150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
411633e6d57Sdrh static int isLookaside(sqlite3 *db, void *p){
412174b9a16Sdrh   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
413633e6d57Sdrh }
4144150ebf8Sdrh #else
4154150ebf8Sdrh #define isLookaside(A,B) 0
4164150ebf8Sdrh #endif
417633e6d57Sdrh 
418633e6d57Sdrh /*
419fec00eabSdrh ** Return the size of a memory allocation previously obtained from
420fec00eabSdrh ** sqlite3Malloc() or sqlite3_malloc().
421fec00eabSdrh */
422fec00eabSdrh int sqlite3MallocSize(void *p){
423107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
424174b9a16Sdrh   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
425075c23afSdanielk1977   return sqlite3GlobalConfig.m.xSize(p);
426fec00eabSdrh }
427633e6d57Sdrh int sqlite3DbMallocSize(sqlite3 *db, void *p){
4287047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
429174b9a16Sdrh   if( db && isLookaside(db, p) ){
430633e6d57Sdrh     return db->lookaside.sz;
431633e6d57Sdrh   }else{
432174b9a16Sdrh     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
433174b9a16Sdrh     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
434174b9a16Sdrh     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
435075c23afSdanielk1977     return sqlite3GlobalConfig.m.xSize(p);
436633e6d57Sdrh   }
437633e6d57Sdrh }
438fec00eabSdrh 
439fec00eabSdrh /*
440fec00eabSdrh ** Free memory previously obtained from sqlite3Malloc().
441fec00eabSdrh */
442fec00eabSdrh void sqlite3_free(void *p){
443fec00eabSdrh   if( p==0 ) return;
444174b9a16Sdrh   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
445107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
446075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
447fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
448f7141990Sdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
449075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
450fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
451fec00eabSdrh   }else{
452075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
453fec00eabSdrh   }
454fec00eabSdrh }
455fec00eabSdrh 
456fec00eabSdrh /*
457633e6d57Sdrh ** Free memory that might be associated with a particular database
458633e6d57Sdrh ** connection.
459633e6d57Sdrh */
460633e6d57Sdrh void sqlite3DbFree(sqlite3 *db, void *p){
4617047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
462174b9a16Sdrh   if( db ){
463174b9a16Sdrh     if( db->pnBytesFreed ){
464174b9a16Sdrh       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
465174b9a16Sdrh       return;
466d46def77Sdan     }
467633e6d57Sdrh     if( isLookaside(db, p) ){
468633e6d57Sdrh       LookasideSlot *pBuf = (LookasideSlot*)p;
469633e6d57Sdrh       pBuf->pNext = db->lookaside.pFree;
470633e6d57Sdrh       db->lookaside.pFree = pBuf;
471633e6d57Sdrh       db->lookaside.nOut--;
472174b9a16Sdrh       return;
473174b9a16Sdrh     }
474174b9a16Sdrh   }
475174b9a16Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
476174b9a16Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
477174b9a16Sdrh   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
478107b56e8Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
479633e6d57Sdrh   sqlite3_free(p);
480633e6d57Sdrh }
481633e6d57Sdrh 
482633e6d57Sdrh /*
483fec00eabSdrh ** Change the size of an existing memory allocation
484fec00eabSdrh */
485fec00eabSdrh void *sqlite3Realloc(void *pOld, int nBytes){
486fec00eabSdrh   int nOld, nNew;
487fec00eabSdrh   void *pNew;
488fec00eabSdrh   if( pOld==0 ){
489fec00eabSdrh     return sqlite3Malloc(nBytes);
490fec00eabSdrh   }
491b6063cf8Sdrh   if( nBytes<=0 ){
492fec00eabSdrh     sqlite3_free(pOld);
493fec00eabSdrh     return 0;
494fec00eabSdrh   }
495b6063cf8Sdrh   if( nBytes>=0x7fffff00 ){
496b6063cf8Sdrh     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
497b6063cf8Sdrh     return 0;
498b6063cf8Sdrh   }
499fec00eabSdrh   nOld = sqlite3MallocSize(pOld);
500075c23afSdanielk1977   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
501fec00eabSdrh   if( nOld==nNew ){
502fec00eabSdrh     pNew = pOld;
5037c6791c8Sdrh   }else if( sqlite3GlobalConfig.bMemstat ){
5047c6791c8Sdrh     sqlite3_mutex_enter(mem0.mutex);
5057c6791c8Sdrh     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
506f7141990Sdrh     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
507f7141990Sdrh           mem0.alarmThreshold ){
508fec00eabSdrh       sqlite3MallocAlarm(nNew-nOld);
509fec00eabSdrh     }
510107b56e8Sdrh     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
511174b9a16Sdrh     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
512075c23afSdanielk1977     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
513d09414cdSdanielk1977     if( pNew==0 && mem0.alarmCallback ){
514fec00eabSdrh       sqlite3MallocAlarm(nBytes);
515075c23afSdanielk1977       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
516fec00eabSdrh     }
517fec00eabSdrh     if( pNew ){
518c702c7ccSdrh       nNew = sqlite3MallocSize(pNew);
519f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
520fec00eabSdrh     }
521fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
522fec00eabSdrh   }else{
5237c6791c8Sdrh     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
524fec00eabSdrh   }
525fec00eabSdrh   return pNew;
526fec00eabSdrh }
527fec00eabSdrh 
528fec00eabSdrh /*
529fec00eabSdrh ** The public interface to sqlite3Realloc.  Make sure that the memory
530fec00eabSdrh ** subsystem is initialized prior to invoking sqliteRealloc.
531fec00eabSdrh */
532fec00eabSdrh void *sqlite3_realloc(void *pOld, int n){
533fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
534fec00eabSdrh   if( sqlite3_initialize() ) return 0;
535fec00eabSdrh #endif
536fec00eabSdrh   return sqlite3Realloc(pOld, n);
537fec00eabSdrh }
538fec00eabSdrh 
539a3152895Sdrh 
540a3152895Sdrh /*
54117435752Sdrh ** Allocate and zero memory.
542a3152895Sdrh */
543fec00eabSdrh void *sqlite3MallocZero(int n){
544fec00eabSdrh   void *p = sqlite3Malloc(n);
545a3152895Sdrh   if( p ){
546a3152895Sdrh     memset(p, 0, n);
547a3152895Sdrh   }
548a3152895Sdrh   return p;
549a3152895Sdrh }
55017435752Sdrh 
55117435752Sdrh /*
55217435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
55317435752Sdrh ** the mallocFailed flag in the connection pointer.
55417435752Sdrh */
555fec00eabSdrh void *sqlite3DbMallocZero(sqlite3 *db, int n){
556a1644fd8Sdanielk1977   void *p = sqlite3DbMallocRaw(db, n);
55717435752Sdrh   if( p ){
55817435752Sdrh     memset(p, 0, n);
55917435752Sdrh   }
56017435752Sdrh   return p;
56117435752Sdrh }
56217435752Sdrh 
56317435752Sdrh /*
56417435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
56517435752Sdrh ** the mallocFailed flag in the connection pointer.
566ddecae79Sdrh **
567ddecae79Sdrh ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
568ddecae79Sdrh ** failure on the same database connection) then always return 0.
569ddecae79Sdrh ** Hence for a particular database connection, once malloc starts
570ddecae79Sdrh ** failing, it fails consistently until mallocFailed is reset.
571ddecae79Sdrh ** This is an important assumption.  There are many places in the
572ddecae79Sdrh ** code that do things like this:
573ddecae79Sdrh **
574ddecae79Sdrh **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
575ddecae79Sdrh **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
576ddecae79Sdrh **         if( b ) a[10] = 9;
577ddecae79Sdrh **
578ddecae79Sdrh ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
579ddecae79Sdrh ** that all prior mallocs (ex: "a") worked too.
58017435752Sdrh */
581fec00eabSdrh void *sqlite3DbMallocRaw(sqlite3 *db, int n){
582633e6d57Sdrh   void *p;
583d9da78a2Sdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
584*ccd4ad3eSdan   assert( db==0 || db->pnBytesFreed==0 );
5854150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
586633e6d57Sdrh   if( db ){
587633e6d57Sdrh     LookasideSlot *pBuf;
588633e6d57Sdrh     if( db->mallocFailed ){
589633e6d57Sdrh       return 0;
590633e6d57Sdrh     }
591633e6d57Sdrh     if( db->lookaside.bEnabled && n<=db->lookaside.sz
592633e6d57Sdrh          && (pBuf = db->lookaside.pFree)!=0 ){
593633e6d57Sdrh       db->lookaside.pFree = pBuf->pNext;
594633e6d57Sdrh       db->lookaside.nOut++;
595633e6d57Sdrh       if( db->lookaside.nOut>db->lookaside.mxOut ){
596633e6d57Sdrh         db->lookaside.mxOut = db->lookaside.nOut;
597633e6d57Sdrh       }
598633e6d57Sdrh       return (void*)pBuf;
599633e6d57Sdrh     }
600633e6d57Sdrh   }
601ddecae79Sdrh #else
602ddecae79Sdrh   if( db && db->mallocFailed ){
603ddecae79Sdrh     return 0;
604ddecae79Sdrh   }
6054150ebf8Sdrh #endif
606fec00eabSdrh   p = sqlite3Malloc(n);
607f3a65f7eSdrh   if( !p && db ){
60817435752Sdrh     db->mallocFailed = 1;
60917435752Sdrh   }
610174b9a16Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_DB |
611174b9a16Sdrh          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
61217435752Sdrh   return p;
61317435752Sdrh }
61417435752Sdrh 
61526783a58Sdanielk1977 /*
61626783a58Sdanielk1977 ** Resize the block of memory pointed to by p to n bytes. If the
61726783a58Sdanielk1977 ** resize fails, set the mallocFailed flag in the connection object.
61826783a58Sdanielk1977 */
619a1644fd8Sdanielk1977 void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
620a1644fd8Sdanielk1977   void *pNew = 0;
621d9da78a2Sdrh   assert( db!=0 );
6227047e25cSdrh   assert( sqlite3_mutex_held(db->mutex) );
623a1644fd8Sdanielk1977   if( db->mallocFailed==0 ){
624633e6d57Sdrh     if( p==0 ){
625633e6d57Sdrh       return sqlite3DbMallocRaw(db, n);
626633e6d57Sdrh     }
627633e6d57Sdrh     if( isLookaside(db, p) ){
628633e6d57Sdrh       if( n<=db->lookaside.sz ){
629633e6d57Sdrh         return p;
630633e6d57Sdrh       }
631633e6d57Sdrh       pNew = sqlite3DbMallocRaw(db, n);
632633e6d57Sdrh       if( pNew ){
633633e6d57Sdrh         memcpy(pNew, p, db->lookaside.sz);
634633e6d57Sdrh         sqlite3DbFree(db, p);
635633e6d57Sdrh       }
636633e6d57Sdrh     }else{
637174b9a16Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
638174b9a16Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
639107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
640a1644fd8Sdanielk1977       pNew = sqlite3_realloc(p, n);
641a1644fd8Sdanielk1977       if( !pNew ){
642174b9a16Sdrh         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
643a1644fd8Sdanielk1977         db->mallocFailed = 1;
644a1644fd8Sdanielk1977       }
645174b9a16Sdrh       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
646174b9a16Sdrh             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
647a1644fd8Sdanielk1977     }
648633e6d57Sdrh   }
649a1644fd8Sdanielk1977   return pNew;
650a1644fd8Sdanielk1977 }
651a1644fd8Sdanielk1977 
65217435752Sdrh /*
65317435752Sdrh ** Attempt to reallocate p.  If the reallocation fails, then free p
65417435752Sdrh ** and set the mallocFailed flag in the database connection.
65517435752Sdrh */
65617435752Sdrh void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
657a3152895Sdrh   void *pNew;
658a1644fd8Sdanielk1977   pNew = sqlite3DbRealloc(db, p, n);
659a3152895Sdrh   if( !pNew ){
660633e6d57Sdrh     sqlite3DbFree(db, p);
661a3152895Sdrh   }
662a3152895Sdrh   return pNew;
663a3152895Sdrh }
664a3152895Sdrh 
665a3152895Sdrh /*
666a3152895Sdrh ** Make a copy of a string in memory obtained from sqliteMalloc(). These
667a3152895Sdrh ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
668a3152895Sdrh ** is because when memory debugging is turned on, these two functions are
669a3152895Sdrh ** called via macros that record the current file and line number in the
670a3152895Sdrh ** ThreadData structure.
671a3152895Sdrh */
672633e6d57Sdrh char *sqlite3DbStrDup(sqlite3 *db, const char *z){
673a3152895Sdrh   char *zNew;
674633e6d57Sdrh   size_t n;
675633e6d57Sdrh   if( z==0 ){
676633e6d57Sdrh     return 0;
677a3152895Sdrh   }
678dee0e404Sdrh   n = sqlite3Strlen30(z) + 1;
679633e6d57Sdrh   assert( (n&0x7fffffff)==n );
680633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, (int)n);
681a3152895Sdrh   if( zNew ){
682a3152895Sdrh     memcpy(zNew, z, n);
6831e536953Sdanielk1977   }
6841e536953Sdanielk1977   return zNew;
6851e536953Sdanielk1977 }
6861e536953Sdanielk1977 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
687633e6d57Sdrh   char *zNew;
688633e6d57Sdrh   if( z==0 ){
689633e6d57Sdrh     return 0;
690633e6d57Sdrh   }
691633e6d57Sdrh   assert( (n&0x7fffffff)==n );
692633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, n+1);
693633e6d57Sdrh   if( zNew ){
694633e6d57Sdrh     memcpy(zNew, z, n);
695633e6d57Sdrh     zNew[n] = 0;
6961e536953Sdanielk1977   }
6971e536953Sdanielk1977   return zNew;
6981e536953Sdanielk1977 }
6991e536953Sdanielk1977 
700a3152895Sdrh /*
701f089aa45Sdrh ** Create a string from the zFromat argument and the va_list that follows.
702f089aa45Sdrh ** Store the string in memory obtained from sqliteMalloc() and make *pz
703f089aa45Sdrh ** point to that string.
704a3152895Sdrh */
705f089aa45Sdrh void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
706a3152895Sdrh   va_list ap;
707f089aa45Sdrh   char *z;
708a3152895Sdrh 
709f089aa45Sdrh   va_start(ap, zFormat);
710f089aa45Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
711a3152895Sdrh   va_end(ap);
712633e6d57Sdrh   sqlite3DbFree(db, *pz);
713f089aa45Sdrh   *pz = z;
714a3152895Sdrh }
715a3152895Sdrh 
716a3152895Sdrh 
717a3152895Sdrh /*
718a3152895Sdrh ** This function must be called before exiting any API function (i.e.
71917435752Sdrh ** returning control to the user) that has called sqlite3_malloc or
72017435752Sdrh ** sqlite3_realloc.
721a3152895Sdrh **
722a3152895Sdrh ** The returned value is normally a copy of the second argument to this
723be217793Sshane ** function. However, if a malloc() failure has occurred since the previous
724a3152895Sdrh ** invocation SQLITE_NOMEM is returned instead.
725a3152895Sdrh **
726be217793Sshane ** If the first argument, db, is not NULL and a malloc() error has occurred,
727a3152895Sdrh ** then the connection error-code (the value returned by sqlite3_errcode())
728a3152895Sdrh ** is set to SQLITE_NOMEM.
729a3152895Sdrh */
730a3152895Sdrh int sqlite3ApiExit(sqlite3* db, int rc){
731a1644fd8Sdanielk1977   /* If the db handle is not NULL, then we must hold the connection handle
732a1644fd8Sdanielk1977   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
733a1644fd8Sdanielk1977   ** is unsafe, as is the call to sqlite3Error().
734a1644fd8Sdanielk1977   */
735a1644fd8Sdanielk1977   assert( !db || sqlite3_mutex_held(db->mutex) );
73698c21903Sdanielk1977   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
737a3152895Sdrh     sqlite3Error(db, SQLITE_NOMEM, 0);
73817435752Sdrh     db->mallocFailed = 0;
739a3152895Sdrh     rc = SQLITE_NOMEM;
740a3152895Sdrh   }
741a3152895Sdrh   return rc & (db ? db->errMask : 0xff);
742a3152895Sdrh }
743