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