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