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