xref: /sqlite-3.40.0/src/malloc.c (revision a408adc5)
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 ** Memory allocation functions used throughout sqlite.
13 **
14 **
15 ** $Id: malloc.c,v 1.2 2007/05/16 17:28:43 danielk1977 Exp $
16 */
17 #include "sqliteInt.h"
18 #include "os.h"
19 #include <stdarg.h>
20 #include <ctype.h>
21 
22 /*
23 ** MALLOC WRAPPER ARCHITECTURE
24 **
25 ** The sqlite code accesses dynamic memory allocation/deallocation by invoking
26 ** the following six APIs (which may be implemented as macros).
27 **
28 **     sqlite3Malloc()
29 **     sqlite3MallocRaw()
30 **     sqlite3Realloc()
31 **     sqlite3ReallocOrFree()
32 **     sqlite3Free()
33 **     sqlite3AllocSize()
34 **
35 ** The function sqlite3FreeX performs the same task as sqlite3Free and is
36 ** guaranteed to be a real function. The same holds for sqlite3MallocX
37 **
38 ** The above APIs are implemented in terms of the functions provided in the
39 ** operating-system interface. The OS interface is never accessed directly
40 ** by code outside of this file.
41 **
42 **     sqlite3OsMalloc()
43 **     sqlite3OsRealloc()
44 **     sqlite3OsFree()
45 **     sqlite3OsAllocationSize()
46 **
47 ** Functions sqlite3MallocRaw() and sqlite3Realloc() may invoke
48 ** sqlite3_release_memory() if a call to sqlite3OsMalloc() or
49 ** sqlite3OsRealloc() fails (or if the soft-heap-limit for the thread is
50 ** exceeded). Function sqlite3Malloc() usually invokes
51 ** sqlite3MallocRaw().
52 **
53 ** MALLOC TEST WRAPPER ARCHITECTURE
54 **
55 ** The test wrapper provides extra test facilities to ensure the library
56 ** does not leak memory and handles the failure of the underlying OS level
57 ** allocation system correctly. It is only present if the library is
58 ** compiled with the SQLITE_MEMDEBUG macro set.
59 **
60 **     * Guardposts to detect overwrites.
61 **     * Ability to cause a specific Malloc() or Realloc() to fail.
62 **     * Audit outstanding memory allocations (i.e check for leaks).
63 */
64 
65 #define MAX(x,y) ((x)>(y)?(x):(y))
66 
67 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
68 /*
69 ** Set the soft heap-size limit for the current thread. Passing a negative
70 ** value indicates no limit.
71 */
72 void sqlite3_soft_heap_limit(int n){
73   ThreadData *pTd = sqlite3ThreadData();
74   if( pTd ){
75     pTd->nSoftHeapLimit = n;
76   }
77   sqlite3ReleaseThreadData();
78 }
79 
80 /*
81 ** Release memory held by SQLite instances created by the current thread.
82 */
83 int sqlite3_release_memory(int n){
84   return sqlite3PagerReleaseMemory(n);
85 }
86 #else
87 /* If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, then define a version
88 ** of sqlite3_release_memory() to be used by other code in this file.
89 ** This is done for no better reason than to reduce the number of
90 ** pre-processor #ifndef statements.
91 */
92 #define sqlite3_release_memory(x) 0    /* 0 == no memory freed */
93 #endif
94 
95 #ifdef SQLITE_MEMDEBUG
96 /*--------------------------------------------------------------------------
97 ** Begin code for memory allocation system test layer.
98 **
99 ** Memory debugging is turned on by defining the SQLITE_MEMDEBUG macro.
100 **
101 ** SQLITE_MEMDEBUG==1    -> Fence-posting only (thread safe)
102 ** SQLITE_MEMDEBUG==2    -> Fence-posting + linked list of allocations (not ts)
103 ** SQLITE_MEMDEBUG==3    -> Above + backtraces (not thread safe, req. glibc)
104 */
105 
106 /* Figure out whether or not to store backtrace() information for each malloc.
107 ** The backtrace() function is only used if SQLITE_MEMDEBUG is set to 2 or
108 ** greater and glibc is in use. If we don't want to use backtrace(), then just
109 ** define it as an empty macro and set the amount of space reserved to 0.
110 */
111 #if defined(__GLIBC__) && SQLITE_MEMDEBUG>2
112   extern int backtrace(void **, int);
113   #define TESTALLOC_STACKSIZE 128
114   #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
115 #else
116   #define backtrace(x, y)
117   #define TESTALLOC_STACKSIZE 0
118   #define TESTALLOC_STACKFRAMES 0
119 #endif
120 
121 /*
122 ** Number of 32-bit guard words.  This should probably be a multiple of
123 ** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
124 ** to be 8-byte aligned.
125 */
126 #ifndef TESTALLOC_NGUARD
127 # define TESTALLOC_NGUARD 2
128 #endif
129 
130 /*
131 ** Size reserved for storing file-name along with each malloc()ed blob.
132 */
133 #define TESTALLOC_FILESIZE 64
134 
135 /*
136 ** Size reserved for storing the user string. Each time a Malloc() or Realloc()
137 ** call succeeds, up to TESTALLOC_USERSIZE bytes of the string pointed to by
138 ** sqlite3_malloc_id are stored along with the other test system metadata.
139 */
140 #define TESTALLOC_USERSIZE 64
141 const char *sqlite3_malloc_id = 0;
142 
143 /*
144 ** Blocks used by the test layer have the following format:
145 **
146 **        <sizeof(void *) pNext pointer>
147 **        <sizeof(void *) pPrev pointer>
148 **        <TESTALLOC_NGUARD 32-bit guard words>
149 **            <The application level allocation>
150 **        <TESTALLOC_NGUARD 32-bit guard words>
151 **        <32-bit line number>
152 **        <TESTALLOC_FILESIZE bytes containing null-terminated file name>
153 **        <TESTALLOC_STACKSIZE bytes of backtrace() output>
154 */
155 
156 #define TESTALLOC_OFFSET_GUARD1(p)    (sizeof(void *) * 2)
157 #define TESTALLOC_OFFSET_DATA(p) ( \
158   TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
159 )
160 #define TESTALLOC_OFFSET_GUARD2(p) ( \
161   TESTALLOC_OFFSET_DATA(p) + sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
162 )
163 #define TESTALLOC_OFFSET_LINENUMBER(p) ( \
164   TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
165 )
166 #define TESTALLOC_OFFSET_FILENAME(p) ( \
167   TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
168 )
169 #define TESTALLOC_OFFSET_USER(p) ( \
170   TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
171 )
172 #define TESTALLOC_OFFSET_STACK(p) ( \
173   TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
174   (TESTALLOC_OFFSET_USER(p) % 8) \
175 )
176 
177 #define TESTALLOC_OVERHEAD ( \
178   sizeof(void *)*2 +                   /* pPrev and pNext pointers */   \
179   TESTALLOC_NGUARD*sizeof(u32)*2 +              /* Guard words */       \
180   sizeof(u32) + TESTALLOC_FILESIZE +   /* File and line number */       \
181   TESTALLOC_USERSIZE +                 /* User string */                \
182   TESTALLOC_STACKSIZE                  /* backtrace() stack */          \
183 )
184 
185 
186 /*
187 ** For keeping track of the number of mallocs and frees.   This
188 ** is used to check for memory leaks.  The iMallocFail and iMallocReset
189 ** values are used to simulate malloc() failures during testing in
190 ** order to verify that the library correctly handles an out-of-memory
191 ** condition.
192 */
193 int sqlite3_nMalloc;         /* Number of sqliteMalloc() calls */
194 int sqlite3_nFree;           /* Number of sqliteFree() calls */
195 int sqlite3_memUsed;         /* TODO Total memory obtained from malloc */
196 int sqlite3_memMax;          /* TODO Mem usage high-water mark */
197 int sqlite3_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
198 int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
199 
200 void *sqlite3_pFirst = 0;         /* Pointer to linked list of allocations */
201 int sqlite3_nMaxAlloc = 0;        /* High water mark of ThreadData.nAlloc */
202 int sqlite3_mallocDisallowed = 0; /* assert() in sqlite3Malloc() if set */
203 int sqlite3_isFail = 0;           /* True if all malloc calls should fail */
204 const char *sqlite3_zFile = 0;    /* Filename to associate debug info with */
205 int sqlite3_iLine = 0;            /* Line number for debug info */
206 
207 /*
208 ** Check for a simulated memory allocation failure.  Return true if
209 ** the failure should be simulated.  Return false to proceed as normal.
210 */
211 int sqlite3TestMallocFail(){
212   if( sqlite3_isFail ){
213     return 1;
214   }
215   if( sqlite3_iMallocFail>=0 ){
216     sqlite3_iMallocFail--;
217     if( sqlite3_iMallocFail==0 ){
218       sqlite3_iMallocFail = sqlite3_iMallocReset;
219       sqlite3_isFail = 1;
220       return 1;
221     }
222   }
223   return 0;
224 }
225 
226 /*
227 ** The argument is a pointer returned by sqlite3OsMalloc() or xRealloc().
228 ** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
229 ** values set by the applyGuards() function.
230 */
231 static void checkGuards(u32 *p)
232 {
233   int i;
234   char *zAlloc = (char *)p;
235   char *z;
236 
237   /* First set of guard words */
238   z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
239   for(i=0; i<TESTALLOC_NGUARD; i++){
240     assert(((u32 *)z)[i]==0xdead1122);
241   }
242 
243   /* Second set of guard words */
244   z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
245   for(i=0; i<TESTALLOC_NGUARD; i++){
246     u32 guard = 0;
247     memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
248     assert(guard==0xdead3344);
249   }
250 }
251 
252 /*
253 ** The argument is a pointer returned by sqlite3OsMalloc() or Realloc(). The
254 ** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as
255 ** guard-posts.
256 */
257 static void applyGuards(u32 *p)
258 {
259   int i;
260   char *z;
261   char *zAlloc = (char *)p;
262 
263   /* First set of guard words */
264   z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
265   for(i=0; i<TESTALLOC_NGUARD; i++){
266     ((u32 *)z)[i] = 0xdead1122;
267   }
268 
269   /* Second set of guard words */
270   z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
271   for(i=0; i<TESTALLOC_NGUARD; i++){
272     static const int guard = 0xdead3344;
273     memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
274   }
275 
276   /* Line number */
277   z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)];             /* Guard words */
278   z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
279   memcpy(z, &sqlite3_iLine, sizeof(u32));
280 
281   /* File name */
282   z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
283   strncpy(z, sqlite3_zFile, TESTALLOC_FILESIZE);
284   z[TESTALLOC_FILESIZE - 1] = '\0';
285 
286   /* User string */
287   z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
288   z[0] = 0;
289   if( sqlite3_malloc_id ){
290     strncpy(z, sqlite3_malloc_id, TESTALLOC_USERSIZE);
291     z[TESTALLOC_USERSIZE-1] = 0;
292   }
293 
294   /* backtrace() stack */
295   z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
296   backtrace((void **)z, TESTALLOC_STACKFRAMES);
297 
298   /* Sanity check to make sure checkGuards() is working */
299   checkGuards(p);
300 }
301 
302 /*
303 ** The argument is a malloc()ed pointer as returned by the test-wrapper.
304 ** Return a pointer to the Os level allocation.
305 */
306 static void *getOsPointer(void *p)
307 {
308   char *z = (char *)p;
309   return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
310 }
311 
312 
313 #if SQLITE_MEMDEBUG>1
314 /*
315 ** The argument points to an Os level allocation. Link it into the threads list
316 ** of allocations.
317 */
318 static void linkAlloc(void *p){
319   void **pp = (void **)p;
320   pp[0] = 0;
321   pp[1] = sqlite3_pFirst;
322   if( sqlite3_pFirst ){
323     ((void **)sqlite3_pFirst)[0] = p;
324   }
325   sqlite3_pFirst = p;
326 }
327 
328 /*
329 ** The argument points to an Os level allocation. Unlinke it from the threads
330 ** list of allocations.
331 */
332 static void unlinkAlloc(void *p)
333 {
334   void **pp = (void **)p;
335   if( p==sqlite3_pFirst ){
336     assert(!pp[0]);
337     assert(!pp[1] || ((void **)(pp[1]))[0]==p);
338     sqlite3_pFirst = pp[1];
339     if( sqlite3_pFirst ){
340       ((void **)sqlite3_pFirst)[0] = 0;
341     }
342   }else{
343     void **pprev = pp[0];
344     void **pnext = pp[1];
345     assert(pprev);
346     assert(pprev[1]==p);
347     pprev[1] = (void *)pnext;
348     if( pnext ){
349       assert(pnext[0]==p);
350       pnext[0] = (void *)pprev;
351     }
352   }
353 }
354 
355 /*
356 ** Pointer p is a pointer to an OS level allocation that has just been
357 ** realloc()ed. Set the list pointers that point to this entry to it's new
358 ** location.
359 */
360 static void relinkAlloc(void *p)
361 {
362   void **pp = (void **)p;
363   if( pp[0] ){
364     ((void **)(pp[0]))[1] = p;
365   }else{
366     sqlite3_pFirst = p;
367   }
368   if( pp[1] ){
369     ((void **)(pp[1]))[0] = p;
370   }
371 }
372 #else
373 #define linkAlloc(x)
374 #define relinkAlloc(x)
375 #define unlinkAlloc(x)
376 #endif
377 
378 /*
379 ** This function sets the result of the Tcl interpreter passed as an argument
380 ** to a list containing an entry for each currently outstanding call made to
381 ** sqliteMalloc and friends by the current thread. Each list entry is itself a
382 ** list, consisting of the following (in order):
383 **
384 **     * The number of bytes allocated
385 **     * The __FILE__ macro at the time of the sqliteMalloc() call.
386 **     * The __LINE__ macro ...
387 **     * The value of the sqlite3_malloc_id variable ...
388 **     * The output of backtrace() (if available) ...
389 **
390 ** Todo: We could have a version of this function that outputs to stdout,
391 ** to debug memory leaks when Tcl is not available.
392 */
393 #if defined(TCLSH) && defined(SQLITE_DEBUG) && SQLITE_MEMDEBUG>1
394 #include <tcl.h>
395 int sqlite3OutstandingMallocs(Tcl_Interp *interp){
396   void *p;
397   Tcl_Obj *pRes = Tcl_NewObj();
398   Tcl_IncrRefCount(pRes);
399 
400 
401   for(p=sqlite3_pFirst; p; p=((void **)p)[1]){
402     Tcl_Obj *pEntry = Tcl_NewObj();
403     Tcl_Obj *pStack = Tcl_NewObj();
404     char *z;
405     u32 iLine;
406     int nBytes = sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
407     char *zAlloc = (char *)p;
408     int i;
409 
410     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));
411 
412     z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
413     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
414 
415     z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
416     memcpy(&iLine, z, sizeof(u32));
417     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));
418 
419     z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
420     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
421 
422     z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
423     for(i=0; i<TESTALLOC_STACKFRAMES; i++){
424       char zHex[128];
425       sqlite3_snprintf(sizeof(zHex), zHex, "%p", ((void **)z)[i]);
426       Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
427     }
428 
429     Tcl_ListObjAppendElement(0, pEntry, pStack);
430     Tcl_ListObjAppendElement(0, pRes, pEntry);
431   }
432 
433   Tcl_ResetResult(interp);
434   Tcl_SetObjResult(interp, pRes);
435   Tcl_DecrRefCount(pRes);
436   return TCL_OK;
437 }
438 #endif
439 
440 /*
441 ** This is the test layer's wrapper around sqlite3OsMalloc().
442 */
443 static void * OSMALLOC(int n){
444   sqlite3OsEnterMutex();
445 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
446   sqlite3_nMaxAlloc =
447       MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
448 #endif
449   assert( !sqlite3_mallocDisallowed );
450   if( !sqlite3TestMallocFail() ){
451     u32 *p;
452     p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
453     assert(p);
454     sqlite3_nMalloc++;
455     applyGuards(p);
456     linkAlloc(p);
457     sqlite3OsLeaveMutex();
458     return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
459   }
460   sqlite3OsLeaveMutex();
461   return 0;
462 }
463 
464 static int OSSIZEOF(void *p){
465   if( p ){
466     u32 *pOs = (u32 *)getOsPointer(p);
467     return sqlite3OsAllocationSize(pOs) - TESTALLOC_OVERHEAD;
468   }
469   return 0;
470 }
471 
472 /*
473 ** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
474 ** pointer to the space allocated for the application to use.
475 */
476 static void OSFREE(void *pFree){
477   u32 *p;         /* Pointer to the OS-layer allocation */
478   sqlite3OsEnterMutex();
479   p = (u32 *)getOsPointer(pFree);
480   checkGuards(p);
481   unlinkAlloc(p);
482   memset(pFree, 0x55, OSSIZEOF(pFree));
483   sqlite3OsFree(p);
484   sqlite3_nFree++;
485   sqlite3OsLeaveMutex();
486 }
487 
488 /*
489 ** This is the test layer's wrapper around sqlite3OsRealloc().
490 */
491 static void * OSREALLOC(void *pRealloc, int n){
492 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
493   sqlite3_nMaxAlloc =
494       MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
495 #endif
496   assert( !sqlite3_mallocDisallowed );
497   if( !sqlite3TestMallocFail() ){
498     u32 *p = (u32 *)getOsPointer(pRealloc);
499     checkGuards(p);
500     p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
501     applyGuards(p);
502     relinkAlloc(p);
503     return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
504   }
505   return 0;
506 }
507 
508 static void OSMALLOC_FAILED(){
509   sqlite3_isFail = 0;
510 }
511 
512 #else
513 /* Define macros to call the sqlite3OsXXX interface directly if
514 ** the SQLITE_MEMDEBUG macro is not defined.
515 */
516 #define OSMALLOC(x)        sqlite3OsMalloc(x)
517 #define OSREALLOC(x,y)     sqlite3OsRealloc(x,y)
518 #define OSFREE(x)          sqlite3OsFree(x)
519 #define OSSIZEOF(x)        sqlite3OsAllocationSize(x)
520 #define OSMALLOC_FAILED()
521 
522 #endif  /* SQLITE_MEMDEBUG */
523 /*
524 ** End code for memory allocation system test layer.
525 **--------------------------------------------------------------------------*/
526 
527 /*
528 ** This routine is called when we are about to allocate n additional bytes
529 ** of memory.  If the new allocation will put is over the soft allocation
530 ** limit, then invoke sqlite3_release_memory() to try to release some
531 ** memory before continuing with the allocation.
532 **
533 ** This routine also makes sure that the thread-specific-data (TSD) has
534 ** be allocated.  If it has not and can not be allocated, then return
535 ** false.  The updateMemoryUsedCount() routine below will deallocate
536 ** the TSD if it ought to be.
537 **
538 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
539 ** a no-op
540 */
541 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
542 static int enforceSoftLimit(int n){
543   ThreadData *pTsd = sqlite3ThreadData();
544   if( pTsd==0 ){
545     return 0;
546   }
547   assert( pTsd->nAlloc>=0 );
548   if( n>0 && pTsd->nSoftHeapLimit>0 ){
549     while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && sqlite3_release_memory(n) ){}
550   }
551   return 1;
552 }
553 #else
554 # define enforceSoftLimit(X)  1
555 #endif
556 
557 /*
558 ** Update the count of total outstanding memory that is held in
559 ** thread-specific-data (TSD).  If after this update the TSD is
560 ** no longer being used, then deallocate it.
561 **
562 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
563 ** a no-op
564 */
565 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
566 static void updateMemoryUsedCount(int n){
567   ThreadData *pTsd = sqlite3ThreadData();
568   if( pTsd ){
569     pTsd->nAlloc += n;
570     assert( pTsd->nAlloc>=0 );
571     if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
572       sqlite3ReleaseThreadData();
573     }
574   }
575 }
576 #else
577 #define updateMemoryUsedCount(x)  /* no-op */
578 #endif
579 
580 /*
581 ** Allocate and return N bytes of uninitialised memory by calling
582 ** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory
583 ** by calling sqlite3_release_memory().
584 */
585 void *sqlite3MallocRaw(int n, int doMemManage){
586   void *p = 0;
587   if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
588     while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
589     if( !p ){
590       sqlite3FailedMalloc();
591       OSMALLOC_FAILED();
592     }else if( doMemManage ){
593       updateMemoryUsedCount(OSSIZEOF(p));
594     }
595   }
596   return p;
597 }
598 
599 /*
600 ** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
601 ** pointer to the new allocation is returned.  If the Realloc() call fails,
602 ** attempt to free memory by calling sqlite3_release_memory().
603 */
604 void *sqlite3Realloc(void *p, int n){
605   if( sqlite3MallocFailed() ){
606     return 0;
607   }
608 
609   if( !p ){
610     return sqlite3Malloc(n, 1);
611   }else{
612     void *np = 0;
613 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
614     int origSize = OSSIZEOF(p);
615 #endif
616     if( enforceSoftLimit(n - origSize) ){
617       while( (np = OSREALLOC(p, n))==0 && sqlite3_release_memory(n) ){}
618       if( !np ){
619         sqlite3FailedMalloc();
620         OSMALLOC_FAILED();
621       }else{
622         updateMemoryUsedCount(OSSIZEOF(np) - origSize);
623       }
624     }
625     return np;
626   }
627 }
628 
629 /*
630 ** Free the memory pointed to by p. p must be either a NULL pointer or a
631 ** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
632 */
633 void sqlite3FreeX(void *p){
634   if( p ){
635     updateMemoryUsedCount(0 - OSSIZEOF(p));
636     OSFREE(p);
637   }
638 }
639 
640 /*
641 ** A version of sqliteMalloc() that is always a function, not a macro.
642 ** Currently, this is used only to alloc to allocate the parser engine.
643 */
644 void *sqlite3MallocX(int n){
645   return sqliteMalloc(n);
646 }
647 
648 /*
649 ** sqlite3Malloc
650 ** sqlite3ReallocOrFree
651 **
652 ** These two are implemented as wrappers around sqlite3MallocRaw(),
653 ** sqlite3Realloc() and sqlite3Free().
654 */
655 void *sqlite3Malloc(int n, int doMemManage){
656   void *p = sqlite3MallocRaw(n, doMemManage);
657   if( p ){
658     memset(p, 0, n);
659   }
660   return p;
661 }
662 void *sqlite3ReallocOrFree(void *p, int n){
663   void *pNew;
664   pNew = sqlite3Realloc(p, n);
665   if( !pNew ){
666     sqlite3FreeX(p);
667   }
668   return pNew;
669 }
670 
671 /*
672 ** sqlite3ThreadSafeMalloc() and sqlite3ThreadSafeFree() are used in those
673 ** rare scenarios where sqlite may allocate memory in one thread and free
674 ** it in another. They are exactly the same as sqlite3Malloc() and
675 ** sqlite3Free() except that:
676 **
677 **   * The allocated memory is not included in any calculations with
678 **     respect to the soft-heap-limit, and
679 **
680 **   * sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
681 **     not sqlite3Free(). Calling sqlite3Free() on memory obtained from
682 **     ThreadSafeMalloc() will cause an error somewhere down the line.
683 */
684 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
685 void *sqlite3ThreadSafeMalloc(int n){
686   (void)ENTER_MALLOC;
687   return sqlite3Malloc(n, 0);
688 }
689 void sqlite3ThreadSafeFree(void *p){
690   (void)ENTER_MALLOC;
691   if( p ){
692     OSFREE(p);
693   }
694 }
695 #endif
696 
697 
698 /*
699 ** Return the number of bytes allocated at location p. p must be either
700 ** a NULL pointer (in which case 0 is returned) or a pointer returned by
701 ** sqlite3Malloc(), sqlite3Realloc() or sqlite3ReallocOrFree().
702 **
703 ** The number of bytes allocated does not include any overhead inserted by
704 ** any malloc() wrapper functions that may be called. So the value returned
705 ** is the number of bytes that were available to SQLite using pointer p,
706 ** regardless of how much memory was actually allocated.
707 */
708 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
709 int sqlite3AllocSize(void *p){
710   return OSSIZEOF(p);
711 }
712 #endif
713 
714 /*
715 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
716 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
717 ** is because when memory debugging is turned on, these two functions are
718 ** called via macros that record the current file and line number in the
719 ** ThreadData structure.
720 */
721 char *sqlite3StrDup(const char *z){
722   char *zNew;
723   int n;
724   if( z==0 ) return 0;
725   n = strlen(z)+1;
726   zNew = sqlite3MallocRaw(n, 1);
727   if( zNew ) memcpy(zNew, z, n);
728   return zNew;
729 }
730 char *sqlite3StrNDup(const char *z, int n){
731   char *zNew;
732   if( z==0 ) return 0;
733   zNew = sqlite3MallocRaw(n+1, 1);
734   if( zNew ){
735     memcpy(zNew, z, n);
736     zNew[n] = 0;
737   }
738   return zNew;
739 }
740 
741 /*
742 ** Create a string from the 2nd and subsequent arguments (up to the
743 ** first NULL argument), store the string in memory obtained from
744 ** sqliteMalloc() and make the pointer indicated by the 1st argument
745 ** point to that string.  The 1st argument must either be NULL or
746 ** point to memory obtained from sqliteMalloc().
747 */
748 void sqlite3SetString(char **pz, ...){
749   va_list ap;
750   int nByte;
751   const char *z;
752   char *zResult;
753 
754   assert( pz!=0 );
755   nByte = 1;
756   va_start(ap, pz);
757   while( (z = va_arg(ap, const char*))!=0 ){
758     nByte += strlen(z);
759   }
760   va_end(ap);
761   sqliteFree(*pz);
762   *pz = zResult = sqliteMallocRaw( nByte );
763   if( zResult==0 ){
764     return;
765   }
766   *zResult = 0;
767   va_start(ap, pz);
768   while( (z = va_arg(ap, const char*))!=0 ){
769     int n = strlen(z);
770     memcpy(zResult, z, n);
771     zResult += n;
772   }
773   zResult[0] = 0;
774   va_end(ap);
775 }
776 
777 
778 /*
779 ** This function must be called before exiting any API function (i.e.
780 ** returning control to the user) that has called sqlite3Malloc or
781 ** sqlite3Realloc.
782 **
783 ** The returned value is normally a copy of the second argument to this
784 ** function. However, if a malloc() failure has occured since the previous
785 ** invocation SQLITE_NOMEM is returned instead.
786 **
787 ** If the first argument, db, is not NULL and a malloc() error has occured,
788 ** then the connection error-code (the value returned by sqlite3_errcode())
789 ** is set to SQLITE_NOMEM.
790 */
791 int sqlite3_mallocHasFailed = 0;
792 int sqlite3ApiExit(sqlite3* db, int rc){
793   if( sqlite3MallocFailed() ){
794     sqlite3_mallocHasFailed = 0;
795     sqlite3OsLeaveMutex();
796     sqlite3Error(db, SQLITE_NOMEM, 0);
797     rc = SQLITE_NOMEM;
798   }
799   return rc & (db ? db->errMask : 0xff);
800 }
801 
802 /*
803 ** Set the "malloc has failed" condition to true for this thread.
804 */
805 void sqlite3FailedMalloc(){
806   if( !sqlite3MallocFailed() ){
807     sqlite3OsEnterMutex();
808     assert( sqlite3_mallocHasFailed==0 );
809     sqlite3_mallocHasFailed = 1;
810   }
811 }
812 
813 #ifdef SQLITE_MEMDEBUG
814 /*
815 ** This function sets a flag in the thread-specific-data structure that will
816 ** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
817 */
818 void sqlite3MallocDisallow(){
819   assert( sqlite3_mallocDisallowed>=0 );
820   sqlite3_mallocDisallowed++;
821 }
822 
823 /*
824 ** This function clears the flag set in the thread-specific-data structure set
825 ** by sqlite3MallocDisallow().
826 */
827 void sqlite3MallocAllow(){
828   assert( sqlite3_mallocDisallowed>0 );
829   sqlite3_mallocDisallowed--;
830 }
831 #endif
832