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