xref: /sqlite-3.40.0/src/malloc.c (revision 39f67beb)
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
659f129f46Sdrh   return sqlite3PcacheReleaseMemory(n);
661e536953Sdanielk1977 #else
679f129f46Sdrh   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
689f129f46Sdrh   ** is a no-op returning zero if SQLite is not compiled with
699f129f46Sdrh   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
7062c14b34Sdanielk1977   UNUSED_PARAMETER(n);
719f129f46Sdrh   return 0;
721e536953Sdanielk1977 #endif
73a3152895Sdrh }
74a3152895Sdrh 
75fec00eabSdrh /*
76badc980aSdrh ** An instance of the following object records the location of
77badc980aSdrh ** each unused scratch buffer.
78badc980aSdrh */
79badc980aSdrh typedef struct ScratchFreeslot {
80badc980aSdrh   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
81badc980aSdrh } ScratchFreeslot;
82badc980aSdrh 
83badc980aSdrh /*
84fec00eabSdrh ** State information local to the memory allocation subsystem.
85fec00eabSdrh */
865c8f8587Sdanielk1977 static SQLITE_WSD struct Mem0Global {
87fec00eabSdrh   sqlite3_mutex *mutex;         /* Mutex to serialize access */
88fec00eabSdrh 
89fec00eabSdrh   /*
90fec00eabSdrh   ** The alarm callback and its arguments.  The mem0.mutex lock will
91fec00eabSdrh   ** be held while the callback is running.  Recursive calls into
92fec00eabSdrh   ** the memory subsystem are allowed, but no new callbacks will be
93e64ca7baSdrh   ** issued.
94fec00eabSdrh   */
95fec00eabSdrh   sqlite3_int64 alarmThreshold;
96fec00eabSdrh   void (*alarmCallback)(void*, sqlite3_int64,int);
97fec00eabSdrh   void *alarmArg;
98fec00eabSdrh 
99fec00eabSdrh   /*
100badc980aSdrh   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
101badc980aSdrh   ** (so that a range test can be used to determine if an allocation
102badc980aSdrh   ** being freed came from pScratch) and a pointer to the list of
103badc980aSdrh   ** unused scratch allocations.
1049ac3fe97Sdrh   */
105badc980aSdrh   void *pScratchEnd;
106badc980aSdrh   ScratchFreeslot *pScratchFree;
107badc980aSdrh   u32 nScratchFree;
10850d1b5f3Sdrh 
10950d1b5f3Sdrh   /*
11050d1b5f3Sdrh   ** True if heap is nearly "full" where "full" is defined by the
11150d1b5f3Sdrh   ** sqlite3_soft_heap_limit() setting.
11250d1b5f3Sdrh   */
11350d1b5f3Sdrh   int nearlyFull;
114badc980aSdrh } mem0 = { 0, 0, 0, 0, 0, 0, 0 };
1155c8f8587Sdanielk1977 
1165c8f8587Sdanielk1977 #define mem0 GLOBAL(struct Mem0Global, mem0)
117fec00eabSdrh 
118fec00eabSdrh /*
119fec00eabSdrh ** Initialize the memory allocation subsystem.
120fec00eabSdrh */
121fec00eabSdrh int sqlite3MallocInit(void){
122075c23afSdanielk1977   if( sqlite3GlobalConfig.m.xMalloc==0 ){
123fec00eabSdrh     sqlite3MemSetDefault();
124fec00eabSdrh   }
125fec00eabSdrh   memset(&mem0, 0, sizeof(mem0));
126075c23afSdanielk1977   if( sqlite3GlobalConfig.bCoreMutex ){
12759f8c08eSdanielk1977     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
128fec00eabSdrh   }
129075c23afSdanielk1977   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
1307ff2719eSdrh       && sqlite3GlobalConfig.nScratch>0 ){
131badc980aSdrh     int i, n, sz;
132badc980aSdrh     ScratchFreeslot *pSlot;
133badc980aSdrh     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
134badc980aSdrh     sqlite3GlobalConfig.szScratch = sz;
135badc980aSdrh     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
136badc980aSdrh     n = sqlite3GlobalConfig.nScratch;
137badc980aSdrh     mem0.pScratchFree = pSlot;
138badc980aSdrh     mem0.nScratchFree = n;
139badc980aSdrh     for(i=0; i<n-1; i++){
140badc980aSdrh       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
141badc980aSdrh       pSlot = pSlot->pNext;
142badc980aSdrh     }
143badc980aSdrh     pSlot->pNext = 0;
144badc980aSdrh     mem0.pScratchEnd = (void*)&pSlot[1];
1459ac3fe97Sdrh   }else{
146badc980aSdrh     mem0.pScratchEnd = 0;
147075c23afSdanielk1977     sqlite3GlobalConfig.pScratch = 0;
148075c23afSdanielk1977     sqlite3GlobalConfig.szScratch = 0;
149badc980aSdrh     sqlite3GlobalConfig.nScratch = 0;
1509ac3fe97Sdrh   }
15150d1b5f3Sdrh   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
15250d1b5f3Sdrh       || sqlite3GlobalConfig.nPage<1 ){
153075c23afSdanielk1977     sqlite3GlobalConfig.pPage = 0;
154075c23afSdanielk1977     sqlite3GlobalConfig.szPage = 0;
15550d1b5f3Sdrh     sqlite3GlobalConfig.nPage = 0;
1569ac3fe97Sdrh   }
157075c23afSdanielk1977   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
158fec00eabSdrh }
159fec00eabSdrh 
160fec00eabSdrh /*
16150d1b5f3Sdrh ** Return true if the heap is currently under memory pressure - in other
16250d1b5f3Sdrh ** words if the amount of heap used is close to the limit set by
16350d1b5f3Sdrh ** sqlite3_soft_heap_limit().
16450d1b5f3Sdrh */
16550d1b5f3Sdrh int sqlite3HeapNearlyFull(void){
16650d1b5f3Sdrh   return mem0.nearlyFull;
16750d1b5f3Sdrh }
16850d1b5f3Sdrh 
16950d1b5f3Sdrh /*
170fec00eabSdrh ** Deinitialize the memory allocation subsystem.
171fec00eabSdrh */
172fec00eabSdrh void sqlite3MallocEnd(void){
1730a549071Sdanielk1977   if( sqlite3GlobalConfig.m.xShutdown ){
174075c23afSdanielk1977     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
1750a549071Sdanielk1977   }
1769ac3fe97Sdrh   memset(&mem0, 0, sizeof(mem0));
177fec00eabSdrh }
178fec00eabSdrh 
179fec00eabSdrh /*
180fec00eabSdrh ** Return the amount of memory currently checked out.
181fec00eabSdrh */
182fec00eabSdrh sqlite3_int64 sqlite3_memory_used(void){
183f7141990Sdrh   int n, mx;
184c376a198Sdrh   sqlite3_int64 res;
185f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
186c376a198Sdrh   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
187c376a198Sdrh   return res;
188fec00eabSdrh }
189fec00eabSdrh 
190fec00eabSdrh /*
191fec00eabSdrh ** Return the maximum amount of memory that has ever been
192fec00eabSdrh ** checked out since either the beginning of this process
193fec00eabSdrh ** or since the most recent reset.
194fec00eabSdrh */
195fec00eabSdrh sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
196f7141990Sdrh   int n, mx;
197c376a198Sdrh   sqlite3_int64 res;
198f7141990Sdrh   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
1997986a71aSdrh   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
200c376a198Sdrh   return res;
201fec00eabSdrh }
202fec00eabSdrh 
203fec00eabSdrh /*
204fec00eabSdrh ** Change the alarm callback
205fec00eabSdrh */
2064a27a286Sshane int sqlite3MemoryAlarm(
207fec00eabSdrh   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
208fec00eabSdrh   void *pArg,
209fec00eabSdrh   sqlite3_int64 iThreshold
210fec00eabSdrh ){
21150d1b5f3Sdrh   int nUsed;
212fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
213fec00eabSdrh   mem0.alarmCallback = xCallback;
214fec00eabSdrh   mem0.alarmArg = pArg;
215fec00eabSdrh   mem0.alarmThreshold = iThreshold;
21650d1b5f3Sdrh   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
21750d1b5f3Sdrh   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
218fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
219fec00eabSdrh   return SQLITE_OK;
220fec00eabSdrh }
221fec00eabSdrh 
222eec556d3Sshane #ifndef SQLITE_OMIT_DEPRECATED
223fec00eabSdrh /*
2244a27a286Sshane ** Deprecated external interface.  Internal/core SQLite code
2254a27a286Sshane ** should call sqlite3MemoryAlarm.
2264a27a286Sshane */
2274a27a286Sshane int sqlite3_memory_alarm(
2284a27a286Sshane   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
2294a27a286Sshane   void *pArg,
2304a27a286Sshane   sqlite3_int64 iThreshold
2314a27a286Sshane ){
2324a27a286Sshane   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
2334a27a286Sshane }
234eec556d3Sshane #endif
2354a27a286Sshane 
2364a27a286Sshane /*
237fec00eabSdrh ** Trigger the alarm
238fec00eabSdrh */
239fec00eabSdrh static void sqlite3MallocAlarm(int nByte){
240fec00eabSdrh   void (*xCallback)(void*,sqlite3_int64,int);
241fec00eabSdrh   sqlite3_int64 nowUsed;
242fec00eabSdrh   void *pArg;
243e64ca7baSdrh   if( mem0.alarmCallback==0 ) return;
244fec00eabSdrh   xCallback = mem0.alarmCallback;
245f7141990Sdrh   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
246fec00eabSdrh   pArg = mem0.alarmArg;
247e64ca7baSdrh   mem0.alarmCallback = 0;
248fec00eabSdrh   sqlite3_mutex_leave(mem0.mutex);
249fec00eabSdrh   xCallback(pArg, nowUsed, nByte);
250fec00eabSdrh   sqlite3_mutex_enter(mem0.mutex);
251e64ca7baSdrh   mem0.alarmCallback = xCallback;
252e64ca7baSdrh   mem0.alarmArg = pArg;
253fec00eabSdrh }
254fec00eabSdrh 
255fec00eabSdrh /*
256f7141990Sdrh ** Do a memory allocation with statistics and alarms.  Assume the
257f7141990Sdrh ** lock is already held.
258fec00eabSdrh */
259f7141990Sdrh static int mallocWithAlarm(int n, void **pp){
260fec00eabSdrh   int nFull;
261f7141990Sdrh   void *p;
262f7141990Sdrh   assert( sqlite3_mutex_held(mem0.mutex) );
263075c23afSdanielk1977   nFull = sqlite3GlobalConfig.m.xRoundup(n);
264f7141990Sdrh   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
265f7141990Sdrh   if( mem0.alarmCallback!=0 ){
266f7141990Sdrh     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
267f7141990Sdrh     if( nUsed+nFull >= mem0.alarmThreshold ){
26850d1b5f3Sdrh       mem0.nearlyFull = 1;
269fec00eabSdrh       sqlite3MallocAlarm(nFull);
27050d1b5f3Sdrh     }else{
27150d1b5f3Sdrh       mem0.nearlyFull = 0;
272fec00eabSdrh     }
273f7141990Sdrh   }
274075c23afSdanielk1977   p = sqlite3GlobalConfig.m.xMalloc(nFull);
27550d1b5f3Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
276d09414cdSdanielk1977   if( p==0 && mem0.alarmCallback ){
277fec00eabSdrh     sqlite3MallocAlarm(nFull);
278075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(nFull);
279fec00eabSdrh   }
28050d1b5f3Sdrh #endif
281c702c7ccSdrh   if( p ){
282c702c7ccSdrh     nFull = sqlite3MallocSize(p);
283c702c7ccSdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
284eafc43b1Sdrh     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
285c702c7ccSdrh   }
286f7141990Sdrh   *pp = p;
287f7141990Sdrh   return nFull;
288fec00eabSdrh }
289f7141990Sdrh 
290f7141990Sdrh /*
291f7141990Sdrh ** Allocate memory.  This routine is like sqlite3_malloc() except that it
292f7141990Sdrh ** assumes the memory subsystem has already been initialized.
293f7141990Sdrh */
294f7141990Sdrh void *sqlite3Malloc(int n){
295f7141990Sdrh   void *p;
29671a1a0f4Sdrh   if( n<=0               /* IMP: R-65312-04917 */
29771a1a0f4Sdrh    || n>=0x7fffff00
29871a1a0f4Sdrh   ){
299e08ed7e7Sdrh     /* A memory allocation of a number of bytes which is near the maximum
300e08ed7e7Sdrh     ** signed integer value might cause an integer overflow inside of the
301e08ed7e7Sdrh     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
302e08ed7e7Sdrh     ** 255 bytes of overhead.  SQLite itself will never use anything near
303e08ed7e7Sdrh     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
304f7141990Sdrh     p = 0;
305075c23afSdanielk1977   }else if( sqlite3GlobalConfig.bMemstat ){
306f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
307f7141990Sdrh     mallocWithAlarm(n, &p);
308fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
309fec00eabSdrh   }else{
310075c23afSdanielk1977     p = sqlite3GlobalConfig.m.xMalloc(n);
311fec00eabSdrh   }
312*39f67bebSdrh   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
313fec00eabSdrh   return p;
314fec00eabSdrh }
315fec00eabSdrh 
316fec00eabSdrh /*
317fec00eabSdrh ** This version of the memory allocation is for use by the application.
318fec00eabSdrh ** First make sure the memory subsystem is initialized, then do the
319fec00eabSdrh ** allocation.
320fec00eabSdrh */
321fec00eabSdrh void *sqlite3_malloc(int n){
322fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
323fec00eabSdrh   if( sqlite3_initialize() ) return 0;
324fec00eabSdrh #endif
325fec00eabSdrh   return sqlite3Malloc(n);
326fec00eabSdrh }
327fec00eabSdrh 
328fec00eabSdrh /*
329e5ae5735Sdrh ** Each thread may only have a single outstanding allocation from
330facf0307Sdrh ** xScratchMalloc().  We verify this constraint in the single-threaded
331facf0307Sdrh ** case by setting scratchAllocOut to 1 when an allocation
332e5ae5735Sdrh ** is outstanding clearing it when the allocation is freed.
333e5ae5735Sdrh */
334e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
335facf0307Sdrh static int scratchAllocOut = 0;
336e5ae5735Sdrh #endif
337e5ae5735Sdrh 
338e5ae5735Sdrh 
339e5ae5735Sdrh /*
340e5ae5735Sdrh ** Allocate memory that is to be used and released right away.
341e5ae5735Sdrh ** This routine is similar to alloca() in that it is not intended
342e5ae5735Sdrh ** for situations where the memory might be held long-term.  This
343e5ae5735Sdrh ** routine is intended to get memory to old large transient data
344e5ae5735Sdrh ** structures that would not normally fit on the stack of an
345e5ae5735Sdrh ** embedded processor.
346e5ae5735Sdrh */
347facf0307Sdrh void *sqlite3ScratchMalloc(int n){
348e5ae5735Sdrh   void *p;
349e5ae5735Sdrh   assert( n>0 );
3509ac3fe97Sdrh 
351badc980aSdrh   sqlite3_mutex_enter(mem0.mutex);
352badc980aSdrh   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
353badc980aSdrh     p = mem0.pScratchFree;
354badc980aSdrh     mem0.pScratchFree = mem0.pScratchFree->pNext;
355badc980aSdrh     mem0.nScratchFree--;
356badc980aSdrh     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
357badc980aSdrh     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
358b0c6a888Sdan     sqlite3_mutex_leave(mem0.mutex);
359badc980aSdrh   }else{
360badc980aSdrh     if( sqlite3GlobalConfig.bMemstat ){
361badc980aSdrh       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
362badc980aSdrh       n = mallocWithAlarm(n, &p);
363badc980aSdrh       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
364b0c6a888Sdan       sqlite3_mutex_leave(mem0.mutex);
365badc980aSdrh     }else{
366b0c6a888Sdan       sqlite3_mutex_leave(mem0.mutex);
367badc980aSdrh       p = sqlite3GlobalConfig.m.xMalloc(n);
368badc980aSdrh     }
369badc980aSdrh     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
370badc980aSdrh   }
3711ff6e3abSdrh   assert( sqlite3_mutex_notheld(mem0.mutex) );
372b0c6a888Sdan 
373badc980aSdrh 
374badc980aSdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
375badc980aSdrh   /* Verify that no more than two scratch allocations per thread
376badc980aSdrh   ** are outstanding at one time.  (This is only checked in the
377badc980aSdrh   ** single-threaded case since checking in the multi-threaded case
378badc980aSdrh   ** would be much more complicated.) */
379badc980aSdrh   assert( scratchAllocOut<=1 );
380badc980aSdrh   if( p ) scratchAllocOut++;
381badc980aSdrh #endif
382badc980aSdrh 
383badc980aSdrh   return p;
384badc980aSdrh }
385badc980aSdrh void sqlite3ScratchFree(void *p){
386badc980aSdrh   if( p ){
387badc980aSdrh 
388e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
38937f99187Sdrh     /* Verify that no more than two scratch allocation per thread
3909ac3fe97Sdrh     ** is outstanding at one time.  (This is only checked in the
3919ac3fe97Sdrh     ** single-threaded case since checking in the multi-threaded case
3929ac3fe97Sdrh     ** would be much more complicated.) */
393badc980aSdrh     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
394badc980aSdrh     scratchAllocOut--;
395e5ae5735Sdrh #endif
3969ac3fe97Sdrh 
397badc980aSdrh     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
398badc980aSdrh       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
399badc980aSdrh       ScratchFreeslot *pSlot;
400badc980aSdrh       pSlot = (ScratchFreeslot*)p;
401e5ae5735Sdrh       sqlite3_mutex_enter(mem0.mutex);
402badc980aSdrh       pSlot->pNext = mem0.pScratchFree;
403badc980aSdrh       mem0.pScratchFree = pSlot;
404badc980aSdrh       mem0.nScratchFree++;
405badc980aSdrh       assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
406badc980aSdrh       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
4079ac3fe97Sdrh       sqlite3_mutex_leave(mem0.mutex);
408f7141990Sdrh     }else{
409badc980aSdrh       /* Release memory back to the heap */
410107b56e8Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
411174b9a16Sdrh       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
412107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
413075c23afSdanielk1977       if( sqlite3GlobalConfig.bMemstat ){
414f7141990Sdrh         int iSize = sqlite3MallocSize(p);
415f7141990Sdrh         sqlite3_mutex_enter(mem0.mutex);
416f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
417f7141990Sdrh         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
41881ba7d16Sdrh         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
419075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
420f7141990Sdrh         sqlite3_mutex_leave(mem0.mutex);
421f7141990Sdrh       }else{
422075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
423f7141990Sdrh       }
4249ac3fe97Sdrh     }
425e5ae5735Sdrh   }
426e5ae5735Sdrh }
427e5ae5735Sdrh 
428e5ae5735Sdrh /*
429633e6d57Sdrh ** TRUE if p is a lookaside memory allocation from db
430633e6d57Sdrh */
4314150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
432633e6d57Sdrh static int isLookaside(sqlite3 *db, void *p){
433174b9a16Sdrh   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
434633e6d57Sdrh }
4354150ebf8Sdrh #else
4364150ebf8Sdrh #define isLookaside(A,B) 0
4374150ebf8Sdrh #endif
438633e6d57Sdrh 
439633e6d57Sdrh /*
440fec00eabSdrh ** Return the size of a memory allocation previously obtained from
441fec00eabSdrh ** sqlite3Malloc() or sqlite3_malloc().
442fec00eabSdrh */
443fec00eabSdrh int sqlite3MallocSize(void *p){
444107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
445174b9a16Sdrh   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
446075c23afSdanielk1977   return sqlite3GlobalConfig.m.xSize(p);
447fec00eabSdrh }
448633e6d57Sdrh int sqlite3DbMallocSize(sqlite3 *db, void *p){
4497047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
450174b9a16Sdrh   if( db && isLookaside(db, p) ){
451633e6d57Sdrh     return db->lookaside.sz;
452633e6d57Sdrh   }else{
453174b9a16Sdrh     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
454174b9a16Sdrh     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
455174b9a16Sdrh     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
456075c23afSdanielk1977     return sqlite3GlobalConfig.m.xSize(p);
457633e6d57Sdrh   }
458633e6d57Sdrh }
459fec00eabSdrh 
460fec00eabSdrh /*
461fec00eabSdrh ** Free memory previously obtained from sqlite3Malloc().
462fec00eabSdrh */
463fec00eabSdrh void sqlite3_free(void *p){
46471a1a0f4Sdrh   if( p==0 ) return;  /* IMP: R-49053-54554 */
465174b9a16Sdrh   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
466107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
467075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
468fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
469f7141990Sdrh     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
470eafc43b1Sdrh     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
471075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
472fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
473fec00eabSdrh   }else{
474075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
475fec00eabSdrh   }
476fec00eabSdrh }
477fec00eabSdrh 
478fec00eabSdrh /*
479633e6d57Sdrh ** Free memory that might be associated with a particular database
480633e6d57Sdrh ** connection.
481633e6d57Sdrh */
482633e6d57Sdrh void sqlite3DbFree(sqlite3 *db, void *p){
4837047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
484174b9a16Sdrh   if( db ){
485174b9a16Sdrh     if( db->pnBytesFreed ){
486174b9a16Sdrh       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
487174b9a16Sdrh       return;
488d46def77Sdan     }
489633e6d57Sdrh     if( isLookaside(db, p) ){
490633e6d57Sdrh       LookasideSlot *pBuf = (LookasideSlot*)p;
491633e6d57Sdrh       pBuf->pNext = db->lookaside.pFree;
492633e6d57Sdrh       db->lookaside.pFree = pBuf;
493633e6d57Sdrh       db->lookaside.nOut--;
494174b9a16Sdrh       return;
495174b9a16Sdrh     }
496174b9a16Sdrh   }
497174b9a16Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
498174b9a16Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
499174b9a16Sdrh   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
500107b56e8Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
501633e6d57Sdrh   sqlite3_free(p);
502633e6d57Sdrh }
503633e6d57Sdrh 
504633e6d57Sdrh /*
505fec00eabSdrh ** Change the size of an existing memory allocation
506fec00eabSdrh */
507fec00eabSdrh void *sqlite3Realloc(void *pOld, int nBytes){
508fec00eabSdrh   int nOld, nNew;
509fec00eabSdrh   void *pNew;
510fec00eabSdrh   if( pOld==0 ){
51171a1a0f4Sdrh     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
512fec00eabSdrh   }
513b6063cf8Sdrh   if( nBytes<=0 ){
51471a1a0f4Sdrh     sqlite3_free(pOld); /* IMP: R-31593-10574 */
515fec00eabSdrh     return 0;
516fec00eabSdrh   }
517b6063cf8Sdrh   if( nBytes>=0x7fffff00 ){
518b6063cf8Sdrh     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
519b6063cf8Sdrh     return 0;
520b6063cf8Sdrh   }
521fec00eabSdrh   nOld = sqlite3MallocSize(pOld);
5229f129f46Sdrh   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
5239f129f46Sdrh   ** argument to xRealloc is always a value returned by a prior call to
5249f129f46Sdrh   ** xRoundup. */
525075c23afSdanielk1977   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
526fec00eabSdrh   if( nOld==nNew ){
527fec00eabSdrh     pNew = pOld;
5287c6791c8Sdrh   }else if( sqlite3GlobalConfig.bMemstat ){
5297c6791c8Sdrh     sqlite3_mutex_enter(mem0.mutex);
5307c6791c8Sdrh     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
531f7141990Sdrh     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
532f7141990Sdrh           mem0.alarmThreshold ){
533fec00eabSdrh       sqlite3MallocAlarm(nNew-nOld);
534fec00eabSdrh     }
535107b56e8Sdrh     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
536174b9a16Sdrh     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
537075c23afSdanielk1977     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
538d09414cdSdanielk1977     if( pNew==0 && mem0.alarmCallback ){
539fec00eabSdrh       sqlite3MallocAlarm(nBytes);
540075c23afSdanielk1977       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
541fec00eabSdrh     }
542fec00eabSdrh     if( pNew ){
543c702c7ccSdrh       nNew = sqlite3MallocSize(pNew);
544f7141990Sdrh       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
545fec00eabSdrh     }
546fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
547fec00eabSdrh   }else{
5487c6791c8Sdrh     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
549fec00eabSdrh   }
550*39f67bebSdrh   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
551fec00eabSdrh   return pNew;
552fec00eabSdrh }
553fec00eabSdrh 
554fec00eabSdrh /*
555fec00eabSdrh ** The public interface to sqlite3Realloc.  Make sure that the memory
556fec00eabSdrh ** subsystem is initialized prior to invoking sqliteRealloc.
557fec00eabSdrh */
558fec00eabSdrh void *sqlite3_realloc(void *pOld, int n){
559fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
560fec00eabSdrh   if( sqlite3_initialize() ) return 0;
561fec00eabSdrh #endif
562fec00eabSdrh   return sqlite3Realloc(pOld, n);
563fec00eabSdrh }
564fec00eabSdrh 
565a3152895Sdrh 
566a3152895Sdrh /*
56717435752Sdrh ** Allocate and zero memory.
568a3152895Sdrh */
569fec00eabSdrh void *sqlite3MallocZero(int n){
570fec00eabSdrh   void *p = sqlite3Malloc(n);
571a3152895Sdrh   if( p ){
572a3152895Sdrh     memset(p, 0, n);
573a3152895Sdrh   }
574a3152895Sdrh   return p;
575a3152895Sdrh }
57617435752Sdrh 
57717435752Sdrh /*
57817435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
57917435752Sdrh ** the mallocFailed flag in the connection pointer.
58017435752Sdrh */
581fec00eabSdrh void *sqlite3DbMallocZero(sqlite3 *db, int n){
582a1644fd8Sdanielk1977   void *p = sqlite3DbMallocRaw(db, n);
58317435752Sdrh   if( p ){
58417435752Sdrh     memset(p, 0, n);
58517435752Sdrh   }
58617435752Sdrh   return p;
58717435752Sdrh }
58817435752Sdrh 
58917435752Sdrh /*
59017435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
59117435752Sdrh ** the mallocFailed flag in the connection pointer.
592ddecae79Sdrh **
593ddecae79Sdrh ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
594ddecae79Sdrh ** failure on the same database connection) then always return 0.
595ddecae79Sdrh ** Hence for a particular database connection, once malloc starts
596ddecae79Sdrh ** failing, it fails consistently until mallocFailed is reset.
597ddecae79Sdrh ** This is an important assumption.  There are many places in the
598ddecae79Sdrh ** code that do things like this:
599ddecae79Sdrh **
600ddecae79Sdrh **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
601ddecae79Sdrh **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
602ddecae79Sdrh **         if( b ) a[10] = 9;
603ddecae79Sdrh **
604ddecae79Sdrh ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
605ddecae79Sdrh ** that all prior mallocs (ex: "a") worked too.
60617435752Sdrh */
607fec00eabSdrh void *sqlite3DbMallocRaw(sqlite3 *db, int n){
608633e6d57Sdrh   void *p;
609d9da78a2Sdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
610ccd4ad3eSdan   assert( db==0 || db->pnBytesFreed==0 );
6114150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
612633e6d57Sdrh   if( db ){
613633e6d57Sdrh     LookasideSlot *pBuf;
614633e6d57Sdrh     if( db->mallocFailed ){
615633e6d57Sdrh       return 0;
616633e6d57Sdrh     }
617633e6d57Sdrh     if( db->lookaside.bEnabled && n<=db->lookaside.sz
618633e6d57Sdrh          && (pBuf = db->lookaside.pFree)!=0 ){
619633e6d57Sdrh       db->lookaside.pFree = pBuf->pNext;
620633e6d57Sdrh       db->lookaside.nOut++;
621633e6d57Sdrh       if( db->lookaside.nOut>db->lookaside.mxOut ){
622633e6d57Sdrh         db->lookaside.mxOut = db->lookaside.nOut;
623633e6d57Sdrh       }
624633e6d57Sdrh       return (void*)pBuf;
625633e6d57Sdrh     }
626633e6d57Sdrh   }
627ddecae79Sdrh #else
628ddecae79Sdrh   if( db && db->mallocFailed ){
629ddecae79Sdrh     return 0;
630ddecae79Sdrh   }
6314150ebf8Sdrh #endif
632fec00eabSdrh   p = sqlite3Malloc(n);
633f3a65f7eSdrh   if( !p && db ){
63417435752Sdrh     db->mallocFailed = 1;
63517435752Sdrh   }
636174b9a16Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_DB |
637174b9a16Sdrh          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
63817435752Sdrh   return p;
63917435752Sdrh }
64017435752Sdrh 
64126783a58Sdanielk1977 /*
64226783a58Sdanielk1977 ** Resize the block of memory pointed to by p to n bytes. If the
64326783a58Sdanielk1977 ** resize fails, set the mallocFailed flag in the connection object.
64426783a58Sdanielk1977 */
645a1644fd8Sdanielk1977 void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
646a1644fd8Sdanielk1977   void *pNew = 0;
647d9da78a2Sdrh   assert( db!=0 );
6487047e25cSdrh   assert( sqlite3_mutex_held(db->mutex) );
649a1644fd8Sdanielk1977   if( db->mallocFailed==0 ){
650633e6d57Sdrh     if( p==0 ){
651633e6d57Sdrh       return sqlite3DbMallocRaw(db, n);
652633e6d57Sdrh     }
653633e6d57Sdrh     if( isLookaside(db, p) ){
654633e6d57Sdrh       if( n<=db->lookaside.sz ){
655633e6d57Sdrh         return p;
656633e6d57Sdrh       }
657633e6d57Sdrh       pNew = sqlite3DbMallocRaw(db, n);
658633e6d57Sdrh       if( pNew ){
659633e6d57Sdrh         memcpy(pNew, p, db->lookaside.sz);
660633e6d57Sdrh         sqlite3DbFree(db, p);
661633e6d57Sdrh       }
662633e6d57Sdrh     }else{
663174b9a16Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
664174b9a16Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
665107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
666a1644fd8Sdanielk1977       pNew = sqlite3_realloc(p, n);
667a1644fd8Sdanielk1977       if( !pNew ){
668174b9a16Sdrh         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
669a1644fd8Sdanielk1977         db->mallocFailed = 1;
670a1644fd8Sdanielk1977       }
671174b9a16Sdrh       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
672174b9a16Sdrh             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
673a1644fd8Sdanielk1977     }
674633e6d57Sdrh   }
675a1644fd8Sdanielk1977   return pNew;
676a1644fd8Sdanielk1977 }
677a1644fd8Sdanielk1977 
67817435752Sdrh /*
67917435752Sdrh ** Attempt to reallocate p.  If the reallocation fails, then free p
68017435752Sdrh ** and set the mallocFailed flag in the database connection.
68117435752Sdrh */
68217435752Sdrh void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
683a3152895Sdrh   void *pNew;
684a1644fd8Sdanielk1977   pNew = sqlite3DbRealloc(db, p, n);
685a3152895Sdrh   if( !pNew ){
686633e6d57Sdrh     sqlite3DbFree(db, p);
687a3152895Sdrh   }
688a3152895Sdrh   return pNew;
689a3152895Sdrh }
690a3152895Sdrh 
691a3152895Sdrh /*
692a3152895Sdrh ** Make a copy of a string in memory obtained from sqliteMalloc(). These
693a3152895Sdrh ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
694a3152895Sdrh ** is because when memory debugging is turned on, these two functions are
695a3152895Sdrh ** called via macros that record the current file and line number in the
696a3152895Sdrh ** ThreadData structure.
697a3152895Sdrh */
698633e6d57Sdrh char *sqlite3DbStrDup(sqlite3 *db, const char *z){
699a3152895Sdrh   char *zNew;
700633e6d57Sdrh   size_t n;
701633e6d57Sdrh   if( z==0 ){
702633e6d57Sdrh     return 0;
703a3152895Sdrh   }
704dee0e404Sdrh   n = sqlite3Strlen30(z) + 1;
705633e6d57Sdrh   assert( (n&0x7fffffff)==n );
706633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, (int)n);
707a3152895Sdrh   if( zNew ){
708a3152895Sdrh     memcpy(zNew, z, n);
7091e536953Sdanielk1977   }
7101e536953Sdanielk1977   return zNew;
7111e536953Sdanielk1977 }
7121e536953Sdanielk1977 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
713633e6d57Sdrh   char *zNew;
714633e6d57Sdrh   if( z==0 ){
715633e6d57Sdrh     return 0;
716633e6d57Sdrh   }
717633e6d57Sdrh   assert( (n&0x7fffffff)==n );
718633e6d57Sdrh   zNew = sqlite3DbMallocRaw(db, n+1);
719633e6d57Sdrh   if( zNew ){
720633e6d57Sdrh     memcpy(zNew, z, n);
721633e6d57Sdrh     zNew[n] = 0;
7221e536953Sdanielk1977   }
7231e536953Sdanielk1977   return zNew;
7241e536953Sdanielk1977 }
7251e536953Sdanielk1977 
726a3152895Sdrh /*
727f089aa45Sdrh ** Create a string from the zFromat argument and the va_list that follows.
728f089aa45Sdrh ** Store the string in memory obtained from sqliteMalloc() and make *pz
729f089aa45Sdrh ** point to that string.
730a3152895Sdrh */
731f089aa45Sdrh void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
732a3152895Sdrh   va_list ap;
733f089aa45Sdrh   char *z;
734a3152895Sdrh 
735f089aa45Sdrh   va_start(ap, zFormat);
736f089aa45Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
737a3152895Sdrh   va_end(ap);
738633e6d57Sdrh   sqlite3DbFree(db, *pz);
739f089aa45Sdrh   *pz = z;
740a3152895Sdrh }
741a3152895Sdrh 
742a3152895Sdrh 
743a3152895Sdrh /*
744a3152895Sdrh ** This function must be called before exiting any API function (i.e.
74517435752Sdrh ** returning control to the user) that has called sqlite3_malloc or
74617435752Sdrh ** sqlite3_realloc.
747a3152895Sdrh **
748a3152895Sdrh ** The returned value is normally a copy of the second argument to this
749be217793Sshane ** function. However, if a malloc() failure has occurred since the previous
750a3152895Sdrh ** invocation SQLITE_NOMEM is returned instead.
751a3152895Sdrh **
752be217793Sshane ** If the first argument, db, is not NULL and a malloc() error has occurred,
753a3152895Sdrh ** then the connection error-code (the value returned by sqlite3_errcode())
754a3152895Sdrh ** is set to SQLITE_NOMEM.
755a3152895Sdrh */
756a3152895Sdrh int sqlite3ApiExit(sqlite3* db, int rc){
757a1644fd8Sdanielk1977   /* If the db handle is not NULL, then we must hold the connection handle
758a1644fd8Sdanielk1977   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
759a1644fd8Sdanielk1977   ** is unsafe, as is the call to sqlite3Error().
760a1644fd8Sdanielk1977   */
761a1644fd8Sdanielk1977   assert( !db || sqlite3_mutex_held(db->mutex) );
76298c21903Sdanielk1977   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
763a3152895Sdrh     sqlite3Error(db, SQLITE_NOMEM, 0);
76417435752Sdrh     db->mallocFailed = 0;
765a3152895Sdrh     rc = SQLITE_NOMEM;
766a3152895Sdrh   }
767a3152895Sdrh   return rc & (db ? db->errMask : 0xff);
768a3152895Sdrh }
769