xref: /sqlite-3.40.0/src/malloc.c (revision 25bb72a7)
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 /*
198468024dSdanielk1977 ** Attempt to release up to n bytes of non-essential memory currently
208468024dSdanielk1977 ** held by SQLite. An example of non-essential memory is memory used to
218468024dSdanielk1977 ** cache database pages that are not currently in use.
22a3152895Sdrh */
23a3152895Sdrh int sqlite3_release_memory(int n){
2486f8c197Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
259f129f46Sdrh   return sqlite3PcacheReleaseMemory(n);
261e536953Sdanielk1977 #else
279f129f46Sdrh   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
289f129f46Sdrh   ** is a no-op returning zero if SQLite is not compiled with
299f129f46Sdrh   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
3062c14b34Sdanielk1977   UNUSED_PARAMETER(n);
319f129f46Sdrh   return 0;
321e536953Sdanielk1977 #endif
33a3152895Sdrh }
34a3152895Sdrh 
35fec00eabSdrh /*
3631999c5cSdrh ** Default value of the hard heap limit.  0 means "no limit".
3731999c5cSdrh */
3831999c5cSdrh #ifndef SQLITE_MAX_MEMORY
3931999c5cSdrh # define SQLITE_MAX_MEMORY 0
4031999c5cSdrh #endif
4131999c5cSdrh 
4231999c5cSdrh /*
43fec00eabSdrh ** State information local to the memory allocation subsystem.
44fec00eabSdrh */
455c8f8587Sdanielk1977 static SQLITE_WSD struct Mem0Global {
46fec00eabSdrh   sqlite3_mutex *mutex;         /* Mutex to serialize access */
474ef299a3Sdrh   sqlite3_int64 alarmThreshold; /* The soft heap limit */
4810c0e711Sdrh   sqlite3_int64 hardLimit;      /* The hard upper bound on memory */
49fec00eabSdrh 
50fec00eabSdrh   /*
5150d1b5f3Sdrh   ** True if heap is nearly "full" where "full" is defined by the
5250d1b5f3Sdrh   ** sqlite3_soft_heap_limit() setting.
5350d1b5f3Sdrh   */
5450d1b5f3Sdrh   int nearlyFull;
5531999c5cSdrh } mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
565c8f8587Sdanielk1977 
575c8f8587Sdanielk1977 #define mem0 GLOBAL(struct Mem0Global, mem0)
58fec00eabSdrh 
59fec00eabSdrh /*
60af89fe66Sdrh ** Return the memory allocator mutex. sqlite3_status() needs it.
61af89fe66Sdrh */
62af89fe66Sdrh sqlite3_mutex *sqlite3MallocMutex(void){
63af89fe66Sdrh   return mem0.mutex;
64af89fe66Sdrh }
65af89fe66Sdrh 
66f82ccf64Sdrh #ifndef SQLITE_OMIT_DEPRECATED
67f82ccf64Sdrh /*
685fb72e5fSdrh ** Deprecated external interface.  It used to set an alarm callback
695fb72e5fSdrh ** that was invoked when memory usage grew too large.  Now it is a
705fb72e5fSdrh ** no-op.
71f82ccf64Sdrh */
72f82ccf64Sdrh int sqlite3_memory_alarm(
73f82ccf64Sdrh   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
74f82ccf64Sdrh   void *pArg,
75f82ccf64Sdrh   sqlite3_int64 iThreshold
76f82ccf64Sdrh ){
775fb72e5fSdrh   (void)xCallback;
785fb72e5fSdrh   (void)pArg;
795fb72e5fSdrh   (void)iThreshold;
804ef299a3Sdrh   return SQLITE_OK;
81f82ccf64Sdrh }
82f82ccf64Sdrh #endif
83f82ccf64Sdrh 
84f82ccf64Sdrh /*
8510c0e711Sdrh ** Set the soft heap-size limit for the library.  An argument of
8610c0e711Sdrh ** zero disables the limit.  A negative argument is a no-op used to
8710c0e711Sdrh ** obtain the return value.
8810c0e711Sdrh **
8910c0e711Sdrh ** The return value is the value of the heap limit just before this
9010c0e711Sdrh ** interface was called.
9110c0e711Sdrh **
9210c0e711Sdrh ** If the hard heap limit is enabled, then the soft heap limit cannot
9310c0e711Sdrh ** be disabled nor raised above the hard heap limit.
94f82ccf64Sdrh */
95f82ccf64Sdrh sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
96f82ccf64Sdrh   sqlite3_int64 priorLimit;
975fb72e5fSdrh   sqlite3_int64 excess;
985fb72e5fSdrh   sqlite3_int64 nUsed;
99f82ccf64Sdrh #ifndef SQLITE_OMIT_AUTOINIT
100de0f1815Sdrh   int rc = sqlite3_initialize();
101de0f1815Sdrh   if( rc ) return -1;
102f82ccf64Sdrh #endif
103f82ccf64Sdrh   sqlite3_mutex_enter(mem0.mutex);
104f82ccf64Sdrh   priorLimit = mem0.alarmThreshold;
1055fb72e5fSdrh   if( n<0 ){
1064ef299a3Sdrh     sqlite3_mutex_leave(mem0.mutex);
107f82ccf64Sdrh     return priorLimit;
108f82ccf64Sdrh   }
10910c0e711Sdrh   if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){
11010c0e711Sdrh     n = mem0.hardLimit;
11110c0e711Sdrh   }
1125fb72e5fSdrh   mem0.alarmThreshold = n;
1135fb72e5fSdrh   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
11423bef340Sdrh   AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);
1155fb72e5fSdrh   sqlite3_mutex_leave(mem0.mutex);
1165fb72e5fSdrh   excess = sqlite3_memory_used() - n;
1175fb72e5fSdrh   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
1185fb72e5fSdrh   return priorLimit;
1195fb72e5fSdrh }
120f82ccf64Sdrh void sqlite3_soft_heap_limit(int n){
121f82ccf64Sdrh   if( n<0 ) n = 0;
122f82ccf64Sdrh   sqlite3_soft_heap_limit64(n);
123f82ccf64Sdrh }
124f82ccf64Sdrh 
125f82ccf64Sdrh /*
12610c0e711Sdrh ** Set the hard heap-size limit for the library. An argument of zero
12710c0e711Sdrh ** disables the hard heap limit.  A negative argument is a no-op used
12810c0e711Sdrh ** to obtain the return value without affecting the hard heap limit.
12910c0e711Sdrh **
13010c0e711Sdrh ** The return value is the value of the hard heap limit just prior to
13110c0e711Sdrh ** calling this interface.
13210c0e711Sdrh **
13310c0e711Sdrh ** Setting the hard heap limit will also activate the soft heap limit
13410c0e711Sdrh ** and constrain the soft heap limit to be no more than the hard heap
13510c0e711Sdrh ** limit.
13610c0e711Sdrh */
13710c0e711Sdrh sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
13810c0e711Sdrh   sqlite3_int64 priorLimit;
13910c0e711Sdrh #ifndef SQLITE_OMIT_AUTOINIT
14010c0e711Sdrh   int rc = sqlite3_initialize();
14110c0e711Sdrh   if( rc ) return -1;
14210c0e711Sdrh #endif
14310c0e711Sdrh   sqlite3_mutex_enter(mem0.mutex);
14410c0e711Sdrh   priorLimit = mem0.hardLimit;
14510c0e711Sdrh   if( n>=0 ){
14610c0e711Sdrh     mem0.hardLimit = n;
14710c0e711Sdrh     if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){
14810c0e711Sdrh       mem0.alarmThreshold = n;
14910c0e711Sdrh     }
15010c0e711Sdrh   }
15110c0e711Sdrh   sqlite3_mutex_leave(mem0.mutex);
15210c0e711Sdrh   return priorLimit;
15310c0e711Sdrh }
15410c0e711Sdrh 
15510c0e711Sdrh 
15610c0e711Sdrh /*
157fec00eabSdrh ** Initialize the memory allocation subsystem.
158fec00eabSdrh */
159fec00eabSdrh int sqlite3MallocInit(void){
160592f0cb1Sdrh   int rc;
161075c23afSdanielk1977   if( sqlite3GlobalConfig.m.xMalloc==0 ){
162fec00eabSdrh     sqlite3MemSetDefault();
163fec00eabSdrh   }
16459f8c08eSdanielk1977   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16550d1b5f3Sdrh   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
16601c5c00cSdrh       || sqlite3GlobalConfig.nPage<=0 ){
167075c23afSdanielk1977     sqlite3GlobalConfig.pPage = 0;
168075c23afSdanielk1977     sqlite3GlobalConfig.szPage = 0;
1699ac3fe97Sdrh   }
170592f0cb1Sdrh   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
171592f0cb1Sdrh   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
172592f0cb1Sdrh   return rc;
173fec00eabSdrh }
174fec00eabSdrh 
175fec00eabSdrh /*
17650d1b5f3Sdrh ** Return true if the heap is currently under memory pressure - in other
17750d1b5f3Sdrh ** words if the amount of heap used is close to the limit set by
17850d1b5f3Sdrh ** sqlite3_soft_heap_limit().
17950d1b5f3Sdrh */
18050d1b5f3Sdrh int sqlite3HeapNearlyFull(void){
1819f603fceSdrh   return AtomicLoad(&mem0.nearlyFull);
18250d1b5f3Sdrh }
18350d1b5f3Sdrh 
18450d1b5f3Sdrh /*
185fec00eabSdrh ** Deinitialize the memory allocation subsystem.
186fec00eabSdrh */
187fec00eabSdrh void sqlite3MallocEnd(void){
1880a549071Sdanielk1977   if( sqlite3GlobalConfig.m.xShutdown ){
189075c23afSdanielk1977     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
1900a549071Sdanielk1977   }
1919ac3fe97Sdrh   memset(&mem0, 0, sizeof(mem0));
192fec00eabSdrh }
193fec00eabSdrh 
194fec00eabSdrh /*
195fec00eabSdrh ** Return the amount of memory currently checked out.
196fec00eabSdrh */
197fec00eabSdrh sqlite3_int64 sqlite3_memory_used(void){
198df5e1a00Sdrh   sqlite3_int64 res, mx;
199df5e1a00Sdrh   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
200c376a198Sdrh   return res;
201fec00eabSdrh }
202fec00eabSdrh 
203fec00eabSdrh /*
204fec00eabSdrh ** Return the maximum amount of memory that has ever been
205fec00eabSdrh ** checked out since either the beginning of this process
206fec00eabSdrh ** or since the most recent reset.
207fec00eabSdrh */
208fec00eabSdrh sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
209df5e1a00Sdrh   sqlite3_int64 res, mx;
210df5e1a00Sdrh   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
211df5e1a00Sdrh   return mx;
212fec00eabSdrh }
213fec00eabSdrh 
214fec00eabSdrh /*
2155fb72e5fSdrh ** Trigger the alarm
2165fb72e5fSdrh */
2175fb72e5fSdrh static void sqlite3MallocAlarm(int nByte){
2185fb72e5fSdrh   if( mem0.alarmThreshold<=0 ) return;
2195fb72e5fSdrh   sqlite3_mutex_leave(mem0.mutex);
2205fb72e5fSdrh   sqlite3_release_memory(nByte);
2215fb72e5fSdrh   sqlite3_mutex_enter(mem0.mutex);
2225fb72e5fSdrh }
2235fb72e5fSdrh 
2245fb72e5fSdrh /*
225f7141990Sdrh ** Do a memory allocation with statistics and alarms.  Assume the
226f7141990Sdrh ** lock is already held.
227fec00eabSdrh */
2281d21bac8Sdrh static void mallocWithAlarm(int n, void **pp){
229f7141990Sdrh   void *p;
230087a29c7Sdrh   int nFull;
231f7141990Sdrh   assert( sqlite3_mutex_held(mem0.mutex) );
232087a29c7Sdrh   assert( n>0 );
233087a29c7Sdrh 
23440b84365Smistachkin   /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
235087a29c7Sdrh   ** implementation of malloc_good_size(), which must be called in debug
236087a29c7Sdrh   ** mode and specifically when the DMD "Dark Matter Detector" is enabled
23740b84365Smistachkin   ** or else a crash results.  Hence, do not attempt to optimize out the
23840b84365Smistachkin   ** following xRoundup() call. */
239087a29c7Sdrh   nFull = sqlite3GlobalConfig.m.xRoundup(n);
240087a29c7Sdrh 
241b02392e6Sdrh   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
2425fb72e5fSdrh   if( mem0.alarmThreshold>0 ){
2435fb72e5fSdrh     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
2445fb72e5fSdrh     if( nUsed >= mem0.alarmThreshold - nFull ){
24523bef340Sdrh       AtomicStore(&mem0.nearlyFull, 1);
2465fb72e5fSdrh       sqlite3MallocAlarm(nFull);
24710c0e711Sdrh       if( mem0.hardLimit ){
24810c0e711Sdrh         nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24910c0e711Sdrh         if( nUsed >= mem0.hardLimit - nFull ){
25010c0e711Sdrh           *pp = 0;
25110c0e711Sdrh           return;
25210c0e711Sdrh         }
25310c0e711Sdrh       }
2545fb72e5fSdrh     }else{
25523bef340Sdrh       AtomicStore(&mem0.nearlyFull, 0);
2565fb72e5fSdrh     }
2575fb72e5fSdrh   }
258087a29c7Sdrh   p = sqlite3GlobalConfig.m.xMalloc(nFull);
25950d1b5f3Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
2605fb72e5fSdrh   if( p==0 && mem0.alarmThreshold>0 ){
2615fb72e5fSdrh     sqlite3MallocAlarm(nFull);
262087a29c7Sdrh     p = sqlite3GlobalConfig.m.xMalloc(nFull);
263fec00eabSdrh   }
26450d1b5f3Sdrh #endif
265c702c7ccSdrh   if( p ){
266be7a0ceeSdrh     nFull = sqlite3MallocSize(p);
267af89fe66Sdrh     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
268af89fe66Sdrh     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
269c702c7ccSdrh   }
270f7141990Sdrh   *pp = p;
271fec00eabSdrh }
272f7141990Sdrh 
273f7141990Sdrh /*
274f7141990Sdrh ** Allocate memory.  This routine is like sqlite3_malloc() except that it
275f7141990Sdrh ** assumes the memory subsystem has already been initialized.
276f7141990Sdrh */
277da4ca9d1Sdrh void *sqlite3Malloc(u64 n){
278f7141990Sdrh   void *p;
279da4ca9d1Sdrh   if( n==0 || n>=0x7fffff00 ){
280e08ed7e7Sdrh     /* A memory allocation of a number of bytes which is near the maximum
281e08ed7e7Sdrh     ** signed integer value might cause an integer overflow inside of the
282e08ed7e7Sdrh     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
283e08ed7e7Sdrh     ** 255 bytes of overhead.  SQLite itself will never use anything near
284e08ed7e7Sdrh     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
285f7141990Sdrh     p = 0;
286075c23afSdanielk1977   }else if( sqlite3GlobalConfig.bMemstat ){
287f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
2883329a63aSdrh     mallocWithAlarm((int)n, &p);
289fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
290fec00eabSdrh   }else{
291da4ca9d1Sdrh     p = sqlite3GlobalConfig.m.xMalloc((int)n);
292fec00eabSdrh   }
2938da47419Sdrh   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
294fec00eabSdrh   return p;
295fec00eabSdrh }
296fec00eabSdrh 
297fec00eabSdrh /*
298fec00eabSdrh ** This version of the memory allocation is for use by the application.
299fec00eabSdrh ** First make sure the memory subsystem is initialized, then do the
300fec00eabSdrh ** allocation.
301fec00eabSdrh */
302fec00eabSdrh void *sqlite3_malloc(int n){
303fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
304fec00eabSdrh   if( sqlite3_initialize() ) return 0;
305fec00eabSdrh #endif
306da4ca9d1Sdrh   return n<=0 ? 0 : sqlite3Malloc(n);
307da4ca9d1Sdrh }
308da4ca9d1Sdrh void *sqlite3_malloc64(sqlite3_uint64 n){
309da4ca9d1Sdrh #ifndef SQLITE_OMIT_AUTOINIT
310da4ca9d1Sdrh   if( sqlite3_initialize() ) return 0;
311da4ca9d1Sdrh #endif
312fec00eabSdrh   return sqlite3Malloc(n);
313fec00eabSdrh }
314fec00eabSdrh 
315fec00eabSdrh /*
316633e6d57Sdrh ** TRUE if p is a lookaside memory allocation from db
317633e6d57Sdrh */
3184150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
319b6dad520Sdrh static int isLookaside(sqlite3 *db, const void *p){
320ac536e61Sdrh   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
321633e6d57Sdrh }
3224150ebf8Sdrh #else
3234150ebf8Sdrh #define isLookaside(A,B) 0
3244150ebf8Sdrh #endif
325633e6d57Sdrh 
326633e6d57Sdrh /*
327fec00eabSdrh ** Return the size of a memory allocation previously obtained from
328fec00eabSdrh ** sqlite3Malloc() or sqlite3_malloc().
329fec00eabSdrh */
330b6dad520Sdrh int sqlite3MallocSize(const void *p){
331107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
332b6dad520Sdrh   return sqlite3GlobalConfig.m.xSize((void*)p);
333fec00eabSdrh }
334b6dad520Sdrh static int lookasideMallocSize(sqlite3 *db, const void *p){
335cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
336cf014f6cSdrh   return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
337115d663cSnumist #else
338115d663cSnumist   return db->lookaside.szTrue;
339115d663cSnumist #endif
340115d663cSnumist }
341b6dad520Sdrh int sqlite3DbMallocSize(sqlite3 *db, const void *p){
342039ca6abSdrh   assert( p!=0 );
343d879e3ebSdrh #ifdef SQLITE_DEBUG
344e6068027Sdrh   if( db==0 || !isLookaside(db,p) ){
34517bcb102Sdrh     if( db==0 ){
346d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
347d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
348633e6d57Sdrh     }else{
349d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
350d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
351633e6d57Sdrh     }
352633e6d57Sdrh   }
353e6068027Sdrh #endif
354e6068027Sdrh   if( db ){
355e6068027Sdrh     if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
356cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
357e6068027Sdrh       if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
358e6068027Sdrh         assert( sqlite3_mutex_held(db->mutex) );
359cf014f6cSdrh         return LOOKASIDE_SMALL;
360e6068027Sdrh       }
361e6068027Sdrh #endif
362e6068027Sdrh       if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
363e6068027Sdrh         assert( sqlite3_mutex_held(db->mutex) );
364e6068027Sdrh         return db->lookaside.szTrue;
365e6068027Sdrh       }
366e6068027Sdrh     }
367e6068027Sdrh   }
368b6dad520Sdrh   return sqlite3GlobalConfig.m.xSize((void*)p);
36917bcb102Sdrh }
370da4ca9d1Sdrh sqlite3_uint64 sqlite3_msize(void *p){
371d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
372d231aa3aSdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
373039ca6abSdrh   return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
374da4ca9d1Sdrh }
375fec00eabSdrh 
376fec00eabSdrh /*
377fec00eabSdrh ** Free memory previously obtained from sqlite3Malloc().
378fec00eabSdrh */
379fec00eabSdrh void sqlite3_free(void *p){
38071a1a0f4Sdrh   if( p==0 ) return;  /* IMP: R-49053-54554 */
381107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
382d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
383075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
384fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
385af89fe66Sdrh     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
386af89fe66Sdrh     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
387075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
388fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
389fec00eabSdrh   }else{
390075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
391fec00eabSdrh   }
392fec00eabSdrh }
393fec00eabSdrh 
394fec00eabSdrh /*
395b4586f12Sdrh ** Add the size of memory allocation "p" to the count in
396b4586f12Sdrh ** *db->pnBytesFreed.
397b4586f12Sdrh */
398b4586f12Sdrh static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
39956d90be1Sdrh   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
400b4586f12Sdrh }
401b4586f12Sdrh 
402b4586f12Sdrh /*
403633e6d57Sdrh ** Free memory that might be associated with a particular database
404dbd6a7dcSdrh ** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
405dbd6a7dcSdrh ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
406633e6d57Sdrh */
407dbd6a7dcSdrh void sqlite3DbFreeNN(sqlite3 *db, void *p){
4087047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
409dbd6a7dcSdrh   assert( p!=0 );
410174b9a16Sdrh   if( db ){
411174b9a16Sdrh     if( db->pnBytesFreed ){
412b4586f12Sdrh       measureAllocationSize(db, p);
413174b9a16Sdrh       return;
414d46def77Sdan     }
415e6068027Sdrh     if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
416cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
417e6068027Sdrh       if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
418e6068027Sdrh         LookasideSlot *pBuf = (LookasideSlot*)p;
419115d663cSnumist #ifdef SQLITE_DEBUG
420cf014f6cSdrh         memset(p, 0xaa, LOOKASIDE_SMALL);  /* Trash freed content */
421115d663cSnumist #endif
422cf014f6cSdrh         pBuf->pNext = db->lookaside.pSmallFree;
423cf014f6cSdrh         db->lookaside.pSmallFree = pBuf;
424115d663cSnumist         return;
425115d663cSnumist       }
426cf014f6cSdrh #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
427e6068027Sdrh       if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
428e6068027Sdrh         LookasideSlot *pBuf = (LookasideSlot*)p;
429d879e3ebSdrh #ifdef SQLITE_DEBUG
430e6068027Sdrh         memset(p, 0xaa, db->lookaside.szTrue);  /* Trash freed content */
4313608f177Sdrh #endif
432633e6d57Sdrh         pBuf->pNext = db->lookaside.pFree;
433633e6d57Sdrh         db->lookaside.pFree = pBuf;
434174b9a16Sdrh         return;
435174b9a16Sdrh       }
436174b9a16Sdrh     }
437e6068027Sdrh   }
438d231aa3aSdrh   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
439d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
440174b9a16Sdrh   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
441107b56e8Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
442633e6d57Sdrh   sqlite3_free(p);
443633e6d57Sdrh }
444dbd6a7dcSdrh void sqlite3DbFree(sqlite3 *db, void *p){
445dbd6a7dcSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
446dbd6a7dcSdrh   if( p ) sqlite3DbFreeNN(db, p);
447dbd6a7dcSdrh }
448633e6d57Sdrh 
449633e6d57Sdrh /*
450fec00eabSdrh ** Change the size of an existing memory allocation
451fec00eabSdrh */
452da4ca9d1Sdrh void *sqlite3Realloc(void *pOld, u64 nBytes){
453ca591febSshaneh   int nOld, nNew, nDiff;
454fec00eabSdrh   void *pNew;
455d231aa3aSdrh   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
456d425864dSmistachkin   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
457fec00eabSdrh   if( pOld==0 ){
4588da47419Sdrh     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
459fec00eabSdrh   }
460da4ca9d1Sdrh   if( nBytes==0 ){
4618da47419Sdrh     sqlite3_free(pOld); /* IMP: R-26507-47431 */
462fec00eabSdrh     return 0;
463fec00eabSdrh   }
464b6063cf8Sdrh   if( nBytes>=0x7fffff00 ){
465b6063cf8Sdrh     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
466b6063cf8Sdrh     return 0;
467b6063cf8Sdrh   }
468fec00eabSdrh   nOld = sqlite3MallocSize(pOld);
4699f129f46Sdrh   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
4709f129f46Sdrh   ** argument to xRealloc is always a value returned by a prior call to
4719f129f46Sdrh   ** xRoundup. */
472da4ca9d1Sdrh   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
473fec00eabSdrh   if( nOld==nNew ){
474fec00eabSdrh     pNew = pOld;
4757c6791c8Sdrh   }else if( sqlite3GlobalConfig.bMemstat ){
476672f07c6Sdrh     sqlite3_int64 nUsed;
4777c6791c8Sdrh     sqlite3_mutex_enter(mem0.mutex);
478b02392e6Sdrh     sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
4798e1bb041Sdrh     nDiff = nNew - nOld;
480672f07c6Sdrh     if( nDiff>0 && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)) >=
4815fb72e5fSdrh           mem0.alarmThreshold-nDiff ){
4825fb72e5fSdrh       sqlite3MallocAlarm(nDiff);
483672f07c6Sdrh       if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){
484672f07c6Sdrh         sqlite3_mutex_leave(mem0.mutex);
485672f07c6Sdrh         return 0;
486672f07c6Sdrh       }
4875fb72e5fSdrh     }
488075c23afSdanielk1977     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
489acc17521Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
4905fb72e5fSdrh     if( pNew==0 && mem0.alarmThreshold>0 ){
4915fb72e5fSdrh       sqlite3MallocAlarm((int)nBytes);
492075c23afSdanielk1977       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
493fec00eabSdrh     }
494acc17521Sdrh #endif
495fec00eabSdrh     if( pNew ){
496c702c7ccSdrh       nNew = sqlite3MallocSize(pNew);
497af89fe66Sdrh       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
498fec00eabSdrh     }
499fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
500fec00eabSdrh   }else{
5017c6791c8Sdrh     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
502fec00eabSdrh   }
5038da47419Sdrh   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
504fec00eabSdrh   return pNew;
505fec00eabSdrh }
506fec00eabSdrh 
507fec00eabSdrh /*
508fec00eabSdrh ** The public interface to sqlite3Realloc.  Make sure that the memory
509fec00eabSdrh ** subsystem is initialized prior to invoking sqliteRealloc.
510fec00eabSdrh */
511fec00eabSdrh void *sqlite3_realloc(void *pOld, int n){
512fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
513fec00eabSdrh   if( sqlite3_initialize() ) return 0;
514fec00eabSdrh #endif
5158da47419Sdrh   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
516da4ca9d1Sdrh   return sqlite3Realloc(pOld, n);
517da4ca9d1Sdrh }
518da4ca9d1Sdrh void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
519da4ca9d1Sdrh #ifndef SQLITE_OMIT_AUTOINIT
520da4ca9d1Sdrh   if( sqlite3_initialize() ) return 0;
521da4ca9d1Sdrh #endif
522fec00eabSdrh   return sqlite3Realloc(pOld, n);
523fec00eabSdrh }
524fec00eabSdrh 
525a3152895Sdrh 
526a3152895Sdrh /*
52717435752Sdrh ** Allocate and zero memory.
528a3152895Sdrh */
529da4ca9d1Sdrh void *sqlite3MallocZero(u64 n){
530fec00eabSdrh   void *p = sqlite3Malloc(n);
531a3152895Sdrh   if( p ){
53220f3df04Sdrh     memset(p, 0, (size_t)n);
533a3152895Sdrh   }
534a3152895Sdrh   return p;
535a3152895Sdrh }
53617435752Sdrh 
53717435752Sdrh /*
53817435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
53917435752Sdrh ** the mallocFailed flag in the connection pointer.
54017435752Sdrh */
541da4ca9d1Sdrh void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
542575fad65Sdrh   void *p;
543575fad65Sdrh   testcase( db==0 );
544575fad65Sdrh   p = sqlite3DbMallocRaw(db, n);
545575fad65Sdrh   if( p ) memset(p, 0, (size_t)n);
546575fad65Sdrh   return p;
54717435752Sdrh }
548575fad65Sdrh 
549575fad65Sdrh 
550575fad65Sdrh /* Finish the work of sqlite3DbMallocRawNN for the unusual and
551575fad65Sdrh ** slower case when the allocation cannot be fulfilled using lookaside.
552575fad65Sdrh */
553575fad65Sdrh static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
554575fad65Sdrh   void *p;
555575fad65Sdrh   assert( db!=0 );
556575fad65Sdrh   p = sqlite3Malloc(n);
557575fad65Sdrh   if( !p ) sqlite3OomFault(db);
558575fad65Sdrh   sqlite3MemdebugSetType(p,
559575fad65Sdrh          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
56017435752Sdrh   return p;
56117435752Sdrh }
56217435752Sdrh 
56317435752Sdrh /*
5641da26a48Sdrh ** Allocate memory, either lookaside (if possible) or heap.
5651da26a48Sdrh ** If the allocation fails, set the mallocFailed flag in
5661da26a48Sdrh ** the connection pointer.
567ddecae79Sdrh **
568ddecae79Sdrh ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
569ddecae79Sdrh ** failure on the same database connection) then always return 0.
570ddecae79Sdrh ** Hence for a particular database connection, once malloc starts
571ddecae79Sdrh ** failing, it fails consistently until mallocFailed is reset.
572ddecae79Sdrh ** This is an important assumption.  There are many places in the
573ddecae79Sdrh ** code that do things like this:
574ddecae79Sdrh **
575ddecae79Sdrh **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
576ddecae79Sdrh **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
577ddecae79Sdrh **         if( b ) a[10] = 9;
578ddecae79Sdrh **
579ddecae79Sdrh ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
580ddecae79Sdrh ** that all prior mallocs (ex: "a") worked too.
581575fad65Sdrh **
582575fad65Sdrh ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
583575fad65Sdrh ** not a NULL pointer.
58417435752Sdrh */
585da4ca9d1Sdrh void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
586575fad65Sdrh   void *p;
587575fad65Sdrh   if( db ) return sqlite3DbMallocRawNN(db, n);
588575fad65Sdrh   p = sqlite3Malloc(n);
589575fad65Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
590575fad65Sdrh   return p;
591575fad65Sdrh }
592575fad65Sdrh void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
593f5818aa5Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
594f5818aa5Sdrh   LookasideSlot *pBuf;
595575fad65Sdrh   assert( db!=0 );
596575fad65Sdrh   assert( sqlite3_mutex_held(db->mutex) );
597575fad65Sdrh   assert( db->pnBytesFreed==0 );
5980b12e7f8Sdrh   if( n>db->lookaside.sz ){
5991b47c9c9Snumist     if( !db->lookaside.bDisable ){
6000b12e7f8Sdrh       db->lookaside.anStat[1]++;
6011b47c9c9Snumist     }else if( db->mallocFailed ){
6021b47c9c9Snumist       return 0;
6031b47c9c9Snumist     }
604c947d6a4Snumist     return dbMallocRawFinish(db, n);
605c947d6a4Snumist   }
606cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
607cf014f6cSdrh   if( n<=LOOKASIDE_SMALL ){
608cf014f6cSdrh     if( (pBuf = db->lookaside.pSmallFree)!=0 ){
609cf014f6cSdrh       db->lookaside.pSmallFree = pBuf->pNext;
610115d663cSnumist       db->lookaside.anStat[0]++;
611115d663cSnumist       return (void*)pBuf;
612cf014f6cSdrh     }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
613cf014f6cSdrh       db->lookaside.pSmallInit = pBuf->pNext;
614115d663cSnumist       db->lookaside.anStat[0]++;
615115d663cSnumist       return (void*)pBuf;
616115d663cSnumist     }
617c947d6a4Snumist   }
618115d663cSnumist #endif
619c947d6a4Snumist   if( (pBuf = db->lookaside.pFree)!=0 ){
620633e6d57Sdrh     db->lookaside.pFree = pBuf->pNext;
6210b12e7f8Sdrh     db->lookaside.anStat[0]++;
622633e6d57Sdrh     return (void*)pBuf;
62352fb8e19Sdrh   }else if( (pBuf = db->lookaside.pInit)!=0 ){
62452fb8e19Sdrh     db->lookaside.pInit = pBuf->pNext;
62552fb8e19Sdrh     db->lookaside.anStat[0]++;
62652fb8e19Sdrh     return (void*)pBuf;
62752fb8e19Sdrh   }else{
62852fb8e19Sdrh     db->lookaside.anStat[2]++;
629633e6d57Sdrh   }
630ddecae79Sdrh #else
631f5818aa5Sdrh   assert( db!=0 );
632f5818aa5Sdrh   assert( sqlite3_mutex_held(db->mutex) );
633f5818aa5Sdrh   assert( db->pnBytesFreed==0 );
634575fad65Sdrh   if( db->mallocFailed ){
635ddecae79Sdrh     return 0;
636ddecae79Sdrh   }
6374150ebf8Sdrh #endif
6381da26a48Sdrh   return dbMallocRawFinish(db, n);
6391da26a48Sdrh }
64017435752Sdrh 
641b84e574cSdrh /* Forward declaration */
642b84e574cSdrh static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
643b84e574cSdrh 
64426783a58Sdanielk1977 /*
64526783a58Sdanielk1977 ** Resize the block of memory pointed to by p to n bytes. If the
64626783a58Sdanielk1977 ** resize fails, set the mallocFailed flag in the connection object.
64726783a58Sdanielk1977 */
648da4ca9d1Sdrh void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
649b84e574cSdrh   assert( db!=0 );
650575fad65Sdrh   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
651b84e574cSdrh   assert( sqlite3_mutex_held(db->mutex) );
652e6068027Sdrh   if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
653cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
654e6068027Sdrh     if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
655cf014f6cSdrh       if( n<=LOOKASIDE_SMALL ) return p;
656e6068027Sdrh     }else
657e6068027Sdrh #endif
658e6068027Sdrh     if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
659e6068027Sdrh       if( n<=db->lookaside.szTrue ) return p;
660e6068027Sdrh     }
661e6068027Sdrh   }
662b84e574cSdrh   return dbReallocFinish(db, p, n);
663b84e574cSdrh }
664b84e574cSdrh static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
665a1644fd8Sdanielk1977   void *pNew = 0;
666d9da78a2Sdrh   assert( db!=0 );
667b84e574cSdrh   assert( p!=0 );
668a1644fd8Sdanielk1977   if( db->mallocFailed==0 ){
669633e6d57Sdrh     if( isLookaside(db, p) ){
670575fad65Sdrh       pNew = sqlite3DbMallocRawNN(db, n);
671633e6d57Sdrh       if( pNew ){
672115d663cSnumist         memcpy(pNew, p, lookasideMallocSize(db, p));
673633e6d57Sdrh         sqlite3DbFree(db, p);
674633e6d57Sdrh       }
675633e6d57Sdrh     }else{
676d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
677d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
678107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
679d924e7bcSdrh       pNew = sqlite3Realloc(p, n);
680a1644fd8Sdanielk1977       if( !pNew ){
6814a642b60Sdrh         sqlite3OomFault(db);
682a1644fd8Sdanielk1977       }
683d231aa3aSdrh       sqlite3MemdebugSetType(pNew,
6844a642b60Sdrh             (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
685a1644fd8Sdanielk1977     }
686633e6d57Sdrh   }
687a1644fd8Sdanielk1977   return pNew;
688a1644fd8Sdanielk1977 }
689a1644fd8Sdanielk1977 
69017435752Sdrh /*
69117435752Sdrh ** Attempt to reallocate p.  If the reallocation fails, then free p
69217435752Sdrh ** and set the mallocFailed flag in the database connection.
69317435752Sdrh */
694da4ca9d1Sdrh void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
695a3152895Sdrh   void *pNew;
696a1644fd8Sdanielk1977   pNew = sqlite3DbRealloc(db, p, n);
697a3152895Sdrh   if( !pNew ){
698633e6d57Sdrh     sqlite3DbFree(db, p);
699a3152895Sdrh   }
700a3152895Sdrh   return pNew;
701a3152895Sdrh }
702a3152895Sdrh 
703a3152895Sdrh /*
704a3152895Sdrh ** Make a copy of a string in memory obtained from sqliteMalloc(). These
705a3152895Sdrh ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
706a3152895Sdrh ** is because when memory debugging is turned on, these two functions are
707a3152895Sdrh ** called via macros that record the current file and line number in the
708a3152895Sdrh ** ThreadData structure.
709a3152895Sdrh */
710633e6d57Sdrh char *sqlite3DbStrDup(sqlite3 *db, const char *z){
711a3152895Sdrh   char *zNew;
712633e6d57Sdrh   size_t n;
713633e6d57Sdrh   if( z==0 ){
714633e6d57Sdrh     return 0;
715a3152895Sdrh   }
716cee11adaSdrh   n = strlen(z) + 1;
717cee11adaSdrh   zNew = sqlite3DbMallocRaw(db, n);
718a3152895Sdrh   if( zNew ){
719a3152895Sdrh     memcpy(zNew, z, n);
7201e536953Sdanielk1977   }
7211e536953Sdanielk1977   return zNew;
7221e536953Sdanielk1977 }
723da4ca9d1Sdrh char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
724633e6d57Sdrh   char *zNew;
725575fad65Sdrh   assert( db!=0 );
726369e758fSdrh   assert( z!=0 || n==0 );
727633e6d57Sdrh   assert( (n&0x7fffffff)==n );
728369e758fSdrh   zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0;
729633e6d57Sdrh   if( zNew ){
73020f3df04Sdrh     memcpy(zNew, z, (size_t)n);
731633e6d57Sdrh     zNew[n] = 0;
7321e536953Sdanielk1977   }
7331e536953Sdanielk1977   return zNew;
7341e536953Sdanielk1977 }
7351e536953Sdanielk1977 
736a3152895Sdrh /*
7379b2e0435Sdrh ** The text between zStart and zEnd represents a phrase within a larger
7389b2e0435Sdrh ** SQL statement.  Make a copy of this phrase in space obtained form
7399b2e0435Sdrh ** sqlite3DbMalloc().  Omit leading and trailing whitespace.
7409b2e0435Sdrh */
7419b2e0435Sdrh char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
7429b2e0435Sdrh   int n;
7439b2e0435Sdrh   while( sqlite3Isspace(zStart[0]) ) zStart++;
7449b2e0435Sdrh   n = (int)(zEnd - zStart);
745e75d1f52Sdrh   while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
7469b2e0435Sdrh   return sqlite3DbStrNDup(db, zStart, n);
7479b2e0435Sdrh }
7489b2e0435Sdrh 
7499b2e0435Sdrh /*
75022c17b8bSdrh ** Free any prior content in *pz and replace it with a copy of zNew.
751a3152895Sdrh */
75222c17b8bSdrh void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
753f7413d9aSdan   char *z = sqlite3DbStrDup(db, zNew);
754633e6d57Sdrh   sqlite3DbFree(db, *pz);
755f7413d9aSdan   *pz = z;
756a3152895Sdrh }
757a3152895Sdrh 
758b50c65d5Sdrh /*
7594a642b60Sdrh ** Call this routine to record the fact that an OOM (out-of-memory) error
7604a642b60Sdrh ** has happened.  This routine will set db->mallocFailed, and also
7614a642b60Sdrh ** temporarily disable the lookaside memory allocator and interrupt
7624a642b60Sdrh ** any running VDBEs.
7633cdb1394Sdrh **
7643cdb1394Sdrh ** Always return a NULL pointer so that this routine can be invoked using
7653cdb1394Sdrh **
7663cdb1394Sdrh **      return sqlite3OomFault(db);
7673cdb1394Sdrh **
7683cdb1394Sdrh ** and thereby avoid unnecessary stack frame allocations for the overwhelmingly
7693cdb1394Sdrh ** common case where no OOM occurs.
7704a642b60Sdrh */
7713cdb1394Sdrh void *sqlite3OomFault(sqlite3 *db){
7724a642b60Sdrh   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
7734a642b60Sdrh     db->mallocFailed = 1;
7744a642b60Sdrh     if( db->nVdbeExec>0 ){
775892edb69Sdan       AtomicStore(&db->u1.isInterrupted, 1);
7764a642b60Sdrh     }
77731f69626Sdrh     DisableLookaside;
7781cf19758Sdrh     if( db->pParse ){
779*25bb72a7Sdrh       Parse *pParse;
7803cdb1394Sdrh       sqlite3ErrorMsg(db->pParse, "out of memory");
7811cf19758Sdrh       db->pParse->rc = SQLITE_NOMEM_BKPT;
782*25bb72a7Sdrh       for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){
783*25bb72a7Sdrh         pParse->nErr++;
784*25bb72a7Sdrh         pParse->rc = SQLITE_NOMEM;
785*25bb72a7Sdrh       }
7861cf19758Sdrh     }
7874a642b60Sdrh   }
7883cdb1394Sdrh   return 0;
7894a642b60Sdrh }
7904a642b60Sdrh 
7914a642b60Sdrh /*
7924a642b60Sdrh ** This routine reactivates the memory allocator and clears the
7934a642b60Sdrh ** db->mallocFailed flag as necessary.
7944a642b60Sdrh **
7954a642b60Sdrh ** The memory allocator is not restarted if there are running
7964a642b60Sdrh ** VDBEs.
7974a642b60Sdrh */
7984a642b60Sdrh void sqlite3OomClear(sqlite3 *db){
7994a642b60Sdrh   if( db->mallocFailed && db->nVdbeExec==0 ){
8004a642b60Sdrh     db->mallocFailed = 0;
801892edb69Sdan     AtomicStore(&db->u1.isInterrupted, 0);
8024a642b60Sdrh     assert( db->lookaside.bDisable>0 );
80331f69626Sdrh     EnableLookaside;
8044a642b60Sdrh   }
8054a642b60Sdrh }
8064a642b60Sdrh 
8074a642b60Sdrh /*
8085a07d10fSdrh ** Take actions at the end of an API call to deal with error codes.
809b50c65d5Sdrh */
8105a07d10fSdrh static SQLITE_NOINLINE int apiHandleError(sqlite3 *db, int rc){
8115a07d10fSdrh   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
8124a642b60Sdrh     sqlite3OomClear(db);
813b50c65d5Sdrh     sqlite3Error(db, SQLITE_NOMEM);
814fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
815b50c65d5Sdrh   }
8165a07d10fSdrh   return rc & db->errMask;
8175a07d10fSdrh }
818a3152895Sdrh 
819a3152895Sdrh /*
820a3152895Sdrh ** This function must be called before exiting any API function (i.e.
82117435752Sdrh ** returning control to the user) that has called sqlite3_malloc or
82217435752Sdrh ** sqlite3_realloc.
823a3152895Sdrh **
824a3152895Sdrh ** The returned value is normally a copy of the second argument to this
825be217793Sshane ** function. However, if a malloc() failure has occurred since the previous
826a3152895Sdrh ** invocation SQLITE_NOMEM is returned instead.
827a3152895Sdrh **
828597d2b64Sdrh ** If an OOM as occurred, then the connection error-code (the value
829597d2b64Sdrh ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
830a3152895Sdrh */
831a3152895Sdrh int sqlite3ApiExit(sqlite3* db, int rc){
832597d2b64Sdrh   /* If the db handle must hold the connection handle mutex here.
833597d2b64Sdrh   ** Otherwise the read (and possible write) of db->mallocFailed
834a1644fd8Sdanielk1977   ** is unsafe, as is the call to sqlite3Error().
835a1644fd8Sdanielk1977   */
836597d2b64Sdrh   assert( db!=0 );
837597d2b64Sdrh   assert( sqlite3_mutex_held(db->mutex) );
8385a07d10fSdrh   if( db->mallocFailed || rc ){
8395a07d10fSdrh     return apiHandleError(db, rc);
840a3152895Sdrh   }
841b50c65d5Sdrh   return rc & db->errMask;
842a3152895Sdrh }
843