xref: /sqlite-3.40.0/src/malloc.c (revision 9edb5ceb)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 **
13 ** Memory allocation functions used throughout sqlite.
14 */
15 #include "sqliteInt.h"
16 #include <stdarg.h>
17 
18 /*
19 ** Attempt to release up to n bytes of non-essential memory currently
20 ** held by SQLite. An example of non-essential memory is memory used to
21 ** cache database pages that are not currently in use.
22 */
23 int sqlite3_release_memory(int n){
24 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
25   return sqlite3PcacheReleaseMemory(n);
26 #else
27   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
28   ** is a no-op returning zero if SQLite is not compiled with
29   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
30   UNUSED_PARAMETER(n);
31   return 0;
32 #endif
33 }
34 
35 /*
36 ** An instance of the following object records the location of
37 ** each unused scratch buffer.
38 */
39 typedef struct ScratchFreeslot {
40   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
41 } ScratchFreeslot;
42 
43 /*
44 ** State information local to the memory allocation subsystem.
45 */
46 static SQLITE_WSD struct Mem0Global {
47   sqlite3_mutex *mutex;         /* Mutex to serialize access */
48 
49   /*
50   ** The alarm callback and its arguments.  The mem0.mutex lock will
51   ** be held while the callback is running.  Recursive calls into
52   ** the memory subsystem are allowed, but no new callbacks will be
53   ** issued.
54   */
55   sqlite3_int64 alarmThreshold;
56   void (*alarmCallback)(void*, sqlite3_int64,int);
57   void *alarmArg;
58 
59   /*
60   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
61   ** (so that a range test can be used to determine if an allocation
62   ** being freed came from pScratch) and a pointer to the list of
63   ** unused scratch allocations.
64   */
65   void *pScratchEnd;
66   ScratchFreeslot *pScratchFree;
67   u32 nScratchFree;
68 
69   /*
70   ** True if heap is nearly "full" where "full" is defined by the
71   ** sqlite3_soft_heap_limit() setting.
72   */
73   int nearlyFull;
74 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
75 
76 #define mem0 GLOBAL(struct Mem0Global, mem0)
77 
78 /*
79 ** Return the memory allocator mutex. sqlite3_status() needs it.
80 */
81 sqlite3_mutex *sqlite3MallocMutex(void){
82   return mem0.mutex;
83 }
84 
85 /*
86 ** This routine runs when the memory allocator sees that the
87 ** total memory allocation is about to exceed the soft heap
88 ** limit.
89 */
90 static void softHeapLimitEnforcer(
91   void *NotUsed,
92   sqlite3_int64 NotUsed2,
93   int allocSize
94 ){
95   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96   sqlite3_release_memory(allocSize);
97 }
98 
99 /*
100 ** Change the alarm callback
101 */
102 static int sqlite3MemoryAlarm(
103   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
104   void *pArg,
105   sqlite3_int64 iThreshold
106 ){
107   sqlite3_int64 nUsed;
108   sqlite3_mutex_enter(mem0.mutex);
109   mem0.alarmCallback = xCallback;
110   mem0.alarmArg = pArg;
111   mem0.alarmThreshold = iThreshold;
112   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
113   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
114   sqlite3_mutex_leave(mem0.mutex);
115   return SQLITE_OK;
116 }
117 
118 #ifndef SQLITE_OMIT_DEPRECATED
119 /*
120 ** Deprecated external interface.  Internal/core SQLite code
121 ** should call sqlite3MemoryAlarm.
122 */
123 int sqlite3_memory_alarm(
124   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
125   void *pArg,
126   sqlite3_int64 iThreshold
127 ){
128   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
129 }
130 #endif
131 
132 /*
133 ** Set the soft heap-size limit for the library. Passing a zero or
134 ** negative value indicates no limit.
135 */
136 sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
137   sqlite3_int64 priorLimit;
138   sqlite3_int64 excess;
139 #ifndef SQLITE_OMIT_AUTOINIT
140   int rc = sqlite3_initialize();
141   if( rc ) return -1;
142 #endif
143   sqlite3_mutex_enter(mem0.mutex);
144   priorLimit = mem0.alarmThreshold;
145   sqlite3_mutex_leave(mem0.mutex);
146   if( n<0 ) return priorLimit;
147   if( n>0 ){
148     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
149   }else{
150     sqlite3MemoryAlarm(0, 0, 0);
151   }
152   excess = sqlite3_memory_used() - n;
153   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
154   return priorLimit;
155 }
156 void sqlite3_soft_heap_limit(int n){
157   if( n<0 ) n = 0;
158   sqlite3_soft_heap_limit64(n);
159 }
160 
161 /*
162 ** Initialize the memory allocation subsystem.
163 */
164 int sqlite3MallocInit(void){
165   int rc;
166   if( sqlite3GlobalConfig.m.xMalloc==0 ){
167     sqlite3MemSetDefault();
168   }
169   memset(&mem0, 0, sizeof(mem0));
170   if( sqlite3GlobalConfig.bCoreMutex ){
171     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
172   }
173   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
174       && sqlite3GlobalConfig.nScratch>0 ){
175     int i, n, sz;
176     ScratchFreeslot *pSlot;
177     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
178     sqlite3GlobalConfig.szScratch = sz;
179     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
180     n = sqlite3GlobalConfig.nScratch;
181     mem0.pScratchFree = pSlot;
182     mem0.nScratchFree = n;
183     for(i=0; i<n-1; i++){
184       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
185       pSlot = pSlot->pNext;
186     }
187     pSlot->pNext = 0;
188     mem0.pScratchEnd = (void*)&pSlot[1];
189   }else{
190     mem0.pScratchEnd = 0;
191     sqlite3GlobalConfig.pScratch = 0;
192     sqlite3GlobalConfig.szScratch = 0;
193     sqlite3GlobalConfig.nScratch = 0;
194   }
195   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
196       || sqlite3GlobalConfig.nPage<=0 ){
197     sqlite3GlobalConfig.pPage = 0;
198     sqlite3GlobalConfig.szPage = 0;
199   }
200   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
201   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
202   return rc;
203 }
204 
205 /*
206 ** Return true if the heap is currently under memory pressure - in other
207 ** words if the amount of heap used is close to the limit set by
208 ** sqlite3_soft_heap_limit().
209 */
210 int sqlite3HeapNearlyFull(void){
211   return mem0.nearlyFull;
212 }
213 
214 /*
215 ** Deinitialize the memory allocation subsystem.
216 */
217 void sqlite3MallocEnd(void){
218   if( sqlite3GlobalConfig.m.xShutdown ){
219     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
220   }
221   memset(&mem0, 0, sizeof(mem0));
222 }
223 
224 /*
225 ** Return the amount of memory currently checked out.
226 */
227 sqlite3_int64 sqlite3_memory_used(void){
228   sqlite3_int64 res, mx;
229   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
230   return res;
231 }
232 
233 /*
234 ** Return the maximum amount of memory that has ever been
235 ** checked out since either the beginning of this process
236 ** or since the most recent reset.
237 */
238 sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
239   sqlite3_int64 res, mx;
240   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
241   return mx;
242 }
243 
244 /*
245 ** Trigger the alarm
246 */
247 static void sqlite3MallocAlarm(int nByte){
248   void (*xCallback)(void*,sqlite3_int64,int);
249   sqlite3_int64 nowUsed;
250   void *pArg;
251   if( mem0.alarmCallback==0 ) return;
252   xCallback = mem0.alarmCallback;
253   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
254   pArg = mem0.alarmArg;
255   mem0.alarmCallback = 0;
256   sqlite3_mutex_leave(mem0.mutex);
257   xCallback(pArg, nowUsed, nByte);
258   sqlite3_mutex_enter(mem0.mutex);
259   mem0.alarmCallback = xCallback;
260   mem0.alarmArg = pArg;
261 }
262 
263 /*
264 ** Do a memory allocation with statistics and alarms.  Assume the
265 ** lock is already held.
266 */
267 static int mallocWithAlarm(int n, void **pp){
268   int nFull;
269   void *p;
270   assert( sqlite3_mutex_held(mem0.mutex) );
271   nFull = sqlite3GlobalConfig.m.xRoundup(n);
272   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
273   if( mem0.alarmCallback!=0 ){
274     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
275     if( nUsed >= mem0.alarmThreshold - nFull ){
276       mem0.nearlyFull = 1;
277       sqlite3MallocAlarm(nFull);
278     }else{
279       mem0.nearlyFull = 0;
280     }
281   }
282   p = sqlite3GlobalConfig.m.xMalloc(nFull);
283 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
284   if( p==0 && mem0.alarmCallback ){
285     sqlite3MallocAlarm(nFull);
286     p = sqlite3GlobalConfig.m.xMalloc(nFull);
287   }
288 #endif
289   if( p ){
290     nFull = sqlite3MallocSize(p);
291     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
292     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
293   }
294   *pp = p;
295   return nFull;
296 }
297 
298 /*
299 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
300 ** assumes the memory subsystem has already been initialized.
301 */
302 void *sqlite3Malloc(u64 n){
303   void *p;
304   if( n==0 || n>=0x7fffff00 ){
305     /* A memory allocation of a number of bytes which is near the maximum
306     ** signed integer value might cause an integer overflow inside of the
307     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
308     ** 255 bytes of overhead.  SQLite itself will never use anything near
309     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
310     p = 0;
311   }else if( sqlite3GlobalConfig.bMemstat ){
312     sqlite3_mutex_enter(mem0.mutex);
313     mallocWithAlarm((int)n, &p);
314     sqlite3_mutex_leave(mem0.mutex);
315   }else{
316     p = sqlite3GlobalConfig.m.xMalloc((int)n);
317   }
318   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
319   return p;
320 }
321 
322 /*
323 ** This version of the memory allocation is for use by the application.
324 ** First make sure the memory subsystem is initialized, then do the
325 ** allocation.
326 */
327 void *sqlite3_malloc(int n){
328 #ifndef SQLITE_OMIT_AUTOINIT
329   if( sqlite3_initialize() ) return 0;
330 #endif
331   return n<=0 ? 0 : sqlite3Malloc(n);
332 }
333 void *sqlite3_malloc64(sqlite3_uint64 n){
334 #ifndef SQLITE_OMIT_AUTOINIT
335   if( sqlite3_initialize() ) return 0;
336 #endif
337   return sqlite3Malloc(n);
338 }
339 
340 /*
341 ** Each thread may only have a single outstanding allocation from
342 ** xScratchMalloc().  We verify this constraint in the single-threaded
343 ** case by setting scratchAllocOut to 1 when an allocation
344 ** is outstanding clearing it when the allocation is freed.
345 */
346 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
347 static int scratchAllocOut = 0;
348 #endif
349 
350 
351 /*
352 ** Allocate memory that is to be used and released right away.
353 ** This routine is similar to alloca() in that it is not intended
354 ** for situations where the memory might be held long-term.  This
355 ** routine is intended to get memory to old large transient data
356 ** structures that would not normally fit on the stack of an
357 ** embedded processor.
358 */
359 void *sqlite3ScratchMalloc(int n){
360   void *p;
361   assert( n>0 );
362 
363   sqlite3_mutex_enter(mem0.mutex);
364   sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
365   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
366     p = mem0.pScratchFree;
367     mem0.pScratchFree = mem0.pScratchFree->pNext;
368     mem0.nScratchFree--;
369     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
370     sqlite3_mutex_leave(mem0.mutex);
371   }else{
372     sqlite3_mutex_leave(mem0.mutex);
373     p = sqlite3Malloc(n);
374     if( sqlite3GlobalConfig.bMemstat && p ){
375       sqlite3_mutex_enter(mem0.mutex);
376       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
377       sqlite3_mutex_leave(mem0.mutex);
378     }
379     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
380   }
381   assert( sqlite3_mutex_notheld(mem0.mutex) );
382 
383 
384 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
385   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
386   ** buffers per thread.
387   **
388   ** This can only be checked in single-threaded mode.
389   */
390   assert( scratchAllocOut==0 );
391   if( p ) scratchAllocOut++;
392 #endif
393 
394   return p;
395 }
396 void sqlite3ScratchFree(void *p){
397   if( p ){
398 
399 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
400     /* Verify that no more than two scratch allocation per thread
401     ** is outstanding at one time.  (This is only checked in the
402     ** single-threaded case since checking in the multi-threaded case
403     ** would be much more complicated.) */
404     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
405     scratchAllocOut--;
406 #endif
407 
408     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
409       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
410       ScratchFreeslot *pSlot;
411       pSlot = (ScratchFreeslot*)p;
412       sqlite3_mutex_enter(mem0.mutex);
413       pSlot->pNext = mem0.pScratchFree;
414       mem0.pScratchFree = pSlot;
415       mem0.nScratchFree++;
416       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
417       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
418       sqlite3_mutex_leave(mem0.mutex);
419     }else{
420       /* Release memory back to the heap */
421       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
422       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
423       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
424       if( sqlite3GlobalConfig.bMemstat ){
425         int iSize = sqlite3MallocSize(p);
426         sqlite3_mutex_enter(mem0.mutex);
427         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
428         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
429         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
430         sqlite3GlobalConfig.m.xFree(p);
431         sqlite3_mutex_leave(mem0.mutex);
432       }else{
433         sqlite3GlobalConfig.m.xFree(p);
434       }
435     }
436   }
437 }
438 
439 /*
440 ** TRUE if p is a lookaside memory allocation from db
441 */
442 #ifndef SQLITE_OMIT_LOOKASIDE
443 static int isLookaside(sqlite3 *db, void *p){
444   return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
445 }
446 #else
447 #define isLookaside(A,B) 0
448 #endif
449 
450 /*
451 ** Return the size of a memory allocation previously obtained from
452 ** sqlite3Malloc() or sqlite3_malloc().
453 */
454 int sqlite3MallocSize(void *p){
455   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
456   return sqlite3GlobalConfig.m.xSize(p);
457 }
458 int sqlite3DbMallocSize(sqlite3 *db, void *p){
459   if( db==0 ){
460     assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
461     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
462     return sqlite3MallocSize(p);
463   }else{
464     assert( sqlite3_mutex_held(db->mutex) );
465     if( isLookaside(db, p) ){
466       return db->lookaside.sz;
467     }else{
468       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
469       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
470       return sqlite3GlobalConfig.m.xSize(p);
471     }
472   }
473 }
474 sqlite3_uint64 sqlite3_msize(void *p){
475   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
476   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
477   return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
478 }
479 
480 /*
481 ** Free memory previously obtained from sqlite3Malloc().
482 */
483 void sqlite3_free(void *p){
484   if( p==0 ) return;  /* IMP: R-49053-54554 */
485   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
486   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
487   if( sqlite3GlobalConfig.bMemstat ){
488     sqlite3_mutex_enter(mem0.mutex);
489     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
490     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
491     sqlite3GlobalConfig.m.xFree(p);
492     sqlite3_mutex_leave(mem0.mutex);
493   }else{
494     sqlite3GlobalConfig.m.xFree(p);
495   }
496 }
497 
498 /*
499 ** Add the size of memory allocation "p" to the count in
500 ** *db->pnBytesFreed.
501 */
502 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
503   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
504 }
505 
506 /*
507 ** Free memory that might be associated with a particular database
508 ** connection.
509 */
510 void sqlite3DbFree(sqlite3 *db, void *p){
511   assert( db==0 || sqlite3_mutex_held(db->mutex) );
512   if( p==0 ) return;
513   if( db ){
514     if( db->pnBytesFreed ){
515       measureAllocationSize(db, p);
516       return;
517     }
518     if( isLookaside(db, p) ){
519       LookasideSlot *pBuf = (LookasideSlot*)p;
520 #if SQLITE_DEBUG
521       /* Trash all content in the buffer being freed */
522       memset(p, 0xaa, db->lookaside.sz);
523 #endif
524       pBuf->pNext = db->lookaside.pFree;
525       db->lookaside.pFree = pBuf;
526       db->lookaside.nOut--;
527       return;
528     }
529   }
530   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
531   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
532   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
533   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
534   sqlite3_free(p);
535 }
536 
537 /*
538 ** Change the size of an existing memory allocation
539 */
540 void *sqlite3Realloc(void *pOld, u64 nBytes){
541   int nOld, nNew, nDiff;
542   void *pNew;
543   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
544   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
545   if( pOld==0 ){
546     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
547   }
548   if( nBytes==0 ){
549     sqlite3_free(pOld); /* IMP: R-26507-47431 */
550     return 0;
551   }
552   if( nBytes>=0x7fffff00 ){
553     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
554     return 0;
555   }
556   nOld = sqlite3MallocSize(pOld);
557   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
558   ** argument to xRealloc is always a value returned by a prior call to
559   ** xRoundup. */
560   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
561   if( nOld==nNew ){
562     pNew = pOld;
563   }else if( sqlite3GlobalConfig.bMemstat ){
564     sqlite3_mutex_enter(mem0.mutex);
565     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
566     nDiff = nNew - nOld;
567     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
568           mem0.alarmThreshold-nDiff ){
569       sqlite3MallocAlarm(nDiff);
570     }
571     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
572     if( pNew==0 && mem0.alarmCallback ){
573       sqlite3MallocAlarm((int)nBytes);
574       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
575     }
576     if( pNew ){
577       nNew = sqlite3MallocSize(pNew);
578       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
579     }
580     sqlite3_mutex_leave(mem0.mutex);
581   }else{
582     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
583   }
584   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
585   return pNew;
586 }
587 
588 /*
589 ** The public interface to sqlite3Realloc.  Make sure that the memory
590 ** subsystem is initialized prior to invoking sqliteRealloc.
591 */
592 void *sqlite3_realloc(void *pOld, int n){
593 #ifndef SQLITE_OMIT_AUTOINIT
594   if( sqlite3_initialize() ) return 0;
595 #endif
596   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
597   return sqlite3Realloc(pOld, n);
598 }
599 void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
600 #ifndef SQLITE_OMIT_AUTOINIT
601   if( sqlite3_initialize() ) return 0;
602 #endif
603   return sqlite3Realloc(pOld, n);
604 }
605 
606 
607 /*
608 ** Allocate and zero memory.
609 */
610 void *sqlite3MallocZero(u64 n){
611   void *p = sqlite3Malloc(n);
612   if( p ){
613     memset(p, 0, (size_t)n);
614   }
615   return p;
616 }
617 
618 /*
619 ** Allocate and zero memory.  If the allocation fails, make
620 ** the mallocFailed flag in the connection pointer.
621 */
622 void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
623   void *p = sqlite3DbMallocRaw(db, n);
624   if( p ){
625     memset(p, 0, (size_t)n);
626   }
627   return p;
628 }
629 
630 /*
631 ** Allocate and zero memory.  If the allocation fails, make
632 ** the mallocFailed flag in the connection pointer.
633 **
634 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
635 ** failure on the same database connection) then always return 0.
636 ** Hence for a particular database connection, once malloc starts
637 ** failing, it fails consistently until mallocFailed is reset.
638 ** This is an important assumption.  There are many places in the
639 ** code that do things like this:
640 **
641 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
642 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
643 **         if( b ) a[10] = 9;
644 **
645 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
646 ** that all prior mallocs (ex: "a") worked too.
647 */
648 void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
649   void *p;
650   assert( db==0 || sqlite3_mutex_held(db->mutex) );
651   assert( db==0 || db->pnBytesFreed==0 );
652 #ifndef SQLITE_OMIT_LOOKASIDE
653   if( db ){
654     LookasideSlot *pBuf;
655     if( db->mallocFailed ){
656       return 0;
657     }
658     if( db->lookaside.bEnabled ){
659       if( n>db->lookaside.sz ){
660         db->lookaside.anStat[1]++;
661       }else if( (pBuf = db->lookaside.pFree)==0 ){
662         db->lookaside.anStat[2]++;
663       }else{
664         db->lookaside.pFree = pBuf->pNext;
665         db->lookaside.nOut++;
666         db->lookaside.anStat[0]++;
667         if( db->lookaside.nOut>db->lookaside.mxOut ){
668           db->lookaside.mxOut = db->lookaside.nOut;
669         }
670         return (void*)pBuf;
671       }
672     }
673   }
674 #else
675   if( db && db->mallocFailed ){
676     return 0;
677   }
678 #endif
679   p = sqlite3Malloc(n);
680   if( !p && db ){
681     db->mallocFailed = 1;
682   }
683   sqlite3MemdebugSetType(p,
684          (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
685   return p;
686 }
687 
688 /*
689 ** Resize the block of memory pointed to by p to n bytes. If the
690 ** resize fails, set the mallocFailed flag in the connection object.
691 */
692 void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
693   void *pNew = 0;
694   assert( db!=0 );
695   assert( sqlite3_mutex_held(db->mutex) );
696   if( db->mallocFailed==0 ){
697     if( p==0 ){
698       return sqlite3DbMallocRaw(db, n);
699     }
700     if( isLookaside(db, p) ){
701       if( n<=db->lookaside.sz ){
702         return p;
703       }
704       pNew = sqlite3DbMallocRaw(db, n);
705       if( pNew ){
706         memcpy(pNew, p, db->lookaside.sz);
707         sqlite3DbFree(db, p);
708       }
709     }else{
710       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
711       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
712       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
713       pNew = sqlite3_realloc64(p, n);
714       if( !pNew ){
715         db->mallocFailed = 1;
716       }
717       sqlite3MemdebugSetType(pNew,
718             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
719     }
720   }
721   return pNew;
722 }
723 
724 /*
725 ** Attempt to reallocate p.  If the reallocation fails, then free p
726 ** and set the mallocFailed flag in the database connection.
727 */
728 void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
729   void *pNew;
730   pNew = sqlite3DbRealloc(db, p, n);
731   if( !pNew ){
732     sqlite3DbFree(db, p);
733   }
734   return pNew;
735 }
736 
737 /*
738 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
739 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
740 ** is because when memory debugging is turned on, these two functions are
741 ** called via macros that record the current file and line number in the
742 ** ThreadData structure.
743 */
744 char *sqlite3DbStrDup(sqlite3 *db, const char *z){
745   char *zNew;
746   size_t n;
747   if( z==0 ){
748     return 0;
749   }
750   n = sqlite3Strlen30(z) + 1;
751   assert( (n&0x7fffffff)==n );
752   zNew = sqlite3DbMallocRaw(db, (int)n);
753   if( zNew ){
754     memcpy(zNew, z, n);
755   }
756   return zNew;
757 }
758 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
759   char *zNew;
760   if( z==0 ){
761     return 0;
762   }
763   assert( (n&0x7fffffff)==n );
764   zNew = sqlite3DbMallocRaw(db, n+1);
765   if( zNew ){
766     memcpy(zNew, z, (size_t)n);
767     zNew[n] = 0;
768   }
769   return zNew;
770 }
771 
772 /*
773 ** Free any prior content in *pz and replace it with a copy of zNew.
774 */
775 void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
776   sqlite3DbFree(db, *pz);
777   *pz = sqlite3DbStrDup(db, zNew);
778 }
779 
780 /*
781 ** Take actions at the end of an API call to indicate an OOM error
782 */
783 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
784   db->mallocFailed = 0;
785   sqlite3Error(db, SQLITE_NOMEM);
786   return SQLITE_NOMEM;
787 }
788 
789 /*
790 ** This function must be called before exiting any API function (i.e.
791 ** returning control to the user) that has called sqlite3_malloc or
792 ** sqlite3_realloc.
793 **
794 ** The returned value is normally a copy of the second argument to this
795 ** function. However, if a malloc() failure has occurred since the previous
796 ** invocation SQLITE_NOMEM is returned instead.
797 **
798 ** If an OOM as occurred, then the connection error-code (the value
799 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
800 */
801 int sqlite3ApiExit(sqlite3* db, int rc){
802   /* If the db handle must hold the connection handle mutex here.
803   ** Otherwise the read (and possible write) of db->mallocFailed
804   ** is unsafe, as is the call to sqlite3Error().
805   */
806   assert( db!=0 );
807   assert( sqlite3_mutex_held(db->mutex) );
808   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
809     return apiOomError(db);
810   }
811   return rc & db->errMask;
812 }
813