xref: /sqlite-3.40.0/src/malloc.c (revision e08ed7e7)
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 **
15*e08ed7e7Sdrh ** $Id: malloc.c,v 1.63 2009/06/26 18:35:17 drh Exp $
16a3152895Sdrh */
17a3152895Sdrh #include "sqliteInt.h"
18a3152895Sdrh #include <stdarg.h>
19a3152895Sdrh 
20a3152895Sdrh /*
21b21c8cd4Sdrh ** This routine runs when the memory allocator sees that the
22b21c8cd4Sdrh ** total memory allocation is about to exceed the soft heap
23b21c8cd4Sdrh ** limit.
24b21c8cd4Sdrh */
25b21c8cd4Sdrh static void softHeapLimitEnforcer(
26b21c8cd4Sdrh   void *NotUsed,
2762c14b34Sdanielk1977   sqlite3_int64 NotUsed2,
28153c62c4Sdrh   int allocSize
29b21c8cd4Sdrh ){
3062c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
31b21c8cd4Sdrh   sqlite3_release_memory(allocSize);
32b21c8cd4Sdrh }
33b21c8cd4Sdrh 
34b21c8cd4Sdrh /*
358468024dSdanielk1977 ** Set the soft heap-size limit for the library. Passing a zero or
368468024dSdanielk1977 ** negative value indicates no limit.
37a3152895Sdrh */
38a3152895Sdrh void sqlite3_soft_heap_limit(int n){
39b21c8cd4Sdrh   sqlite3_uint64 iLimit;
40b21c8cd4Sdrh   int overage;
41b21c8cd4Sdrh   if( n<0 ){
42b21c8cd4Sdrh     iLimit = 0;
43b21c8cd4Sdrh   }else{
44b21c8cd4Sdrh     iLimit = n;
45a3152895Sdrh   }
469ac3fe97Sdrh   sqlite3_initialize();
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 #if 0
6767e3da7aSdanielk1977   nRet += sqlite3VdbeReleaseMemory(n);
6867e3da7aSdanielk1977 #endif
6967e3da7aSdanielk1977   nRet += sqlite3PcacheReleaseMemory(n-nRet);
70dfb316d4Sdanielk1977   return nRet;
711e536953Sdanielk1977 #else
7262c14b34Sdanielk1977   UNUSED_PARAMETER(n);
731e536953Sdanielk1977   return SQLITE_OK;
741e536953Sdanielk1977 #endif
75a3152895Sdrh }
76a3152895Sdrh 
77fec00eabSdrh /*
78fec00eabSdrh ** State information local to the memory allocation subsystem.
79fec00eabSdrh */
805c8f8587Sdanielk1977 static SQLITE_WSD struct Mem0Global {
8123bf0f41Sdanielk1977   /* Number of free pages for scratch and page-cache memory */
8223bf0f41Sdanielk1977   u32 nScratchFree;
8323bf0f41Sdanielk1977   u32 nPageFree;
8423bf0f41Sdanielk1977 
85fec00eabSdrh   sqlite3_mutex *mutex;         /* Mutex to serialize access */
86fec00eabSdrh 
87fec00eabSdrh   /*
88fec00eabSdrh   ** The alarm callback and its arguments.  The mem0.mutex lock will
89fec00eabSdrh   ** be held while the callback is running.  Recursive calls into
90fec00eabSdrh   ** the memory subsystem are allowed, but no new callbacks will be
91fec00eabSdrh   ** issued.  The alarmBusy variable is set to prevent recursive
92fec00eabSdrh   ** callbacks.
93fec00eabSdrh   */
94fec00eabSdrh   sqlite3_int64 alarmThreshold;
95fec00eabSdrh   void (*alarmCallback)(void*, sqlite3_int64,int);
96fec00eabSdrh   void *alarmArg;
97fec00eabSdrh   int alarmBusy;
98fec00eabSdrh 
99fec00eabSdrh   /*
100075c23afSdanielk1977   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
101075c23afSdanielk1977   ** sqlite3GlobalConfig.pPage to a block of memory that records
1029ac3fe97Sdrh   ** which pages are available.
1039ac3fe97Sdrh   */
1049ac3fe97Sdrh   u32 *aScratchFree;
1059ac3fe97Sdrh   u32 *aPageFree;
106cdcfe95cSdanielk1977 } mem0 = { 62560955, 0, 0, 0, 0, 0, 0, 0, 0 };
1075c8f8587Sdanielk1977 
1085c8f8587Sdanielk1977 #define mem0 GLOBAL(struct Mem0Global, mem0)
109fec00eabSdrh 
110fec00eabSdrh /*
111fec00eabSdrh ** Initialize the memory allocation subsystem.
112fec00eabSdrh */
113fec00eabSdrh int sqlite3MallocInit(void){
114075c23afSdanielk1977   if( sqlite3GlobalConfig.m.xMalloc==0 ){
115fec00eabSdrh     sqlite3MemSetDefault();
116fec00eabSdrh   }
117fec00eabSdrh   memset(&mem0, 0, sizeof(mem0));
118075c23afSdanielk1977   if( sqlite3GlobalConfig.bCoreMutex ){
11959f8c08eSdanielk1977     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
120fec00eabSdrh   }
121075c23afSdanielk1977   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
122075c23afSdanielk1977       && sqlite3GlobalConfig.nScratch>=0 ){
1239ac3fe97Sdrh     int i;
124bc73971dSdanielk1977     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
125075c23afSdanielk1977     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
126075c23afSdanielk1977                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
127075c23afSdanielk1977     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
128075c23afSdanielk1977     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
1299ac3fe97Sdrh   }else{
130075c23afSdanielk1977     sqlite3GlobalConfig.pScratch = 0;
131075c23afSdanielk1977     sqlite3GlobalConfig.szScratch = 0;
1329ac3fe97Sdrh   }
133075c23afSdanielk1977   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
134075c23afSdanielk1977       && sqlite3GlobalConfig.nPage>=1 ){
1359ac3fe97Sdrh     int i;
1360a60a384Sdrh     int overhead;
137bc73971dSdanielk1977     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
138075c23afSdanielk1977     int n = sqlite3GlobalConfig.nPage;
1390a60a384Sdrh     overhead = (4*n + sz - 1)/sz;
140075c23afSdanielk1977     sqlite3GlobalConfig.nPage -= overhead;
141075c23afSdanielk1977     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
142075c23afSdanielk1977                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
143075c23afSdanielk1977     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
144075c23afSdanielk1977     mem0.nPageFree = sqlite3GlobalConfig.nPage;
1459ac3fe97Sdrh   }else{
146075c23afSdanielk1977     sqlite3GlobalConfig.pPage = 0;
147075c23afSdanielk1977     sqlite3GlobalConfig.szPage = 0;
1489ac3fe97Sdrh   }
149075c23afSdanielk1977   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
150fec00eabSdrh }
151fec00eabSdrh 
152fec00eabSdrh /*
153fec00eabSdrh ** Deinitialize the memory allocation subsystem.
154fec00eabSdrh */
155fec00eabSdrh void sqlite3MallocEnd(void){
1560a549071Sdanielk1977   if( sqlite3GlobalConfig.m.xShutdown ){
157075c23afSdanielk1977     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
1580a549071Sdanielk1977   }
1599ac3fe97Sdrh   memset(&mem0, 0, sizeof(mem0));
160fec00eabSdrh }
161fec00eabSdrh 
162fec00eabSdrh /*
163fec00eabSdrh ** Return the amount of memory currently checked out.
164fec00eabSdrh */
165fec00eabSdrh sqlite3_int64 sqlite3_memory_used(void){
166f7141990Sdrh   int n, mx;
167c376a198Sdrh   sqlite3_int64 res;
168f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
169c376a198Sdrh   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
170c376a198Sdrh   return res;
171fec00eabSdrh }
172fec00eabSdrh 
173fec00eabSdrh /*
174fec00eabSdrh ** Return the maximum amount of memory that has ever been
175fec00eabSdrh ** checked out since either the beginning of this process
176fec00eabSdrh ** or since the most recent reset.
177fec00eabSdrh */
178fec00eabSdrh sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
179f7141990Sdrh   int n, mx;
180c376a198Sdrh   sqlite3_int64 res;
181f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
1827986a71aSdrh   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
183c376a198Sdrh   return res;
184fec00eabSdrh }
185fec00eabSdrh 
186fec00eabSdrh /*
187fec00eabSdrh ** Change the alarm callback
188fec00eabSdrh */
1894a27a286Sshane int sqlite3MemoryAlarm(
190fec00eabSdrh   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
191fec00eabSdrh   void *pArg,
192fec00eabSdrh   sqlite3_int64 iThreshold
193fec00eabSdrh ){
194fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
195fec00eabSdrh   mem0.alarmCallback = xCallback;
196fec00eabSdrh   mem0.alarmArg = pArg;
197fec00eabSdrh   mem0.alarmThreshold = iThreshold;
198fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
199fec00eabSdrh   return SQLITE_OK;
200fec00eabSdrh }
201fec00eabSdrh 
202eec556d3Sshane #ifndef SQLITE_OMIT_DEPRECATED
203fec00eabSdrh /*
2044a27a286Sshane ** Deprecated external interface.  Internal/core SQLite code
2054a27a286Sshane ** should call sqlite3MemoryAlarm.
2064a27a286Sshane */
2074a27a286Sshane int sqlite3_memory_alarm(
2084a27a286Sshane   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
2094a27a286Sshane   void *pArg,
2104a27a286Sshane   sqlite3_int64 iThreshold
2114a27a286Sshane ){
2124a27a286Sshane   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
2134a27a286Sshane }
214eec556d3Sshane #endif
2154a27a286Sshane 
2164a27a286Sshane /*
217fec00eabSdrh ** Trigger the alarm
218fec00eabSdrh */
219fec00eabSdrh static void sqlite3MallocAlarm(int nByte){
220fec00eabSdrh   void (*xCallback)(void*,sqlite3_int64,int);
221fec00eabSdrh   sqlite3_int64 nowUsed;
222fec00eabSdrh   void *pArg;
223fec00eabSdrh   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
224fec00eabSdrh   mem0.alarmBusy = 1;
225fec00eabSdrh   xCallback = mem0.alarmCallback;
226f7141990Sdrh   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
227fec00eabSdrh   pArg = mem0.alarmArg;
228fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
229fec00eabSdrh   xCallback(pArg, nowUsed, nByte);
230fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
231fec00eabSdrh   mem0.alarmBusy = 0;
232fec00eabSdrh }
233fec00eabSdrh 
234fec00eabSdrh /*
235f7141990Sdrh ** Do a memory allocation with statistics and alarms.  Assume the
236f7141990Sdrh ** lock is already held.
237fec00eabSdrh */
238f7141990Sdrh static int mallocWithAlarm(int n, void **pp){
239fec00eabSdrh   int nFull;
240f7141990Sdrh   void *p;
241f7141990Sdrh   assert( sqlite3_mutex_held(mem0.mutex) );
242075c23afSdanielk1977   nFull = sqlite3GlobalConfig.m.xRoundup(n);
243f7141990Sdrh   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
244f7141990Sdrh   if( mem0.alarmCallback!=0 ){
245f7141990Sdrh     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
246f7141990Sdrh     if( nUsed+nFull >= mem0.alarmThreshold ){
247fec00eabSdrh       sqlite3MallocAlarm(nFull);
248fec00eabSdrh     }
249f7141990Sdrh   }
250075c23afSdanielk1977   p = sqlite3GlobalConfig.m.xMalloc(nFull);
251d09414cdSdanielk1977   if( p==0 && mem0.alarmCallback ){
252fec00eabSdrh     sqlite3MallocAlarm(nFull);
253075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(nFull);
254fec00eabSdrh   }
255c702c7ccSdrh   if( p ){
256c702c7ccSdrh     nFull = sqlite3MallocSize(p);
257c702c7ccSdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
258c702c7ccSdrh   }
259f7141990Sdrh   *pp = p;
260f7141990Sdrh   return nFull;
261fec00eabSdrh }
262f7141990Sdrh 
263f7141990Sdrh /*
264f7141990Sdrh ** Allocate memory.  This routine is like sqlite3_malloc() except that it
265f7141990Sdrh ** assumes the memory subsystem has already been initialized.
266f7141990Sdrh */
267f7141990Sdrh void *sqlite3Malloc(int n){
268f7141990Sdrh   void *p;
269*e08ed7e7Sdrh   if( n<=0 || n>=0x7fffff00 ){
270*e08ed7e7Sdrh     /* A memory allocation of a number of bytes which is near the maximum
271*e08ed7e7Sdrh     ** signed integer value might cause an integer overflow inside of the
272*e08ed7e7Sdrh     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
273*e08ed7e7Sdrh     ** 255 bytes of overhead.  SQLite itself will never use anything near
274*e08ed7e7Sdrh     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
275f7141990Sdrh     p = 0;
276075c23afSdanielk1977   }else if( sqlite3GlobalConfig.bMemstat ){
277f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
278f7141990Sdrh     mallocWithAlarm(n, &p);
279fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
280fec00eabSdrh   }else{
281075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(n);
282fec00eabSdrh   }
283fec00eabSdrh   return p;
284fec00eabSdrh }
285fec00eabSdrh 
286fec00eabSdrh /*
287fec00eabSdrh ** This version of the memory allocation is for use by the application.
288fec00eabSdrh ** First make sure the memory subsystem is initialized, then do the
289fec00eabSdrh ** allocation.
290fec00eabSdrh */
291fec00eabSdrh void *sqlite3_malloc(int n){
292fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
293fec00eabSdrh   if( sqlite3_initialize() ) return 0;
294fec00eabSdrh #endif
295fec00eabSdrh   return sqlite3Malloc(n);
296fec00eabSdrh }
297fec00eabSdrh 
298fec00eabSdrh /*
299e5ae5735Sdrh ** Each thread may only have a single outstanding allocation from
300facf0307Sdrh ** xScratchMalloc().  We verify this constraint in the single-threaded
301facf0307Sdrh ** case by setting scratchAllocOut to 1 when an allocation
302e5ae5735Sdrh ** is outstanding clearing it when the allocation is freed.
303e5ae5735Sdrh */
304e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
305facf0307Sdrh static int scratchAllocOut = 0;
306e5ae5735Sdrh #endif
307e5ae5735Sdrh 
308e5ae5735Sdrh 
309e5ae5735Sdrh /*
310e5ae5735Sdrh ** Allocate memory that is to be used and released right away.
311e5ae5735Sdrh ** This routine is similar to alloca() in that it is not intended
312e5ae5735Sdrh ** for situations where the memory might be held long-term.  This
313e5ae5735Sdrh ** routine is intended to get memory to old large transient data
314e5ae5735Sdrh ** structures that would not normally fit on the stack of an
315e5ae5735Sdrh ** embedded processor.
316e5ae5735Sdrh */
317facf0307Sdrh void *sqlite3ScratchMalloc(int n){
318e5ae5735Sdrh   void *p;
319e5ae5735Sdrh   assert( n>0 );
3209ac3fe97Sdrh 
321e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
3229ac3fe97Sdrh   /* Verify that no more than one scratch allocation per thread
3239ac3fe97Sdrh   ** is outstanding at one time.  (This is only checked in the
3249ac3fe97Sdrh   ** single-threaded case since checking in the multi-threaded case
3259ac3fe97Sdrh   ** would be much more complicated.) */
326facf0307Sdrh   assert( scratchAllocOut==0 );
327e5ae5735Sdrh #endif
3289ac3fe97Sdrh 
329075c23afSdanielk1977   if( sqlite3GlobalConfig.szScratch<n ){
330f7141990Sdrh     goto scratch_overflow;
331f7141990Sdrh   }else{
332e5ae5735Sdrh     sqlite3_mutex_enter(mem0.mutex);
333f7141990Sdrh     if( mem0.nScratchFree==0 ){
334f7141990Sdrh       sqlite3_mutex_leave(mem0.mutex);
335f7141990Sdrh       goto scratch_overflow;
336e5ae5735Sdrh     }else{
3379ac3fe97Sdrh       int i;
3389ac3fe97Sdrh       i = mem0.aScratchFree[--mem0.nScratchFree];
339075c23afSdanielk1977       i *= sqlite3GlobalConfig.szScratch;
340f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
341e50135e2Sdrh       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
3428183e339Sdanielk1977       sqlite3_mutex_leave(mem0.mutex);
343075c23afSdanielk1977       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
34415301596Sshane       assert(  (((u8*)p - (u8*)0) & 7)==0 );
345e5ae5735Sdrh     }
346f7141990Sdrh   }
347f7141990Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
348f7141990Sdrh   scratchAllocOut = p!=0;
349f7141990Sdrh #endif
350f7141990Sdrh 
351f7141990Sdrh   return p;
352f7141990Sdrh 
353f7141990Sdrh scratch_overflow:
354075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
355f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
356e50135e2Sdrh     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
357f7141990Sdrh     n = mallocWithAlarm(n, &p);
358f7141990Sdrh     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
3599ac3fe97Sdrh     sqlite3_mutex_leave(mem0.mutex);
360f7141990Sdrh   }else{
361075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(n);
362f7141990Sdrh   }
363f7141990Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
364f7141990Sdrh   scratchAllocOut = p!=0;
365f7141990Sdrh #endif
366e5ae5735Sdrh   return p;
367e5ae5735Sdrh }
368facf0307Sdrh void sqlite3ScratchFree(void *p){
369e5ae5735Sdrh   if( p ){
3709ac3fe97Sdrh 
371e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
3729ac3fe97Sdrh     /* Verify that no more than one scratch allocation per thread
3739ac3fe97Sdrh     ** is outstanding at one time.  (This is only checked in the
3749ac3fe97Sdrh     ** single-threaded case since checking in the multi-threaded case
3759ac3fe97Sdrh     ** would be much more complicated.) */
376facf0307Sdrh     assert( scratchAllocOut==1 );
377facf0307Sdrh     scratchAllocOut = 0;
378e5ae5735Sdrh #endif
3799ac3fe97Sdrh 
380075c23afSdanielk1977     if( sqlite3GlobalConfig.pScratch==0
381075c23afSdanielk1977            || p<sqlite3GlobalConfig.pScratch
3829ac3fe97Sdrh            || p>=(void*)mem0.aScratchFree ){
383075c23afSdanielk1977       if( sqlite3GlobalConfig.bMemstat ){
384f7141990Sdrh         int iSize = sqlite3MallocSize(p);
385f7141990Sdrh         sqlite3_mutex_enter(mem0.mutex);
386f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
387f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
388075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
389f7141990Sdrh         sqlite3_mutex_leave(mem0.mutex);
390f7141990Sdrh       }else{
391075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
392f7141990Sdrh       }
3939ac3fe97Sdrh     }else{
3949ac3fe97Sdrh       int i;
3951bd10f8aSdrh       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
396075c23afSdanielk1977       i /= sqlite3GlobalConfig.szScratch;
397075c23afSdanielk1977       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
398f7141990Sdrh       sqlite3_mutex_enter(mem0.mutex);
39900e13613Sdanielk1977       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
4009ac3fe97Sdrh       mem0.aScratchFree[mem0.nScratchFree++] = i;
401f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
4029ac3fe97Sdrh       sqlite3_mutex_leave(mem0.mutex);
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){
412633e6d57Sdrh   return db && 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){
423075c23afSdanielk1977   return sqlite3GlobalConfig.m.xSize(p);
424fec00eabSdrh }
425633e6d57Sdrh int sqlite3DbMallocSize(sqlite3 *db, void *p){
4267047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
4276a1e071fSdrh   if( p==0 ){
4286a1e071fSdrh     return 0;
4296a1e071fSdrh   }else if( isLookaside(db, p) ){
430633e6d57Sdrh     return db->lookaside.sz;
431633e6d57Sdrh   }else{
432075c23afSdanielk1977     return sqlite3GlobalConfig.m.xSize(p);
433633e6d57Sdrh   }
434633e6d57Sdrh }
435fec00eabSdrh 
436fec00eabSdrh /*
437fec00eabSdrh ** Free memory previously obtained from sqlite3Malloc().
438fec00eabSdrh */
439fec00eabSdrh void sqlite3_free(void *p){
440fec00eabSdrh   if( p==0 ) return;
441075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
442fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
443f7141990Sdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
444075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
445fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
446fec00eabSdrh   }else{
447075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
448fec00eabSdrh   }
449fec00eabSdrh }
450fec00eabSdrh 
451fec00eabSdrh /*
452633e6d57Sdrh ** Free memory that might be associated with a particular database
453633e6d57Sdrh ** connection.
454633e6d57Sdrh */
455633e6d57Sdrh void sqlite3DbFree(sqlite3 *db, void *p){
4567047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
457633e6d57Sdrh   if( isLookaside(db, p) ){
458633e6d57Sdrh     LookasideSlot *pBuf = (LookasideSlot*)p;
459633e6d57Sdrh     pBuf->pNext = db->lookaside.pFree;
460633e6d57Sdrh     db->lookaside.pFree = pBuf;
461633e6d57Sdrh     db->lookaside.nOut--;
462633e6d57Sdrh   }else{
463633e6d57Sdrh     sqlite3_free(p);
464633e6d57Sdrh   }
465633e6d57Sdrh }
466633e6d57Sdrh 
467633e6d57Sdrh /*
468fec00eabSdrh ** Change the size of an existing memory allocation
469fec00eabSdrh */
470fec00eabSdrh void *sqlite3Realloc(void *pOld, int nBytes){
471fec00eabSdrh   int nOld, nNew;
472fec00eabSdrh   void *pNew;
473fec00eabSdrh   if( pOld==0 ){
474fec00eabSdrh     return sqlite3Malloc(nBytes);
475fec00eabSdrh   }
476*e08ed7e7Sdrh   if( nBytes<=0 || nBytes>=0x7fffff00 ){
477*e08ed7e7Sdrh     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
478fec00eabSdrh     sqlite3_free(pOld);
479fec00eabSdrh     return 0;
480fec00eabSdrh   }
481fec00eabSdrh   nOld = sqlite3MallocSize(pOld);
482075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
483fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
484f7141990Sdrh     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
485075c23afSdanielk1977     nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
486fec00eabSdrh     if( nOld==nNew ){
487fec00eabSdrh       pNew = pOld;
488fec00eabSdrh     }else{
489f7141990Sdrh       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
490f7141990Sdrh             mem0.alarmThreshold ){
491fec00eabSdrh         sqlite3MallocAlarm(nNew-nOld);
492fec00eabSdrh       }
493075c23afSdanielk1977       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
494d09414cdSdanielk1977       if( pNew==0 && mem0.alarmCallback ){
495fec00eabSdrh         sqlite3MallocAlarm(nBytes);
496075c23afSdanielk1977         pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
497fec00eabSdrh       }
498fec00eabSdrh       if( pNew ){
499c702c7ccSdrh         nNew = sqlite3MallocSize(pNew);
500f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
501fec00eabSdrh       }
502fec00eabSdrh     }
503fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
504fec00eabSdrh   }else{
505075c23afSdanielk1977     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
506fec00eabSdrh   }
507fec00eabSdrh   return pNew;
508fec00eabSdrh }
509fec00eabSdrh 
510fec00eabSdrh /*
511fec00eabSdrh ** The public interface to sqlite3Realloc.  Make sure that the memory
512fec00eabSdrh ** subsystem is initialized prior to invoking sqliteRealloc.
513fec00eabSdrh */
514fec00eabSdrh void *sqlite3_realloc(void *pOld, int n){
515fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
516fec00eabSdrh   if( sqlite3_initialize() ) return 0;
517fec00eabSdrh #endif
518fec00eabSdrh   return sqlite3Realloc(pOld, n);
519fec00eabSdrh }
520fec00eabSdrh 
521a3152895Sdrh 
522a3152895Sdrh /*
52317435752Sdrh ** Allocate and zero memory.
524a3152895Sdrh */
525fec00eabSdrh void *sqlite3MallocZero(int n){
526fec00eabSdrh   void *p = sqlite3Malloc(n);
527a3152895Sdrh   if( p ){
528a3152895Sdrh     memset(p, 0, n);
529a3152895Sdrh   }
530a3152895Sdrh   return p;
531a3152895Sdrh }
53217435752Sdrh 
53317435752Sdrh /*
53417435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
53517435752Sdrh ** the mallocFailed flag in the connection pointer.
53617435752Sdrh */
537fec00eabSdrh void *sqlite3DbMallocZero(sqlite3 *db, int n){
538a1644fd8Sdanielk1977   void *p = sqlite3DbMallocRaw(db, n);
53917435752Sdrh   if( p ){
54017435752Sdrh     memset(p, 0, n);
54117435752Sdrh   }
54217435752Sdrh   return p;
54317435752Sdrh }
54417435752Sdrh 
54517435752Sdrh /*
54617435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
54717435752Sdrh ** the mallocFailed flag in the connection pointer.
548ddecae79Sdrh **
549ddecae79Sdrh ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
550ddecae79Sdrh ** failure on the same database connection) then always return 0.
551ddecae79Sdrh ** Hence for a particular database connection, once malloc starts
552ddecae79Sdrh ** failing, it fails consistently until mallocFailed is reset.
553ddecae79Sdrh ** This is an important assumption.  There are many places in the
554ddecae79Sdrh ** code that do things like this:
555ddecae79Sdrh **
556ddecae79Sdrh **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
557ddecae79Sdrh **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
558ddecae79Sdrh **         if( b ) a[10] = 9;
559ddecae79Sdrh **
560ddecae79Sdrh ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
561ddecae79Sdrh ** that all prior mallocs (ex: "a") worked too.
56217435752Sdrh */
563fec00eabSdrh void *sqlite3DbMallocRaw(sqlite3 *db, int n){
564633e6d57Sdrh   void *p;
565d9da78a2Sdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
5664150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
567633e6d57Sdrh   if( db ){
568633e6d57Sdrh     LookasideSlot *pBuf;
569633e6d57Sdrh     if( db->mallocFailed ){
570633e6d57Sdrh       return 0;
571633e6d57Sdrh     }
572633e6d57Sdrh     if( db->lookaside.bEnabled && n<=db->lookaside.sz
573633e6d57Sdrh          && (pBuf = db->lookaside.pFree)!=0 ){
574633e6d57Sdrh       db->lookaside.pFree = pBuf->pNext;
575633e6d57Sdrh       db->lookaside.nOut++;
576633e6d57Sdrh       if( db->lookaside.nOut>db->lookaside.mxOut ){
577633e6d57Sdrh         db->lookaside.mxOut = db->lookaside.nOut;
578633e6d57Sdrh       }
579633e6d57Sdrh       return (void*)pBuf;
580633e6d57Sdrh     }
581633e6d57Sdrh   }
582ddecae79Sdrh #else
583ddecae79Sdrh   if( db && db->mallocFailed ){
584ddecae79Sdrh     return 0;
585ddecae79Sdrh   }
5864150ebf8Sdrh #endif
587fec00eabSdrh   p = sqlite3Malloc(n);
588f3a65f7eSdrh   if( !p && db ){
58917435752Sdrh     db->mallocFailed = 1;
59017435752Sdrh   }
59117435752Sdrh   return p;
59217435752Sdrh }
59317435752Sdrh 
59426783a58Sdanielk1977 /*
59526783a58Sdanielk1977 ** Resize the block of memory pointed to by p to n bytes. If the
59626783a58Sdanielk1977 ** resize fails, set the mallocFailed flag in the connection object.
59726783a58Sdanielk1977 */
598a1644fd8Sdanielk1977 void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
599a1644fd8Sdanielk1977   void *pNew = 0;
600d9da78a2Sdrh   assert( db!=0 );
6017047e25cSdrh   assert( sqlite3_mutex_held(db->mutex) );
602a1644fd8Sdanielk1977   if( db->mallocFailed==0 ){
603633e6d57Sdrh     if( p==0 ){
604633e6d57Sdrh       return sqlite3DbMallocRaw(db, n);
605633e6d57Sdrh     }
606633e6d57Sdrh     if( isLookaside(db, p) ){
607633e6d57Sdrh       if( n<=db->lookaside.sz ){
608633e6d57Sdrh         return p;
609633e6d57Sdrh       }
610633e6d57Sdrh       pNew = sqlite3DbMallocRaw(db, n);
611633e6d57Sdrh       if( pNew ){
612633e6d57Sdrh         memcpy(pNew, p, db->lookaside.sz);
613633e6d57Sdrh         sqlite3DbFree(db, p);
614633e6d57Sdrh       }
615633e6d57Sdrh     }else{
616a1644fd8Sdanielk1977       pNew = sqlite3_realloc(p, n);
617a1644fd8Sdanielk1977       if( !pNew ){
618a1644fd8Sdanielk1977         db->mallocFailed = 1;
619a1644fd8Sdanielk1977       }
620a1644fd8Sdanielk1977     }
621633e6d57Sdrh   }
622a1644fd8Sdanielk1977   return pNew;
623a1644fd8Sdanielk1977 }
624a1644fd8Sdanielk1977 
62517435752Sdrh /*
62617435752Sdrh ** Attempt to reallocate p.  If the reallocation fails, then free p
62717435752Sdrh ** and set the mallocFailed flag in the database connection.
62817435752Sdrh */
62917435752Sdrh void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
630a3152895Sdrh   void *pNew;
631a1644fd8Sdanielk1977   pNew = sqlite3DbRealloc(db, p, n);
632a3152895Sdrh   if( !pNew ){
633633e6d57Sdrh     sqlite3DbFree(db, p);
634a3152895Sdrh   }
635a3152895Sdrh   return pNew;
636a3152895Sdrh }
637a3152895Sdrh 
638a3152895Sdrh /*
639a3152895Sdrh ** Make a copy of a string in memory obtained from sqliteMalloc(). These
640a3152895Sdrh ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
641a3152895Sdrh ** is because when memory debugging is turned on, these two functions are
642a3152895Sdrh ** called via macros that record the current file and line number in the
643a3152895Sdrh ** ThreadData structure.
644a3152895Sdrh */
645633e6d57Sdrh char *sqlite3DbStrDup(sqlite3 *db, const char *z){
646a3152895Sdrh   char *zNew;
647633e6d57Sdrh   size_t n;
648633e6d57Sdrh   if( z==0 ){
649633e6d57Sdrh     return 0;
650a3152895Sdrh   }
651dee0e404Sdrh   n = sqlite3Strlen30(z) + 1;
652633e6d57Sdrh   assert( (n&0x7fffffff)==n );
653633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, (int)n);
654a3152895Sdrh   if( zNew ){
655a3152895Sdrh     memcpy(zNew, z, n);
6561e536953Sdanielk1977   }
6571e536953Sdanielk1977   return zNew;
6581e536953Sdanielk1977 }
6591e536953Sdanielk1977 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
660633e6d57Sdrh   char *zNew;
661633e6d57Sdrh   if( z==0 ){
662633e6d57Sdrh     return 0;
663633e6d57Sdrh   }
664633e6d57Sdrh   assert( (n&0x7fffffff)==n );
665633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, n+1);
666633e6d57Sdrh   if( zNew ){
667633e6d57Sdrh     memcpy(zNew, z, n);
668633e6d57Sdrh     zNew[n] = 0;
6691e536953Sdanielk1977   }
6701e536953Sdanielk1977   return zNew;
6711e536953Sdanielk1977 }
6721e536953Sdanielk1977 
673a3152895Sdrh /*
674f089aa45Sdrh ** Create a string from the zFromat argument and the va_list that follows.
675f089aa45Sdrh ** Store the string in memory obtained from sqliteMalloc() and make *pz
676f089aa45Sdrh ** point to that string.
677a3152895Sdrh */
678f089aa45Sdrh void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
679a3152895Sdrh   va_list ap;
680f089aa45Sdrh   char *z;
681a3152895Sdrh 
682f089aa45Sdrh   va_start(ap, zFormat);
683f089aa45Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
684a3152895Sdrh   va_end(ap);
685633e6d57Sdrh   sqlite3DbFree(db, *pz);
686f089aa45Sdrh   *pz = z;
687a3152895Sdrh }
688a3152895Sdrh 
689a3152895Sdrh 
690a3152895Sdrh /*
691a3152895Sdrh ** This function must be called before exiting any API function (i.e.
69217435752Sdrh ** returning control to the user) that has called sqlite3_malloc or
69317435752Sdrh ** sqlite3_realloc.
694a3152895Sdrh **
695a3152895Sdrh ** The returned value is normally a copy of the second argument to this
696be217793Sshane ** function. However, if a malloc() failure has occurred since the previous
697a3152895Sdrh ** invocation SQLITE_NOMEM is returned instead.
698a3152895Sdrh **
699be217793Sshane ** If the first argument, db, is not NULL and a malloc() error has occurred,
700a3152895Sdrh ** then the connection error-code (the value returned by sqlite3_errcode())
701a3152895Sdrh ** is set to SQLITE_NOMEM.
702a3152895Sdrh */
703a3152895Sdrh int sqlite3ApiExit(sqlite3* db, int rc){
704a1644fd8Sdanielk1977   /* If the db handle is not NULL, then we must hold the connection handle
705a1644fd8Sdanielk1977   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
706a1644fd8Sdanielk1977   ** is unsafe, as is the call to sqlite3Error().
707a1644fd8Sdanielk1977   */
708a1644fd8Sdanielk1977   assert( !db || sqlite3_mutex_held(db->mutex) );
70998c21903Sdanielk1977   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
710a3152895Sdrh     sqlite3Error(db, SQLITE_NOMEM, 0);
71117435752Sdrh     db->mallocFailed = 0;
712a3152895Sdrh     rc = SQLITE_NOMEM;
713a3152895Sdrh   }
714a3152895Sdrh   return rc & (db ? db->errMask : 0xff);
715a3152895Sdrh }
716