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