mem2.c

Go to the documentation of this file.
00001 /*
00002 ** 2007 August 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 **
00013 ** This file contains low-level memory allocation drivers for when
00014 ** SQLite will use the standard C-library malloc/realloc/free interface
00015 ** to obtain the memory it needs while adding lots of additional debugging
00016 ** information to each allocation in order to help detect and fix memory
00017 ** leaks and memory usage errors.
00018 **
00019 ** This file contains implementations of the low-level memory allocation
00020 ** routines specified in the sqlite3_mem_methods object.
00021 **
00022 ** $Id: mem2.c,v 1.40 2008/10/28 18:58:20 drh Exp $
00023 */
00024 #include "sqliteInt.h"
00025 
00026 /*
00027 ** This version of the memory allocator is used only if the
00028 ** SQLITE_MEMDEBUG macro is defined
00029 */
00030 #ifdef SQLITE_MEMDEBUG
00031 
00032 /*
00033 ** The backtrace functionality is only available with GLIBC
00034 */
00035 #ifdef __GLIBC__
00036   extern int backtrace(void**,int);
00037   extern void backtrace_symbols_fd(void*const*,int,int);
00038 #else
00039 # define backtrace(A,B) 1
00040 # define backtrace_symbols_fd(A,B,C)
00041 #endif
00042 #include <stdio.h>
00043 
00044 /*
00045 ** Each memory allocation looks like this:
00046 **
00047 **  ------------------------------------------------------------------------
00048 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
00049 **  ------------------------------------------------------------------------
00050 **
00051 ** The application code sees only a pointer to the allocation.  We have
00052 ** to back up from the allocation pointer to find the MemBlockHdr.  The
00053 ** MemBlockHdr tells us the size of the allocation and the number of
00054 ** backtrace pointers.  There is also a guard word at the end of the
00055 ** MemBlockHdr.
00056 */
00057 struct MemBlockHdr {
00058   i64 iSize;                          /* Size of this allocation */
00059   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
00060   char nBacktrace;                    /* Number of backtraces on this alloc */
00061   char nBacktraceSlots;               /* Available backtrace slots */
00062   short nTitle;                       /* Bytes of title; includes '\0' */
00063   int iForeGuard;                     /* Guard word for sanity */
00064 };
00065 
00066 /*
00067 ** Guard words
00068 */
00069 #define FOREGUARD 0x80F5E153
00070 #define REARGUARD 0xE4676B53
00071 
00072 /*
00073 ** Number of malloc size increments to track.
00074 */
00075 #define NCSIZE  1000
00076 
00077 /*
00078 ** All of the static variables used by this module are collected
00079 ** into a single structure named "mem".  This is to keep the
00080 ** static variables organized and to reduce namespace pollution
00081 ** when this module is combined with other in the amalgamation.
00082 */
00083 static struct {
00084   
00085   /*
00086   ** Mutex to control access to the memory allocation subsystem.
00087   */
00088   sqlite3_mutex *mutex;
00089 
00090   /*
00091   ** Head and tail of a linked list of all outstanding allocations
00092   */
00093   struct MemBlockHdr *pFirst;
00094   struct MemBlockHdr *pLast;
00095   
00096   /*
00097   ** The number of levels of backtrace to save in new allocations.
00098   */
00099   int nBacktrace;
00100   void (*xBacktrace)(int, int, void **);
00101 
00102   /*
00103   ** Title text to insert in front of each block
00104   */
00105   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
00106   char zTitle[100];  /* The title text */
00107 
00108   /* 
00109   ** sqlite3MallocDisallow() increments the following counter.
00110   ** sqlite3MallocAllow() decrements it.
00111   */
00112   int disallow; /* Do not allow memory allocation */
00113 
00114   /*
00115   ** Gather statistics on the sizes of memory allocations.
00116   ** nAlloc[i] is the number of allocation attempts of i*8
00117   ** bytes.  i==NCSIZE is the number of allocation attempts for
00118   ** sizes more than NCSIZE*8 bytes.
00119   */
00120   int nAlloc[NCSIZE];      /* Total number of allocations */
00121   int nCurrent[NCSIZE];    /* Current number of allocations */
00122   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
00123 
00124 } mem;
00125 
00126 
00127 /*
00128 ** Adjust memory usage statistics
00129 */
00130 static void adjustStats(int iSize, int increment){
00131   int i = ((iSize+7)&~7)/8;
00132   if( i>NCSIZE-1 ){
00133     i = NCSIZE - 1;
00134   }
00135   if( increment>0 ){
00136     mem.nAlloc[i]++;
00137     mem.nCurrent[i]++;
00138     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
00139       mem.mxCurrent[i] = mem.nCurrent[i];
00140     }
00141   }else{
00142     mem.nCurrent[i]--;
00143     assert( mem.nCurrent[i]>=0 );
00144   }
00145 }
00146 
00147 /*
00148 ** Given an allocation, find the MemBlockHdr for that allocation.
00149 **
00150 ** This routine checks the guards at either end of the allocation and
00151 ** if they are incorrect it asserts.
00152 */
00153 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
00154   struct MemBlockHdr *p;
00155   int *pInt;
00156   u8 *pU8;
00157   int nReserve;
00158 
00159   p = (struct MemBlockHdr*)pAllocation;
00160   p--;
00161   assert( p->iForeGuard==FOREGUARD );
00162   nReserve = (p->iSize+7)&~7;
00163   pInt = (int*)pAllocation;
00164   pU8 = (u8*)pAllocation;
00165   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
00166   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
00167   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
00168   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
00169   return p;
00170 }
00171 
00172 /*
00173 ** Return the number of bytes currently allocated at address p.
00174 */
00175 static int sqlite3MemSize(void *p){
00176   struct MemBlockHdr *pHdr;
00177   if( !p ){
00178     return 0;
00179   }
00180   pHdr = sqlite3MemsysGetHeader(p);
00181   return pHdr->iSize;
00182 }
00183 
00184 /*
00185 ** Initialize the memory allocation subsystem.
00186 */
00187 static int sqlite3MemInit(void *NotUsed){
00188   if( !sqlite3GlobalConfig.bMemstat ){
00189     /* If memory status is enabled, then the malloc.c wrapper will already
00190     ** hold the STATIC_MEM mutex when the routines here are invoked. */
00191     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
00192   }
00193   return SQLITE_OK;
00194 }
00195 
00196 /*
00197 ** Deinitialize the memory allocation subsystem.
00198 */
00199 static void sqlite3MemShutdown(void *NotUsed){
00200   mem.mutex = 0;
00201 }
00202 
00203 /*
00204 ** Round up a request size to the next valid allocation size.
00205 */
00206 static int sqlite3MemRoundup(int n){
00207   return (n+7) & ~7;
00208 }
00209 
00210 /*
00211 ** Allocate nByte bytes of memory.
00212 */
00213 static void *sqlite3MemMalloc(int nByte){
00214   struct MemBlockHdr *pHdr;
00215   void **pBt;
00216   char *z;
00217   int *pInt;
00218   void *p = 0;
00219   int totalSize;
00220   int nReserve;
00221   sqlite3_mutex_enter(mem.mutex);
00222   assert( mem.disallow==0 );
00223   nReserve = (nByte+7)&~7;
00224   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
00225                mem.nBacktrace*sizeof(void*) + mem.nTitle;
00226   p = malloc(totalSize);
00227   if( p ){
00228     z = p;
00229     pBt = (void**)&z[mem.nTitle];
00230     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
00231     pHdr->pNext = 0;
00232     pHdr->pPrev = mem.pLast;
00233     if( mem.pLast ){
00234       mem.pLast->pNext = pHdr;
00235     }else{
00236       mem.pFirst = pHdr;
00237     }
00238     mem.pLast = pHdr;
00239     pHdr->iForeGuard = FOREGUARD;
00240     pHdr->nBacktraceSlots = mem.nBacktrace;
00241     pHdr->nTitle = mem.nTitle;
00242     if( mem.nBacktrace ){
00243       void *aAddr[40];
00244       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
00245       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
00246       if( mem.xBacktrace ){
00247         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
00248       }
00249     }else{
00250       pHdr->nBacktrace = 0;
00251     }
00252     if( mem.nTitle ){
00253       memcpy(z, mem.zTitle, mem.nTitle);
00254     }
00255     pHdr->iSize = nByte;
00256     adjustStats(nByte, +1);
00257     pInt = (int*)&pHdr[1];
00258     pInt[nReserve/sizeof(int)] = REARGUARD;
00259     memset(pInt, 0x65, nReserve);
00260     p = (void*)pInt;
00261   }
00262   sqlite3_mutex_leave(mem.mutex);
00263   return p; 
00264 }
00265 
00266 /*
00267 ** Free memory.
00268 */
00269 static void sqlite3MemFree(void *pPrior){
00270   struct MemBlockHdr *pHdr;
00271   void **pBt;
00272   char *z;
00273   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
00274   pHdr = sqlite3MemsysGetHeader(pPrior);
00275   pBt = (void**)pHdr;
00276   pBt -= pHdr->nBacktraceSlots;
00277   sqlite3_mutex_enter(mem.mutex);
00278   if( pHdr->pPrev ){
00279     assert( pHdr->pPrev->pNext==pHdr );
00280     pHdr->pPrev->pNext = pHdr->pNext;
00281   }else{
00282     assert( mem.pFirst==pHdr );
00283     mem.pFirst = pHdr->pNext;
00284   }
00285   if( pHdr->pNext ){
00286     assert( pHdr->pNext->pPrev==pHdr );
00287     pHdr->pNext->pPrev = pHdr->pPrev;
00288   }else{
00289     assert( mem.pLast==pHdr );
00290     mem.pLast = pHdr->pPrev;
00291   }
00292   z = (char*)pBt;
00293   z -= pHdr->nTitle;
00294   adjustStats(pHdr->iSize, -1);
00295   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
00296                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
00297   free(z);
00298   sqlite3_mutex_leave(mem.mutex);  
00299 }
00300 
00301 /*
00302 ** Change the size of an existing memory allocation.
00303 **
00304 ** For this debugging implementation, we *always* make a copy of the
00305 ** allocation into a new place in memory.  In this way, if the 
00306 ** higher level code is using pointer to the old allocation, it is 
00307 ** much more likely to break and we are much more liking to find
00308 ** the error.
00309 */
00310 static void *sqlite3MemRealloc(void *pPrior, int nByte){
00311   struct MemBlockHdr *pOldHdr;
00312   void *pNew;
00313   assert( mem.disallow==0 );
00314   pOldHdr = sqlite3MemsysGetHeader(pPrior);
00315   pNew = sqlite3MemMalloc(nByte);
00316   if( pNew ){
00317     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
00318     if( nByte>pOldHdr->iSize ){
00319       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
00320     }
00321     sqlite3MemFree(pPrior);
00322   }
00323   return pNew;
00324 }
00325 
00326 /*
00327 ** Populate the low-level memory allocation function pointers in
00328 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
00329 */
00330 void sqlite3MemSetDefault(void){
00331   static const sqlite3_mem_methods defaultMethods = {
00332      sqlite3MemMalloc,
00333      sqlite3MemFree,
00334      sqlite3MemRealloc,
00335      sqlite3MemSize,
00336      sqlite3MemRoundup,
00337      sqlite3MemInit,
00338      sqlite3MemShutdown,
00339      0
00340   };
00341   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
00342 }
00343 
00344 /*
00345 ** Set the number of backtrace levels kept for each allocation.
00346 ** A value of zero turns off backtracing.  The number is always rounded
00347 ** up to a multiple of 2.
00348 */
00349 void sqlite3MemdebugBacktrace(int depth){
00350   if( depth<0 ){ depth = 0; }
00351   if( depth>20 ){ depth = 20; }
00352   depth = (depth+1)&0xfe;
00353   mem.nBacktrace = depth;
00354 }
00355 
00356 void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
00357   mem.xBacktrace = xBacktrace;
00358 }
00359 
00360 /*
00361 ** Set the title string for subsequent allocations.
00362 */
00363 void sqlite3MemdebugSettitle(const char *zTitle){
00364   int n = strlen(zTitle) + 1;
00365   sqlite3_mutex_enter(mem.mutex);
00366   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
00367   memcpy(mem.zTitle, zTitle, n);
00368   mem.zTitle[n] = 0;
00369   mem.nTitle = (n+7)&~7;
00370   sqlite3_mutex_leave(mem.mutex);
00371 }
00372 
00373 void sqlite3MemdebugSync(){
00374   struct MemBlockHdr *pHdr;
00375   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
00376     void **pBt = (void**)pHdr;
00377     pBt -= pHdr->nBacktraceSlots;
00378     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
00379   }
00380 }
00381 
00382 /*
00383 ** Open the file indicated and write a log of all unfreed memory 
00384 ** allocations into that log.
00385 */
00386 void sqlite3MemdebugDump(const char *zFilename){
00387   FILE *out;
00388   struct MemBlockHdr *pHdr;
00389   void **pBt;
00390   int i;
00391   out = fopen(zFilename, "w");
00392   if( out==0 ){
00393     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
00394                     zFilename);
00395     return;
00396   }
00397   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
00398     char *z = (char*)pHdr;
00399     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
00400     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
00401             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
00402     if( pHdr->nBacktrace ){
00403       fflush(out);
00404       pBt = (void**)pHdr;
00405       pBt -= pHdr->nBacktraceSlots;
00406       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
00407       fprintf(out, "\n");
00408     }
00409   }
00410   fprintf(out, "COUNTS:\n");
00411   for(i=0; i<NCSIZE-1; i++){
00412     if( mem.nAlloc[i] ){
00413       fprintf(out, "   %5d: %10d %10d %10d\n", 
00414             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
00415     }
00416   }
00417   if( mem.nAlloc[NCSIZE-1] ){
00418     fprintf(out, "   %5d: %10d %10d %10d\n",
00419              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
00420              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
00421   }
00422   fclose(out);
00423 }
00424 
00425 /*
00426 ** Return the number of times sqlite3MemMalloc() has been called.
00427 */
00428 int sqlite3MemdebugMallocCount(){
00429   int i;
00430   int nTotal = 0;
00431   for(i=0; i<NCSIZE; i++){
00432     nTotal += mem.nAlloc[i];
00433   }
00434   return nTotal;
00435 }
00436 
00437 
00438 #endif /* SQLITE_MEMDEBUG */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:55 2011 by Doxygen 1.6.1