xref: /sqlite-3.40.0/src/malloc.c (revision dbd6a7dc)
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 /*
36badc980aSdrh ** An instance of the following object records the location of
37badc980aSdrh ** each unused scratch buffer.
38badc980aSdrh */
39badc980aSdrh typedef struct ScratchFreeslot {
40badc980aSdrh   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
41badc980aSdrh } ScratchFreeslot;
42badc980aSdrh 
43badc980aSdrh /*
44fec00eabSdrh ** State information local to the memory allocation subsystem.
45fec00eabSdrh */
465c8f8587Sdanielk1977 static SQLITE_WSD struct Mem0Global {
47fec00eabSdrh   sqlite3_mutex *mutex;         /* Mutex to serialize access */
484ef299a3Sdrh   sqlite3_int64 alarmThreshold; /* The soft heap limit */
49fec00eabSdrh 
50fec00eabSdrh   /*
51badc980aSdrh   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
52badc980aSdrh   ** (so that a range test can be used to determine if an allocation
53badc980aSdrh   ** being freed came from pScratch) and a pointer to the list of
54badc980aSdrh   ** unused scratch allocations.
559ac3fe97Sdrh   */
56badc980aSdrh   void *pScratchEnd;
57badc980aSdrh   ScratchFreeslot *pScratchFree;
58badc980aSdrh   u32 nScratchFree;
5950d1b5f3Sdrh 
6050d1b5f3Sdrh   /*
6150d1b5f3Sdrh   ** True if heap is nearly "full" where "full" is defined by the
6250d1b5f3Sdrh   ** sqlite3_soft_heap_limit() setting.
6350d1b5f3Sdrh   */
6450d1b5f3Sdrh   int nearlyFull;
654ef299a3Sdrh } mem0 = { 0, 0, 0, 0, 0, 0 };
665c8f8587Sdanielk1977 
675c8f8587Sdanielk1977 #define mem0 GLOBAL(struct Mem0Global, mem0)
68fec00eabSdrh 
69fec00eabSdrh /*
70af89fe66Sdrh ** Return the memory allocator mutex. sqlite3_status() needs it.
71af89fe66Sdrh */
72af89fe66Sdrh sqlite3_mutex *sqlite3MallocMutex(void){
73af89fe66Sdrh   return mem0.mutex;
74af89fe66Sdrh }
75af89fe66Sdrh 
76f82ccf64Sdrh #ifndef SQLITE_OMIT_DEPRECATED
77f82ccf64Sdrh /*
785fb72e5fSdrh ** Deprecated external interface.  It used to set an alarm callback
795fb72e5fSdrh ** that was invoked when memory usage grew too large.  Now it is a
805fb72e5fSdrh ** no-op.
81f82ccf64Sdrh */
82f82ccf64Sdrh int sqlite3_memory_alarm(
83f82ccf64Sdrh   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
84f82ccf64Sdrh   void *pArg,
85f82ccf64Sdrh   sqlite3_int64 iThreshold
86f82ccf64Sdrh ){
875fb72e5fSdrh   (void)xCallback;
885fb72e5fSdrh   (void)pArg;
895fb72e5fSdrh   (void)iThreshold;
904ef299a3Sdrh   return SQLITE_OK;
91f82ccf64Sdrh }
92f82ccf64Sdrh #endif
93f82ccf64Sdrh 
94f82ccf64Sdrh /*
95f82ccf64Sdrh ** Set the soft heap-size limit for the library. Passing a zero or
96f82ccf64Sdrh ** negative value indicates no limit.
97f82ccf64Sdrh */
98f82ccf64Sdrh sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
99f82ccf64Sdrh   sqlite3_int64 priorLimit;
1005fb72e5fSdrh   sqlite3_int64 excess;
1015fb72e5fSdrh   sqlite3_int64 nUsed;
102f82ccf64Sdrh #ifndef SQLITE_OMIT_AUTOINIT
103de0f1815Sdrh   int rc = sqlite3_initialize();
104de0f1815Sdrh   if( rc ) return -1;
105f82ccf64Sdrh #endif
106f82ccf64Sdrh   sqlite3_mutex_enter(mem0.mutex);
107f82ccf64Sdrh   priorLimit = mem0.alarmThreshold;
1085fb72e5fSdrh   if( n<0 ){
1094ef299a3Sdrh     sqlite3_mutex_leave(mem0.mutex);
110f82ccf64Sdrh     return priorLimit;
111f82ccf64Sdrh   }
1125fb72e5fSdrh   mem0.alarmThreshold = n;
1135fb72e5fSdrh   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
1145fb72e5fSdrh   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 /*
126fec00eabSdrh ** Initialize the memory allocation subsystem.
127fec00eabSdrh */
128fec00eabSdrh int sqlite3MallocInit(void){
129592f0cb1Sdrh   int rc;
130075c23afSdanielk1977   if( sqlite3GlobalConfig.m.xMalloc==0 ){
131fec00eabSdrh     sqlite3MemSetDefault();
132fec00eabSdrh   }
133fec00eabSdrh   memset(&mem0, 0, sizeof(mem0));
13459f8c08eSdanielk1977   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
135075c23afSdanielk1977   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
1367ff2719eSdrh       && sqlite3GlobalConfig.nScratch>0 ){
137badc980aSdrh     int i, n, sz;
138badc980aSdrh     ScratchFreeslot *pSlot;
139badc980aSdrh     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
140badc980aSdrh     sqlite3GlobalConfig.szScratch = sz;
141badc980aSdrh     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
142badc980aSdrh     n = sqlite3GlobalConfig.nScratch;
143badc980aSdrh     mem0.pScratchFree = pSlot;
144badc980aSdrh     mem0.nScratchFree = n;
145badc980aSdrh     for(i=0; i<n-1; i++){
146badc980aSdrh       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
147badc980aSdrh       pSlot = pSlot->pNext;
148badc980aSdrh     }
149badc980aSdrh     pSlot->pNext = 0;
150badc980aSdrh     mem0.pScratchEnd = (void*)&pSlot[1];
1519ac3fe97Sdrh   }else{
152badc980aSdrh     mem0.pScratchEnd = 0;
153075c23afSdanielk1977     sqlite3GlobalConfig.pScratch = 0;
154075c23afSdanielk1977     sqlite3GlobalConfig.szScratch = 0;
155badc980aSdrh     sqlite3GlobalConfig.nScratch = 0;
1569ac3fe97Sdrh   }
15750d1b5f3Sdrh   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
15801c5c00cSdrh       || sqlite3GlobalConfig.nPage<=0 ){
159075c23afSdanielk1977     sqlite3GlobalConfig.pPage = 0;
160075c23afSdanielk1977     sqlite3GlobalConfig.szPage = 0;
1619ac3fe97Sdrh   }
162592f0cb1Sdrh   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
163592f0cb1Sdrh   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
164592f0cb1Sdrh   return rc;
165fec00eabSdrh }
166fec00eabSdrh 
167fec00eabSdrh /*
16850d1b5f3Sdrh ** Return true if the heap is currently under memory pressure - in other
16950d1b5f3Sdrh ** words if the amount of heap used is close to the limit set by
17050d1b5f3Sdrh ** sqlite3_soft_heap_limit().
17150d1b5f3Sdrh */
17250d1b5f3Sdrh int sqlite3HeapNearlyFull(void){
17350d1b5f3Sdrh   return mem0.nearlyFull;
17450d1b5f3Sdrh }
17550d1b5f3Sdrh 
17650d1b5f3Sdrh /*
177fec00eabSdrh ** Deinitialize the memory allocation subsystem.
178fec00eabSdrh */
179fec00eabSdrh void sqlite3MallocEnd(void){
1800a549071Sdanielk1977   if( sqlite3GlobalConfig.m.xShutdown ){
181075c23afSdanielk1977     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
1820a549071Sdanielk1977   }
1839ac3fe97Sdrh   memset(&mem0, 0, sizeof(mem0));
184fec00eabSdrh }
185fec00eabSdrh 
186fec00eabSdrh /*
187fec00eabSdrh ** Return the amount of memory currently checked out.
188fec00eabSdrh */
189fec00eabSdrh sqlite3_int64 sqlite3_memory_used(void){
190df5e1a00Sdrh   sqlite3_int64 res, mx;
191df5e1a00Sdrh   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
192c376a198Sdrh   return res;
193fec00eabSdrh }
194fec00eabSdrh 
195fec00eabSdrh /*
196fec00eabSdrh ** Return the maximum amount of memory that has ever been
197fec00eabSdrh ** checked out since either the beginning of this process
198fec00eabSdrh ** or since the most recent reset.
199fec00eabSdrh */
200fec00eabSdrh sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
201df5e1a00Sdrh   sqlite3_int64 res, mx;
202df5e1a00Sdrh   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
203df5e1a00Sdrh   return mx;
204fec00eabSdrh }
205fec00eabSdrh 
206fec00eabSdrh /*
2075fb72e5fSdrh ** Trigger the alarm
2085fb72e5fSdrh */
2095fb72e5fSdrh static void sqlite3MallocAlarm(int nByte){
2105fb72e5fSdrh   if( mem0.alarmThreshold<=0 ) return;
2115fb72e5fSdrh   sqlite3_mutex_leave(mem0.mutex);
2125fb72e5fSdrh   sqlite3_release_memory(nByte);
2135fb72e5fSdrh   sqlite3_mutex_enter(mem0.mutex);
2145fb72e5fSdrh }
2155fb72e5fSdrh 
2165fb72e5fSdrh /*
217f7141990Sdrh ** Do a memory allocation with statistics and alarms.  Assume the
218f7141990Sdrh ** lock is already held.
219fec00eabSdrh */
2201d21bac8Sdrh static void mallocWithAlarm(int n, void **pp){
221f7141990Sdrh   void *p;
222087a29c7Sdrh   int nFull;
223f7141990Sdrh   assert( sqlite3_mutex_held(mem0.mutex) );
224087a29c7Sdrh   assert( n>0 );
225087a29c7Sdrh 
22640b84365Smistachkin   /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
227087a29c7Sdrh   ** implementation of malloc_good_size(), which must be called in debug
228087a29c7Sdrh   ** mode and specifically when the DMD "Dark Matter Detector" is enabled
22940b84365Smistachkin   ** or else a crash results.  Hence, do not attempt to optimize out the
23040b84365Smistachkin   ** following xRoundup() call. */
231087a29c7Sdrh   nFull = sqlite3GlobalConfig.m.xRoundup(n);
232087a29c7Sdrh 
233e43d6aeeSdrh #ifdef SQLITE_MAX_MEMORY
234e43d6aeeSdrh   if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
235a6bf20b5Sdrh     *pp = 0;
236a6bf20b5Sdrh     return;
237e43d6aeeSdrh   }
238e43d6aeeSdrh #endif
239e43d6aeeSdrh 
240b02392e6Sdrh   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
2415fb72e5fSdrh   if( mem0.alarmThreshold>0 ){
2425fb72e5fSdrh     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
2435fb72e5fSdrh     if( nUsed >= mem0.alarmThreshold - nFull ){
2445fb72e5fSdrh       mem0.nearlyFull = 1;
2455fb72e5fSdrh       sqlite3MallocAlarm(nFull);
2465fb72e5fSdrh     }else{
2475fb72e5fSdrh       mem0.nearlyFull = 0;
2485fb72e5fSdrh     }
2495fb72e5fSdrh   }
250087a29c7Sdrh   p = sqlite3GlobalConfig.m.xMalloc(nFull);
25150d1b5f3Sdrh #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
2525fb72e5fSdrh   if( p==0 && mem0.alarmThreshold>0 ){
2535fb72e5fSdrh     sqlite3MallocAlarm(nFull);
254087a29c7Sdrh     p = sqlite3GlobalConfig.m.xMalloc(nFull);
255fec00eabSdrh   }
25650d1b5f3Sdrh #endif
257c702c7ccSdrh   if( p ){
258be7a0ceeSdrh     nFull = sqlite3MallocSize(p);
259af89fe66Sdrh     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
260af89fe66Sdrh     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
261c702c7ccSdrh   }
262f7141990Sdrh   *pp = p;
263fec00eabSdrh }
264f7141990Sdrh 
265f7141990Sdrh /*
266f7141990Sdrh ** Allocate memory.  This routine is like sqlite3_malloc() except that it
267f7141990Sdrh ** assumes the memory subsystem has already been initialized.
268f7141990Sdrh */
269da4ca9d1Sdrh void *sqlite3Malloc(u64 n){
270f7141990Sdrh   void *p;
271da4ca9d1Sdrh   if( n==0 || n>=0x7fffff00 ){
272e08ed7e7Sdrh     /* A memory allocation of a number of bytes which is near the maximum
273e08ed7e7Sdrh     ** signed integer value might cause an integer overflow inside of the
274e08ed7e7Sdrh     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
275e08ed7e7Sdrh     ** 255 bytes of overhead.  SQLite itself will never use anything near
276e08ed7e7Sdrh     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
277f7141990Sdrh     p = 0;
278075c23afSdanielk1977   }else if( sqlite3GlobalConfig.bMemstat ){
279f7141990Sdrh     sqlite3_mutex_enter(mem0.mutex);
2803329a63aSdrh     mallocWithAlarm((int)n, &p);
281fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
282fec00eabSdrh   }else{
283da4ca9d1Sdrh     p = sqlite3GlobalConfig.m.xMalloc((int)n);
284fec00eabSdrh   }
2858da47419Sdrh   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
286fec00eabSdrh   return p;
287fec00eabSdrh }
288fec00eabSdrh 
289fec00eabSdrh /*
290fec00eabSdrh ** This version of the memory allocation is for use by the application.
291fec00eabSdrh ** First make sure the memory subsystem is initialized, then do the
292fec00eabSdrh ** allocation.
293fec00eabSdrh */
294fec00eabSdrh void *sqlite3_malloc(int n){
295fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
296fec00eabSdrh   if( sqlite3_initialize() ) return 0;
297fec00eabSdrh #endif
298da4ca9d1Sdrh   return n<=0 ? 0 : sqlite3Malloc(n);
299da4ca9d1Sdrh }
300da4ca9d1Sdrh void *sqlite3_malloc64(sqlite3_uint64 n){
301da4ca9d1Sdrh #ifndef SQLITE_OMIT_AUTOINIT
302da4ca9d1Sdrh   if( sqlite3_initialize() ) return 0;
303da4ca9d1Sdrh #endif
304fec00eabSdrh   return sqlite3Malloc(n);
305fec00eabSdrh }
306fec00eabSdrh 
307fec00eabSdrh /*
308e5ae5735Sdrh ** Each thread may only have a single outstanding allocation from
309facf0307Sdrh ** xScratchMalloc().  We verify this constraint in the single-threaded
310facf0307Sdrh ** case by setting scratchAllocOut to 1 when an allocation
311e5ae5735Sdrh ** is outstanding clearing it when the allocation is freed.
312e5ae5735Sdrh */
313e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
314facf0307Sdrh static int scratchAllocOut = 0;
315e5ae5735Sdrh #endif
316e5ae5735Sdrh 
317e5ae5735Sdrh 
318e5ae5735Sdrh /*
319e5ae5735Sdrh ** Allocate memory that is to be used and released right away.
320e5ae5735Sdrh ** This routine is similar to alloca() in that it is not intended
321e5ae5735Sdrh ** for situations where the memory might be held long-term.  This
322e5ae5735Sdrh ** routine is intended to get memory to old large transient data
323e5ae5735Sdrh ** structures that would not normally fit on the stack of an
324e5ae5735Sdrh ** embedded processor.
325e5ae5735Sdrh */
326facf0307Sdrh void *sqlite3ScratchMalloc(int n){
327e5ae5735Sdrh   void *p;
328e5ae5735Sdrh   assert( n>0 );
3299ac3fe97Sdrh 
330badc980aSdrh   sqlite3_mutex_enter(mem0.mutex);
331b02392e6Sdrh   sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
332badc980aSdrh   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
333badc980aSdrh     p = mem0.pScratchFree;
334badc980aSdrh     mem0.pScratchFree = mem0.pScratchFree->pNext;
335badc980aSdrh     mem0.nScratchFree--;
336af89fe66Sdrh     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
337b0c6a888Sdan     sqlite3_mutex_leave(mem0.mutex);
338badc980aSdrh   }else{
339b0c6a888Sdan     sqlite3_mutex_leave(mem0.mutex);
3403ccd5bf8Sdrh     p = sqlite3Malloc(n);
3413ccd5bf8Sdrh     if( sqlite3GlobalConfig.bMemstat && p ){
3423ccd5bf8Sdrh       sqlite3_mutex_enter(mem0.mutex);
343af89fe66Sdrh       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
3443ccd5bf8Sdrh       sqlite3_mutex_leave(mem0.mutex);
345badc980aSdrh     }
346badc980aSdrh     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
347badc980aSdrh   }
3481ff6e3abSdrh   assert( sqlite3_mutex_notheld(mem0.mutex) );
349b0c6a888Sdan 
350badc980aSdrh 
351badc980aSdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
352cbd55b03Sdrh   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
353cbd55b03Sdrh   ** buffers per thread.
354cbd55b03Sdrh   **
355cbd55b03Sdrh   ** This can only be checked in single-threaded mode.
356cbd55b03Sdrh   */
357cbd55b03Sdrh   assert( scratchAllocOut==0 );
358badc980aSdrh   if( p ) scratchAllocOut++;
359badc980aSdrh #endif
360badc980aSdrh 
361badc980aSdrh   return p;
362badc980aSdrh }
363badc980aSdrh void sqlite3ScratchFree(void *p){
364badc980aSdrh   if( p ){
365badc980aSdrh 
366e5ae5735Sdrh #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
36737f99187Sdrh     /* Verify that no more than two scratch allocation per thread
3689ac3fe97Sdrh     ** is outstanding at one time.  (This is only checked in the
3699ac3fe97Sdrh     ** single-threaded case since checking in the multi-threaded case
3709ac3fe97Sdrh     ** would be much more complicated.) */
371badc980aSdrh     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
372badc980aSdrh     scratchAllocOut--;
373e5ae5735Sdrh #endif
3749ac3fe97Sdrh 
375ac536e61Sdrh     if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
376badc980aSdrh       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
377badc980aSdrh       ScratchFreeslot *pSlot;
378badc980aSdrh       pSlot = (ScratchFreeslot*)p;
379e5ae5735Sdrh       sqlite3_mutex_enter(mem0.mutex);
380badc980aSdrh       pSlot->pNext = mem0.pScratchFree;
381badc980aSdrh       mem0.pScratchFree = pSlot;
382badc980aSdrh       mem0.nScratchFree++;
383fcd71b60Sdrh       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
384af89fe66Sdrh       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
3859ac3fe97Sdrh       sqlite3_mutex_leave(mem0.mutex);
386f7141990Sdrh     }else{
387badc980aSdrh       /* Release memory back to the heap */
388107b56e8Sdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
389d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
390107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
391075c23afSdanielk1977       if( sqlite3GlobalConfig.bMemstat ){
392f7141990Sdrh         int iSize = sqlite3MallocSize(p);
393f7141990Sdrh         sqlite3_mutex_enter(mem0.mutex);
394af89fe66Sdrh         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
395af89fe66Sdrh         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
396af89fe66Sdrh         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
397075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
398f7141990Sdrh         sqlite3_mutex_leave(mem0.mutex);
399f7141990Sdrh       }else{
400075c23afSdanielk1977         sqlite3GlobalConfig.m.xFree(p);
401f7141990Sdrh       }
4029ac3fe97Sdrh     }
403e5ae5735Sdrh   }
404e5ae5735Sdrh }
405e5ae5735Sdrh 
406e5ae5735Sdrh /*
407633e6d57Sdrh ** TRUE if p is a lookaside memory allocation from db
408633e6d57Sdrh */
4094150ebf8Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
410633e6d57Sdrh static int isLookaside(sqlite3 *db, void *p){
411ac536e61Sdrh   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
412633e6d57Sdrh }
4134150ebf8Sdrh #else
4144150ebf8Sdrh #define isLookaside(A,B) 0
4154150ebf8Sdrh #endif
416633e6d57Sdrh 
417633e6d57Sdrh /*
418fec00eabSdrh ** Return the size of a memory allocation previously obtained from
419fec00eabSdrh ** sqlite3Malloc() or sqlite3_malloc().
420fec00eabSdrh */
421fec00eabSdrh int sqlite3MallocSize(void *p){
422107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
423075c23afSdanielk1977   return sqlite3GlobalConfig.m.xSize(p);
424fec00eabSdrh }
425633e6d57Sdrh int sqlite3DbMallocSize(sqlite3 *db, void *p){
426039ca6abSdrh   assert( p!=0 );
427054bbabcSdrh   if( db==0 || !isLookaside(db,p) ){
428d879e3ebSdrh #ifdef SQLITE_DEBUG
42917bcb102Sdrh     if( db==0 ){
430d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
431d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
432633e6d57Sdrh     }else{
433d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
434d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
435633e6d57Sdrh     }
436054bbabcSdrh #endif
437054bbabcSdrh     return sqlite3GlobalConfig.m.xSize(p);
438054bbabcSdrh   }else{
439054bbabcSdrh     assert( sqlite3_mutex_held(db->mutex) );
440054bbabcSdrh     return db->lookaside.sz;
441633e6d57Sdrh   }
44217bcb102Sdrh }
443da4ca9d1Sdrh sqlite3_uint64 sqlite3_msize(void *p){
444d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
445d231aa3aSdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
446039ca6abSdrh   return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
447da4ca9d1Sdrh }
448fec00eabSdrh 
449fec00eabSdrh /*
450fec00eabSdrh ** Free memory previously obtained from sqlite3Malloc().
451fec00eabSdrh */
452fec00eabSdrh void sqlite3_free(void *p){
45371a1a0f4Sdrh   if( p==0 ) return;  /* IMP: R-49053-54554 */
454107b56e8Sdrh   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
455d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
456075c23afSdanielk1977   if( sqlite3GlobalConfig.bMemstat ){
457fec00eabSdrh     sqlite3_mutex_enter(mem0.mutex);
458af89fe66Sdrh     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
459af89fe66Sdrh     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
460075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
461fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
462fec00eabSdrh   }else{
463075c23afSdanielk1977     sqlite3GlobalConfig.m.xFree(p);
464fec00eabSdrh   }
465fec00eabSdrh }
466fec00eabSdrh 
467fec00eabSdrh /*
468b4586f12Sdrh ** Add the size of memory allocation "p" to the count in
469b4586f12Sdrh ** *db->pnBytesFreed.
470b4586f12Sdrh */
471b4586f12Sdrh static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
47256d90be1Sdrh   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
473b4586f12Sdrh }
474b4586f12Sdrh 
475b4586f12Sdrh /*
476633e6d57Sdrh ** Free memory that might be associated with a particular database
477*dbd6a7dcSdrh ** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
478*dbd6a7dcSdrh ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
479633e6d57Sdrh */
480*dbd6a7dcSdrh void sqlite3DbFreeNN(sqlite3 *db, void *p){
4817047e25cSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
482*dbd6a7dcSdrh   assert( p!=0 );
483174b9a16Sdrh   if( db ){
484174b9a16Sdrh     if( db->pnBytesFreed ){
485b4586f12Sdrh       measureAllocationSize(db, p);
486174b9a16Sdrh       return;
487d46def77Sdan     }
488633e6d57Sdrh     if( isLookaside(db, p) ){
489633e6d57Sdrh       LookasideSlot *pBuf = (LookasideSlot*)p;
490d879e3ebSdrh #ifdef SQLITE_DEBUG
4913608f177Sdrh       /* Trash all content in the buffer being freed */
4923608f177Sdrh       memset(p, 0xaa, db->lookaside.sz);
4933608f177Sdrh #endif
494633e6d57Sdrh       pBuf->pNext = db->lookaside.pFree;
495633e6d57Sdrh       db->lookaside.pFree = pBuf;
496633e6d57Sdrh       db->lookaside.nOut--;
497174b9a16Sdrh       return;
498174b9a16Sdrh     }
499174b9a16Sdrh   }
500d231aa3aSdrh   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
501d425864dSmistachkin   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
502174b9a16Sdrh   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
503107b56e8Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
504633e6d57Sdrh   sqlite3_free(p);
505633e6d57Sdrh }
506*dbd6a7dcSdrh void sqlite3DbFree(sqlite3 *db, void *p){
507*dbd6a7dcSdrh   assert( db==0 || sqlite3_mutex_held(db->mutex) );
508*dbd6a7dcSdrh   if( p ) sqlite3DbFreeNN(db, p);
509*dbd6a7dcSdrh }
510633e6d57Sdrh 
511633e6d57Sdrh /*
512fec00eabSdrh ** Change the size of an existing memory allocation
513fec00eabSdrh */
514da4ca9d1Sdrh void *sqlite3Realloc(void *pOld, u64 nBytes){
515ca591febSshaneh   int nOld, nNew, nDiff;
516fec00eabSdrh   void *pNew;
517d231aa3aSdrh   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
518d425864dSmistachkin   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
519fec00eabSdrh   if( pOld==0 ){
5208da47419Sdrh     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
521fec00eabSdrh   }
522da4ca9d1Sdrh   if( nBytes==0 ){
5238da47419Sdrh     sqlite3_free(pOld); /* IMP: R-26507-47431 */
524fec00eabSdrh     return 0;
525fec00eabSdrh   }
526b6063cf8Sdrh   if( nBytes>=0x7fffff00 ){
527b6063cf8Sdrh     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
528b6063cf8Sdrh     return 0;
529b6063cf8Sdrh   }
530fec00eabSdrh   nOld = sqlite3MallocSize(pOld);
5319f129f46Sdrh   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
5329f129f46Sdrh   ** argument to xRealloc is always a value returned by a prior call to
5339f129f46Sdrh   ** xRoundup. */
534da4ca9d1Sdrh   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
535fec00eabSdrh   if( nOld==nNew ){
536fec00eabSdrh     pNew = pOld;
5377c6791c8Sdrh   }else if( sqlite3GlobalConfig.bMemstat ){
5387c6791c8Sdrh     sqlite3_mutex_enter(mem0.mutex);
539b02392e6Sdrh     sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
5408e1bb041Sdrh     nDiff = nNew - nOld;
5411aa34695Sdrh     if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
5425fb72e5fSdrh           mem0.alarmThreshold-nDiff ){
5435fb72e5fSdrh       sqlite3MallocAlarm(nDiff);
5445fb72e5fSdrh     }
545075c23afSdanielk1977     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
5465fb72e5fSdrh     if( pNew==0 && mem0.alarmThreshold>0 ){
5475fb72e5fSdrh       sqlite3MallocAlarm((int)nBytes);
548075c23afSdanielk1977       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
549fec00eabSdrh     }
550fec00eabSdrh     if( pNew ){
551c702c7ccSdrh       nNew = sqlite3MallocSize(pNew);
552af89fe66Sdrh       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
553fec00eabSdrh     }
554fec00eabSdrh     sqlite3_mutex_leave(mem0.mutex);
555fec00eabSdrh   }else{
5567c6791c8Sdrh     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
557fec00eabSdrh   }
5588da47419Sdrh   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
559fec00eabSdrh   return pNew;
560fec00eabSdrh }
561fec00eabSdrh 
562fec00eabSdrh /*
563fec00eabSdrh ** The public interface to sqlite3Realloc.  Make sure that the memory
564fec00eabSdrh ** subsystem is initialized prior to invoking sqliteRealloc.
565fec00eabSdrh */
566fec00eabSdrh void *sqlite3_realloc(void *pOld, int n){
567fec00eabSdrh #ifndef SQLITE_OMIT_AUTOINIT
568fec00eabSdrh   if( sqlite3_initialize() ) return 0;
569fec00eabSdrh #endif
5708da47419Sdrh   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
571da4ca9d1Sdrh   return sqlite3Realloc(pOld, n);
572da4ca9d1Sdrh }
573da4ca9d1Sdrh void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
574da4ca9d1Sdrh #ifndef SQLITE_OMIT_AUTOINIT
575da4ca9d1Sdrh   if( sqlite3_initialize() ) return 0;
576da4ca9d1Sdrh #endif
577fec00eabSdrh   return sqlite3Realloc(pOld, n);
578fec00eabSdrh }
579fec00eabSdrh 
580a3152895Sdrh 
581a3152895Sdrh /*
58217435752Sdrh ** Allocate and zero memory.
583a3152895Sdrh */
584da4ca9d1Sdrh void *sqlite3MallocZero(u64 n){
585fec00eabSdrh   void *p = sqlite3Malloc(n);
586a3152895Sdrh   if( p ){
58720f3df04Sdrh     memset(p, 0, (size_t)n);
588a3152895Sdrh   }
589a3152895Sdrh   return p;
590a3152895Sdrh }
59117435752Sdrh 
59217435752Sdrh /*
59317435752Sdrh ** Allocate and zero memory.  If the allocation fails, make
59417435752Sdrh ** the mallocFailed flag in the connection pointer.
59517435752Sdrh */
596da4ca9d1Sdrh void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
597575fad65Sdrh   void *p;
598575fad65Sdrh   testcase( db==0 );
599575fad65Sdrh   p = sqlite3DbMallocRaw(db, n);
600575fad65Sdrh   if( p ) memset(p, 0, (size_t)n);
601575fad65Sdrh   return p;
60217435752Sdrh }
603575fad65Sdrh 
604575fad65Sdrh 
605575fad65Sdrh /* Finish the work of sqlite3DbMallocRawNN for the unusual and
606575fad65Sdrh ** slower case when the allocation cannot be fulfilled using lookaside.
607575fad65Sdrh */
608575fad65Sdrh static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
609575fad65Sdrh   void *p;
610575fad65Sdrh   assert( db!=0 );
611575fad65Sdrh   p = sqlite3Malloc(n);
612575fad65Sdrh   if( !p ) sqlite3OomFault(db);
613575fad65Sdrh   sqlite3MemdebugSetType(p,
614575fad65Sdrh          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
61517435752Sdrh   return p;
61617435752Sdrh }
61717435752Sdrh 
61817435752Sdrh /*
6191da26a48Sdrh ** Allocate memory, either lookaside (if possible) or heap.
6201da26a48Sdrh ** If the allocation fails, set the mallocFailed flag in
6211da26a48Sdrh ** the connection pointer.
622ddecae79Sdrh **
623ddecae79Sdrh ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
624ddecae79Sdrh ** failure on the same database connection) then always return 0.
625ddecae79Sdrh ** Hence for a particular database connection, once malloc starts
626ddecae79Sdrh ** failing, it fails consistently until mallocFailed is reset.
627ddecae79Sdrh ** This is an important assumption.  There are many places in the
628ddecae79Sdrh ** code that do things like this:
629ddecae79Sdrh **
630ddecae79Sdrh **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
631ddecae79Sdrh **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
632ddecae79Sdrh **         if( b ) a[10] = 9;
633ddecae79Sdrh **
634ddecae79Sdrh ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
635ddecae79Sdrh ** that all prior mallocs (ex: "a") worked too.
636575fad65Sdrh **
637575fad65Sdrh ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
638575fad65Sdrh ** not a NULL pointer.
63917435752Sdrh */
640da4ca9d1Sdrh void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
641575fad65Sdrh   void *p;
642575fad65Sdrh   if( db ) return sqlite3DbMallocRawNN(db, n);
643575fad65Sdrh   p = sqlite3Malloc(n);
644575fad65Sdrh   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
645575fad65Sdrh   return p;
646575fad65Sdrh }
647575fad65Sdrh void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
648f5818aa5Sdrh #ifndef SQLITE_OMIT_LOOKASIDE
649f5818aa5Sdrh   LookasideSlot *pBuf;
650575fad65Sdrh   assert( db!=0 );
651575fad65Sdrh   assert( sqlite3_mutex_held(db->mutex) );
652575fad65Sdrh   assert( db->pnBytesFreed==0 );
6534a642b60Sdrh   if( db->lookaside.bDisable==0 ){
6544a642b60Sdrh     assert( db->mallocFailed==0 );
6550b12e7f8Sdrh     if( n>db->lookaside.sz ){
6560b12e7f8Sdrh       db->lookaside.anStat[1]++;
6570b12e7f8Sdrh     }else if( (pBuf = db->lookaside.pFree)==0 ){
6580b12e7f8Sdrh       db->lookaside.anStat[2]++;
6590b12e7f8Sdrh     }else{
660633e6d57Sdrh       db->lookaside.pFree = pBuf->pNext;
661633e6d57Sdrh       db->lookaside.nOut++;
6620b12e7f8Sdrh       db->lookaside.anStat[0]++;
663633e6d57Sdrh       if( db->lookaside.nOut>db->lookaside.mxOut ){
664633e6d57Sdrh         db->lookaside.mxOut = db->lookaside.nOut;
665633e6d57Sdrh       }
666633e6d57Sdrh       return (void*)pBuf;
667633e6d57Sdrh     }
6684a642b60Sdrh   }else if( db->mallocFailed ){
6694a642b60Sdrh     return 0;
670633e6d57Sdrh   }
671ddecae79Sdrh #else
672f5818aa5Sdrh   assert( db!=0 );
673f5818aa5Sdrh   assert( sqlite3_mutex_held(db->mutex) );
674f5818aa5Sdrh   assert( db->pnBytesFreed==0 );
675575fad65Sdrh   if( db->mallocFailed ){
676ddecae79Sdrh     return 0;
677ddecae79Sdrh   }
6784150ebf8Sdrh #endif
6791da26a48Sdrh   return dbMallocRawFinish(db, n);
6801da26a48Sdrh }
68117435752Sdrh 
682b84e574cSdrh /* Forward declaration */
683b84e574cSdrh static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
684b84e574cSdrh 
68526783a58Sdanielk1977 /*
68626783a58Sdanielk1977 ** Resize the block of memory pointed to by p to n bytes. If the
68726783a58Sdanielk1977 ** resize fails, set the mallocFailed flag in the connection object.
68826783a58Sdanielk1977 */
689da4ca9d1Sdrh void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
690b84e574cSdrh   assert( db!=0 );
691575fad65Sdrh   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
692b84e574cSdrh   assert( sqlite3_mutex_held(db->mutex) );
693b84e574cSdrh   if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
694b84e574cSdrh   return dbReallocFinish(db, p, n);
695b84e574cSdrh }
696b84e574cSdrh static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
697a1644fd8Sdanielk1977   void *pNew = 0;
698d9da78a2Sdrh   assert( db!=0 );
699b84e574cSdrh   assert( p!=0 );
700a1644fd8Sdanielk1977   if( db->mallocFailed==0 ){
701633e6d57Sdrh     if( isLookaside(db, p) ){
702575fad65Sdrh       pNew = sqlite3DbMallocRawNN(db, n);
703633e6d57Sdrh       if( pNew ){
704633e6d57Sdrh         memcpy(pNew, p, db->lookaside.sz);
705633e6d57Sdrh         sqlite3DbFree(db, p);
706633e6d57Sdrh       }
707633e6d57Sdrh     }else{
708d231aa3aSdrh       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
709d425864dSmistachkin       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
710107b56e8Sdrh       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
7113329a63aSdrh       pNew = sqlite3_realloc64(p, n);
712a1644fd8Sdanielk1977       if( !pNew ){
7134a642b60Sdrh         sqlite3OomFault(db);
714a1644fd8Sdanielk1977       }
715d231aa3aSdrh       sqlite3MemdebugSetType(pNew,
7164a642b60Sdrh             (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
717a1644fd8Sdanielk1977     }
718633e6d57Sdrh   }
719a1644fd8Sdanielk1977   return pNew;
720a1644fd8Sdanielk1977 }
721a1644fd8Sdanielk1977 
72217435752Sdrh /*
72317435752Sdrh ** Attempt to reallocate p.  If the reallocation fails, then free p
72417435752Sdrh ** and set the mallocFailed flag in the database connection.
72517435752Sdrh */
726da4ca9d1Sdrh void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
727a3152895Sdrh   void *pNew;
728a1644fd8Sdanielk1977   pNew = sqlite3DbRealloc(db, p, n);
729a3152895Sdrh   if( !pNew ){
730633e6d57Sdrh     sqlite3DbFree(db, p);
731a3152895Sdrh   }
732a3152895Sdrh   return pNew;
733a3152895Sdrh }
734a3152895Sdrh 
735a3152895Sdrh /*
736a3152895Sdrh ** Make a copy of a string in memory obtained from sqliteMalloc(). These
737a3152895Sdrh ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
738a3152895Sdrh ** is because when memory debugging is turned on, these two functions are
739a3152895Sdrh ** called via macros that record the current file and line number in the
740a3152895Sdrh ** ThreadData structure.
741a3152895Sdrh */
742633e6d57Sdrh char *sqlite3DbStrDup(sqlite3 *db, const char *z){
743a3152895Sdrh   char *zNew;
744633e6d57Sdrh   size_t n;
745633e6d57Sdrh   if( z==0 ){
746633e6d57Sdrh     return 0;
747a3152895Sdrh   }
748cee11adaSdrh   n = strlen(z) + 1;
749cee11adaSdrh   zNew = sqlite3DbMallocRaw(db, n);
750a3152895Sdrh   if( zNew ){
751a3152895Sdrh     memcpy(zNew, z, n);
7521e536953Sdanielk1977   }
7531e536953Sdanielk1977   return zNew;
7541e536953Sdanielk1977 }
755da4ca9d1Sdrh char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
756633e6d57Sdrh   char *zNew;
757575fad65Sdrh   assert( db!=0 );
758633e6d57Sdrh   if( z==0 ){
759633e6d57Sdrh     return 0;
760633e6d57Sdrh   }
761633e6d57Sdrh   assert( (n&0x7fffffff)==n );
762575fad65Sdrh   zNew = sqlite3DbMallocRawNN(db, n+1);
763633e6d57Sdrh   if( zNew ){
76420f3df04Sdrh     memcpy(zNew, z, (size_t)n);
765633e6d57Sdrh     zNew[n] = 0;
7661e536953Sdanielk1977   }
7671e536953Sdanielk1977   return zNew;
7681e536953Sdanielk1977 }
7691e536953Sdanielk1977 
770a3152895Sdrh /*
77122c17b8bSdrh ** Free any prior content in *pz and replace it with a copy of zNew.
772a3152895Sdrh */
77322c17b8bSdrh void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
774633e6d57Sdrh   sqlite3DbFree(db, *pz);
77522c17b8bSdrh   *pz = sqlite3DbStrDup(db, zNew);
776a3152895Sdrh }
777a3152895Sdrh 
778b50c65d5Sdrh /*
7794a642b60Sdrh ** Call this routine to record the fact that an OOM (out-of-memory) error
7804a642b60Sdrh ** has happened.  This routine will set db->mallocFailed, and also
7814a642b60Sdrh ** temporarily disable the lookaside memory allocator and interrupt
7824a642b60Sdrh ** any running VDBEs.
7834a642b60Sdrh */
7844a642b60Sdrh void sqlite3OomFault(sqlite3 *db){
7854a642b60Sdrh   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
7864a642b60Sdrh     db->mallocFailed = 1;
7874a642b60Sdrh     if( db->nVdbeExec>0 ){
7884a642b60Sdrh       db->u1.isInterrupted = 1;
7894a642b60Sdrh     }
7904a642b60Sdrh     db->lookaside.bDisable++;
7914a642b60Sdrh   }
7924a642b60Sdrh }
7934a642b60Sdrh 
7944a642b60Sdrh /*
7954a642b60Sdrh ** This routine reactivates the memory allocator and clears the
7964a642b60Sdrh ** db->mallocFailed flag as necessary.
7974a642b60Sdrh **
7984a642b60Sdrh ** The memory allocator is not restarted if there are running
7994a642b60Sdrh ** VDBEs.
8004a642b60Sdrh */
8014a642b60Sdrh void sqlite3OomClear(sqlite3 *db){
8024a642b60Sdrh   if( db->mallocFailed && db->nVdbeExec==0 ){
8034a642b60Sdrh     db->mallocFailed = 0;
8044a642b60Sdrh     db->u1.isInterrupted = 0;
8054a642b60Sdrh     assert( db->lookaside.bDisable>0 );
8064a642b60Sdrh     db->lookaside.bDisable--;
8074a642b60Sdrh   }
8084a642b60Sdrh }
8094a642b60Sdrh 
8104a642b60Sdrh /*
811b50c65d5Sdrh ** Take actions at the end of an API call to indicate an OOM error
812b50c65d5Sdrh */
813b50c65d5Sdrh static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
8144a642b60Sdrh   sqlite3OomClear(db);
815b50c65d5Sdrh   sqlite3Error(db, SQLITE_NOMEM);
816fad3039cSmistachkin   return SQLITE_NOMEM_BKPT;
817b50c65d5Sdrh }
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) );
838b50c65d5Sdrh   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
839b50c65d5Sdrh     return apiOomError(db);
840a3152895Sdrh   }
841b50c65d5Sdrh   return rc & db->errMask;
842a3152895Sdrh }
843