xref: /sqlite-3.40.0/src/malloc.c (revision 6695f47e)
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 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
360   scratchAllocOut = p!=0;
361 #endif
362   return p;
363 }
364 void sqlite3ScratchFree(void *p){
365   if( p ){
366 
367 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
368     /* Verify that no more than one scratch allocation per thread
369     ** is outstanding at one time.  (This is only checked in the
370     ** single-threaded case since checking in the multi-threaded case
371     ** would be much more complicated.) */
372     assert( scratchAllocOut==1 );
373     scratchAllocOut = 0;
374 #endif
375 
376     if( sqlite3GlobalConfig.pScratch==0
377            || p<sqlite3GlobalConfig.pScratch
378            || p>=(void*)mem0.aScratchFree ){
379       if( sqlite3GlobalConfig.bMemstat ){
380         int iSize = sqlite3MallocSize(p);
381         sqlite3_mutex_enter(mem0.mutex);
382         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
383         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
384         sqlite3GlobalConfig.m.xFree(p);
385         sqlite3_mutex_leave(mem0.mutex);
386       }else{
387         sqlite3GlobalConfig.m.xFree(p);
388       }
389     }else{
390       int i;
391       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
392       i /= sqlite3GlobalConfig.szScratch;
393       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
394       sqlite3_mutex_enter(mem0.mutex);
395       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
396       mem0.aScratchFree[mem0.nScratchFree++] = i;
397       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
398       sqlite3_mutex_leave(mem0.mutex);
399     }
400   }
401 }
402 
403 /*
404 ** TRUE if p is a lookaside memory allocation from db
405 */
406 #ifndef SQLITE_OMIT_LOOKASIDE
407 static int isLookaside(sqlite3 *db, void *p){
408   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
409 }
410 #else
411 #define isLookaside(A,B) 0
412 #endif
413 
414 /*
415 ** Return the size of a memory allocation previously obtained from
416 ** sqlite3Malloc() or sqlite3_malloc().
417 */
418 int sqlite3MallocSize(void *p){
419   return sqlite3GlobalConfig.m.xSize(p);
420 }
421 int sqlite3DbMallocSize(sqlite3 *db, void *p){
422   assert( db==0 || sqlite3_mutex_held(db->mutex) );
423   if( isLookaside(db, p) ){
424     return db->lookaside.sz;
425   }else{
426     return sqlite3GlobalConfig.m.xSize(p);
427   }
428 }
429 
430 /*
431 ** Free memory previously obtained from sqlite3Malloc().
432 */
433 void sqlite3_free(void *p){
434   if( p==0 ) return;
435   if( sqlite3GlobalConfig.bMemstat ){
436     sqlite3_mutex_enter(mem0.mutex);
437     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
438     sqlite3GlobalConfig.m.xFree(p);
439     sqlite3_mutex_leave(mem0.mutex);
440   }else{
441     sqlite3GlobalConfig.m.xFree(p);
442   }
443 }
444 
445 /*
446 ** Free memory that might be associated with a particular database
447 ** connection.
448 */
449 void sqlite3DbFree(sqlite3 *db, void *p){
450   assert( db==0 || sqlite3_mutex_held(db->mutex) );
451   if( isLookaside(db, p) ){
452     LookasideSlot *pBuf = (LookasideSlot*)p;
453     pBuf->pNext = db->lookaside.pFree;
454     db->lookaside.pFree = pBuf;
455     db->lookaside.nOut--;
456   }else{
457     sqlite3_free(p);
458   }
459 }
460 
461 /*
462 ** Change the size of an existing memory allocation
463 */
464 void *sqlite3Realloc(void *pOld, int nBytes){
465   int nOld, nNew;
466   void *pNew;
467   if( pOld==0 ){
468     return sqlite3Malloc(nBytes);
469   }
470   if( nBytes<=0 ){
471     sqlite3_free(pOld);
472     return 0;
473   }
474   if( nBytes>=0x7fffff00 ){
475     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
476     return 0;
477   }
478   nOld = sqlite3MallocSize(pOld);
479   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
480   if( nOld==nNew ){
481     pNew = pOld;
482   }else if( sqlite3GlobalConfig.bMemstat ){
483     sqlite3_mutex_enter(mem0.mutex);
484     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
485     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
486           mem0.alarmThreshold ){
487       sqlite3MallocAlarm(nNew-nOld);
488     }
489     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
490     if( pNew==0 && mem0.alarmCallback ){
491       sqlite3MallocAlarm(nBytes);
492       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
493     }
494     if( pNew ){
495       nNew = sqlite3MallocSize(pNew);
496       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
497     }
498     sqlite3_mutex_leave(mem0.mutex);
499   }else{
500     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
501   }
502   return pNew;
503 }
504 
505 /*
506 ** The public interface to sqlite3Realloc.  Make sure that the memory
507 ** subsystem is initialized prior to invoking sqliteRealloc.
508 */
509 void *sqlite3_realloc(void *pOld, int n){
510 #ifndef SQLITE_OMIT_AUTOINIT
511   if( sqlite3_initialize() ) return 0;
512 #endif
513   return sqlite3Realloc(pOld, n);
514 }
515 
516 
517 /*
518 ** Allocate and zero memory.
519 */
520 void *sqlite3MallocZero(int n){
521   void *p = sqlite3Malloc(n);
522   if( p ){
523     memset(p, 0, n);
524   }
525   return p;
526 }
527 
528 /*
529 ** Allocate and zero memory.  If the allocation fails, make
530 ** the mallocFailed flag in the connection pointer.
531 */
532 void *sqlite3DbMallocZero(sqlite3 *db, int n){
533   void *p = sqlite3DbMallocRaw(db, n);
534   if( p ){
535     memset(p, 0, n);
536   }
537   return p;
538 }
539 
540 /*
541 ** Allocate and zero memory.  If the allocation fails, make
542 ** the mallocFailed flag in the connection pointer.
543 **
544 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
545 ** failure on the same database connection) then always return 0.
546 ** Hence for a particular database connection, once malloc starts
547 ** failing, it fails consistently until mallocFailed is reset.
548 ** This is an important assumption.  There are many places in the
549 ** code that do things like this:
550 **
551 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
552 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
553 **         if( b ) a[10] = 9;
554 **
555 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
556 ** that all prior mallocs (ex: "a") worked too.
557 */
558 void *sqlite3DbMallocRaw(sqlite3 *db, int n){
559   void *p;
560   assert( db==0 || sqlite3_mutex_held(db->mutex) );
561 #ifndef SQLITE_OMIT_LOOKASIDE
562   if( db ){
563     LookasideSlot *pBuf;
564     if( db->mallocFailed ){
565       return 0;
566     }
567     if( db->lookaside.bEnabled && n<=db->lookaside.sz
568          && (pBuf = db->lookaside.pFree)!=0 ){
569       db->lookaside.pFree = pBuf->pNext;
570       db->lookaside.nOut++;
571       if( db->lookaside.nOut>db->lookaside.mxOut ){
572         db->lookaside.mxOut = db->lookaside.nOut;
573       }
574       return (void*)pBuf;
575     }
576   }
577 #else
578   if( db && db->mallocFailed ){
579     return 0;
580   }
581 #endif
582   p = sqlite3Malloc(n);
583   if( !p && db ){
584     db->mallocFailed = 1;
585   }
586   return p;
587 }
588 
589 /*
590 ** Resize the block of memory pointed to by p to n bytes. If the
591 ** resize fails, set the mallocFailed flag in the connection object.
592 */
593 void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
594   void *pNew = 0;
595   assert( db!=0 );
596   assert( sqlite3_mutex_held(db->mutex) );
597   if( db->mallocFailed==0 ){
598     if( p==0 ){
599       return sqlite3DbMallocRaw(db, n);
600     }
601     if( isLookaside(db, p) ){
602       if( n<=db->lookaside.sz ){
603         return p;
604       }
605       pNew = sqlite3DbMallocRaw(db, n);
606       if( pNew ){
607         memcpy(pNew, p, db->lookaside.sz);
608         sqlite3DbFree(db, p);
609       }
610     }else{
611       pNew = sqlite3_realloc(p, n);
612       if( !pNew ){
613         db->mallocFailed = 1;
614       }
615     }
616   }
617   return pNew;
618 }
619 
620 /*
621 ** Attempt to reallocate p.  If the reallocation fails, then free p
622 ** and set the mallocFailed flag in the database connection.
623 */
624 void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
625   void *pNew;
626   pNew = sqlite3DbRealloc(db, p, n);
627   if( !pNew ){
628     sqlite3DbFree(db, p);
629   }
630   return pNew;
631 }
632 
633 /*
634 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
635 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
636 ** is because when memory debugging is turned on, these two functions are
637 ** called via macros that record the current file and line number in the
638 ** ThreadData structure.
639 */
640 char *sqlite3DbStrDup(sqlite3 *db, const char *z){
641   char *zNew;
642   size_t n;
643   if( z==0 ){
644     return 0;
645   }
646   n = sqlite3Strlen30(z) + 1;
647   assert( (n&0x7fffffff)==n );
648   zNew = sqlite3DbMallocRaw(db, (int)n);
649   if( zNew ){
650     memcpy(zNew, z, n);
651   }
652   return zNew;
653 }
654 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
655   char *zNew;
656   if( z==0 ){
657     return 0;
658   }
659   assert( (n&0x7fffffff)==n );
660   zNew = sqlite3DbMallocRaw(db, n+1);
661   if( zNew ){
662     memcpy(zNew, z, n);
663     zNew[n] = 0;
664   }
665   return zNew;
666 }
667 
668 /*
669 ** Create a string from the zFromat argument and the va_list that follows.
670 ** Store the string in memory obtained from sqliteMalloc() and make *pz
671 ** point to that string.
672 */
673 void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
674   va_list ap;
675   char *z;
676 
677   va_start(ap, zFormat);
678   z = sqlite3VMPrintf(db, zFormat, ap);
679   va_end(ap);
680   sqlite3DbFree(db, *pz);
681   *pz = z;
682 }
683 
684 
685 /*
686 ** This function must be called before exiting any API function (i.e.
687 ** returning control to the user) that has called sqlite3_malloc or
688 ** sqlite3_realloc.
689 **
690 ** The returned value is normally a copy of the second argument to this
691 ** function. However, if a malloc() failure has occurred since the previous
692 ** invocation SQLITE_NOMEM is returned instead.
693 **
694 ** If the first argument, db, is not NULL and a malloc() error has occurred,
695 ** then the connection error-code (the value returned by sqlite3_errcode())
696 ** is set to SQLITE_NOMEM.
697 */
698 int sqlite3ApiExit(sqlite3* db, int rc){
699   /* If the db handle is not NULL, then we must hold the connection handle
700   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
701   ** is unsafe, as is the call to sqlite3Error().
702   */
703   assert( !db || sqlite3_mutex_held(db->mutex) );
704   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
705     sqlite3Error(db, SQLITE_NOMEM, 0);
706     db->mallocFailed = 0;
707     rc = SQLITE_NOMEM;
708   }
709   return rc & (db ? db->errMask : 0xff);
710 }
711