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