1 /* 2 ** 2007 August 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 ** This file contains low-level memory allocation drivers for when 14 ** SQLite will use the standard C-library malloc/realloc/free interface 15 ** to obtain the memory it needs while adding lots of additional debugging 16 ** information to each allocation in order to help detect and fix memory 17 ** leaks and memory usage errors. 18 ** 19 ** This file contains implementations of the low-level memory allocation 20 ** routines specified in the sqlite3_mem_methods object. 21 ** 22 ** $Id: mem2.c,v 1.42 2008/12/10 19:26:24 drh Exp $ 23 */ 24 #include "sqliteInt.h" 25 26 /* 27 ** This version of the memory allocator is used only if the 28 ** SQLITE_MEMDEBUG macro is defined 29 */ 30 #ifdef SQLITE_MEMDEBUG 31 32 /* 33 ** The backtrace functionality is only available with GLIBC 34 */ 35 #ifdef __GLIBC__ 36 extern int backtrace(void**,int); 37 extern void backtrace_symbols_fd(void*const*,int,int); 38 #else 39 # define backtrace(A,B) 1 40 # define backtrace_symbols_fd(A,B,C) 41 #endif 42 #include <stdio.h> 43 44 /* 45 ** Each memory allocation looks like this: 46 ** 47 ** ------------------------------------------------------------------------ 48 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | 49 ** ------------------------------------------------------------------------ 50 ** 51 ** The application code sees only a pointer to the allocation. We have 52 ** to back up from the allocation pointer to find the MemBlockHdr. The 53 ** MemBlockHdr tells us the size of the allocation and the number of 54 ** backtrace pointers. There is also a guard word at the end of the 55 ** MemBlockHdr. 56 */ 57 struct MemBlockHdr { 58 i64 iSize; /* Size of this allocation */ 59 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ 60 char nBacktrace; /* Number of backtraces on this alloc */ 61 char nBacktraceSlots; /* Available backtrace slots */ 62 short nTitle; /* Bytes of title; includes '\0' */ 63 int iForeGuard; /* Guard word for sanity */ 64 }; 65 66 /* 67 ** Guard words 68 */ 69 #define FOREGUARD 0x80F5E153 70 #define REARGUARD 0xE4676B53 71 72 /* 73 ** Number of malloc size increments to track. 74 */ 75 #define NCSIZE 1000 76 77 /* 78 ** All of the static variables used by this module are collected 79 ** into a single structure named "mem". This is to keep the 80 ** static variables organized and to reduce namespace pollution 81 ** when this module is combined with other in the amalgamation. 82 */ 83 static struct { 84 85 /* 86 ** Mutex to control access to the memory allocation subsystem. 87 */ 88 sqlite3_mutex *mutex; 89 90 /* 91 ** Head and tail of a linked list of all outstanding allocations 92 */ 93 struct MemBlockHdr *pFirst; 94 struct MemBlockHdr *pLast; 95 96 /* 97 ** The number of levels of backtrace to save in new allocations. 98 */ 99 int nBacktrace; 100 void (*xBacktrace)(int, int, void **); 101 102 /* 103 ** Title text to insert in front of each block 104 */ 105 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ 106 char zTitle[100]; /* The title text */ 107 108 /* 109 ** sqlite3MallocDisallow() increments the following counter. 110 ** sqlite3MallocAllow() decrements it. 111 */ 112 int disallow; /* Do not allow memory allocation */ 113 114 /* 115 ** Gather statistics on the sizes of memory allocations. 116 ** nAlloc[i] is the number of allocation attempts of i*8 117 ** bytes. i==NCSIZE is the number of allocation attempts for 118 ** sizes more than NCSIZE*8 bytes. 119 */ 120 int nAlloc[NCSIZE]; /* Total number of allocations */ 121 int nCurrent[NCSIZE]; /* Current number of allocations */ 122 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ 123 124 } mem; 125 126 127 /* 128 ** Adjust memory usage statistics 129 */ 130 static void adjustStats(int iSize, int increment){ 131 int i = ((iSize+7)&~7)/8; 132 if( i>NCSIZE-1 ){ 133 i = NCSIZE - 1; 134 } 135 if( increment>0 ){ 136 mem.nAlloc[i]++; 137 mem.nCurrent[i]++; 138 if( mem.nCurrent[i]>mem.mxCurrent[i] ){ 139 mem.mxCurrent[i] = mem.nCurrent[i]; 140 } 141 }else{ 142 mem.nCurrent[i]--; 143 assert( mem.nCurrent[i]>=0 ); 144 } 145 } 146 147 /* 148 ** Given an allocation, find the MemBlockHdr for that allocation. 149 ** 150 ** This routine checks the guards at either end of the allocation and 151 ** if they are incorrect it asserts. 152 */ 153 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ 154 struct MemBlockHdr *p; 155 int *pInt; 156 u8 *pU8; 157 int nReserve; 158 159 p = (struct MemBlockHdr*)pAllocation; 160 p--; 161 assert( p->iForeGuard==(int)FOREGUARD ); 162 nReserve = (p->iSize+7)&~7; 163 pInt = (int*)pAllocation; 164 pU8 = (u8*)pAllocation; 165 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); 166 assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 ); 167 assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 ); 168 assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 ); 169 return p; 170 } 171 172 /* 173 ** Return the number of bytes currently allocated at address p. 174 */ 175 static int sqlite3MemSize(void *p){ 176 struct MemBlockHdr *pHdr; 177 if( !p ){ 178 return 0; 179 } 180 pHdr = sqlite3MemsysGetHeader(p); 181 return pHdr->iSize; 182 } 183 184 /* 185 ** Initialize the memory allocation subsystem. 186 */ 187 static int sqlite3MemInit(void *NotUsed){ 188 UNUSED_PARAMETER(NotUsed); 189 if( !sqlite3GlobalConfig.bMemstat ){ 190 /* If memory status is enabled, then the malloc.c wrapper will already 191 ** hold the STATIC_MEM mutex when the routines here are invoked. */ 192 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); 193 } 194 return SQLITE_OK; 195 } 196 197 /* 198 ** Deinitialize the memory allocation subsystem. 199 */ 200 static void sqlite3MemShutdown(void *NotUsed){ 201 UNUSED_PARAMETER(NotUsed); 202 mem.mutex = 0; 203 } 204 205 /* 206 ** Round up a request size to the next valid allocation size. 207 */ 208 static int sqlite3MemRoundup(int n){ 209 return (n+7) & ~7; 210 } 211 212 /* 213 ** Allocate nByte bytes of memory. 214 */ 215 static void *sqlite3MemMalloc(int nByte){ 216 struct MemBlockHdr *pHdr; 217 void **pBt; 218 char *z; 219 int *pInt; 220 void *p = 0; 221 int totalSize; 222 int nReserve; 223 sqlite3_mutex_enter(mem.mutex); 224 assert( mem.disallow==0 ); 225 nReserve = (nByte+7)&~7; 226 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + 227 mem.nBacktrace*sizeof(void*) + mem.nTitle; 228 p = malloc(totalSize); 229 if( p ){ 230 z = p; 231 pBt = (void**)&z[mem.nTitle]; 232 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; 233 pHdr->pNext = 0; 234 pHdr->pPrev = mem.pLast; 235 if( mem.pLast ){ 236 mem.pLast->pNext = pHdr; 237 }else{ 238 mem.pFirst = pHdr; 239 } 240 mem.pLast = pHdr; 241 pHdr->iForeGuard = FOREGUARD; 242 pHdr->nBacktraceSlots = mem.nBacktrace; 243 pHdr->nTitle = mem.nTitle; 244 if( mem.nBacktrace ){ 245 void *aAddr[40]; 246 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; 247 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); 248 if( mem.xBacktrace ){ 249 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); 250 } 251 }else{ 252 pHdr->nBacktrace = 0; 253 } 254 if( mem.nTitle ){ 255 memcpy(z, mem.zTitle, mem.nTitle); 256 } 257 pHdr->iSize = nByte; 258 adjustStats(nByte, +1); 259 pInt = (int*)&pHdr[1]; 260 pInt[nReserve/sizeof(int)] = REARGUARD; 261 memset(pInt, 0x65, nReserve); 262 p = (void*)pInt; 263 } 264 sqlite3_mutex_leave(mem.mutex); 265 return p; 266 } 267 268 /* 269 ** Free memory. 270 */ 271 static void sqlite3MemFree(void *pPrior){ 272 struct MemBlockHdr *pHdr; 273 void **pBt; 274 char *z; 275 assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 ); 276 pHdr = sqlite3MemsysGetHeader(pPrior); 277 pBt = (void**)pHdr; 278 pBt -= pHdr->nBacktraceSlots; 279 sqlite3_mutex_enter(mem.mutex); 280 if( pHdr->pPrev ){ 281 assert( pHdr->pPrev->pNext==pHdr ); 282 pHdr->pPrev->pNext = pHdr->pNext; 283 }else{ 284 assert( mem.pFirst==pHdr ); 285 mem.pFirst = pHdr->pNext; 286 } 287 if( pHdr->pNext ){ 288 assert( pHdr->pNext->pPrev==pHdr ); 289 pHdr->pNext->pPrev = pHdr->pPrev; 290 }else{ 291 assert( mem.pLast==pHdr ); 292 mem.pLast = pHdr->pPrev; 293 } 294 z = (char*)pBt; 295 z -= pHdr->nTitle; 296 adjustStats(pHdr->iSize, -1); 297 memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + 298 pHdr->iSize + sizeof(int) + pHdr->nTitle); 299 free(z); 300 sqlite3_mutex_leave(mem.mutex); 301 } 302 303 /* 304 ** Change the size of an existing memory allocation. 305 ** 306 ** For this debugging implementation, we *always* make a copy of the 307 ** allocation into a new place in memory. In this way, if the 308 ** higher level code is using pointer to the old allocation, it is 309 ** much more likely to break and we are much more liking to find 310 ** the error. 311 */ 312 static void *sqlite3MemRealloc(void *pPrior, int nByte){ 313 struct MemBlockHdr *pOldHdr; 314 void *pNew; 315 assert( mem.disallow==0 ); 316 pOldHdr = sqlite3MemsysGetHeader(pPrior); 317 pNew = sqlite3MemMalloc(nByte); 318 if( pNew ){ 319 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize); 320 if( nByte>pOldHdr->iSize ){ 321 memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize); 322 } 323 sqlite3MemFree(pPrior); 324 } 325 return pNew; 326 } 327 328 /* 329 ** Populate the low-level memory allocation function pointers in 330 ** sqlite3GlobalConfig.m with pointers to the routines in this file. 331 */ 332 void sqlite3MemSetDefault(void){ 333 static const sqlite3_mem_methods defaultMethods = { 334 sqlite3MemMalloc, 335 sqlite3MemFree, 336 sqlite3MemRealloc, 337 sqlite3MemSize, 338 sqlite3MemRoundup, 339 sqlite3MemInit, 340 sqlite3MemShutdown, 341 0 342 }; 343 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); 344 } 345 346 /* 347 ** Set the number of backtrace levels kept for each allocation. 348 ** A value of zero turns off backtracing. The number is always rounded 349 ** up to a multiple of 2. 350 */ 351 void sqlite3MemdebugBacktrace(int depth){ 352 if( depth<0 ){ depth = 0; } 353 if( depth>20 ){ depth = 20; } 354 depth = (depth+1)&0xfe; 355 mem.nBacktrace = depth; 356 } 357 358 void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ 359 mem.xBacktrace = xBacktrace; 360 } 361 362 /* 363 ** Set the title string for subsequent allocations. 364 */ 365 void sqlite3MemdebugSettitle(const char *zTitle){ 366 unsigned int n = sqlite3Strlen30(zTitle) + 1; 367 sqlite3_mutex_enter(mem.mutex); 368 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; 369 memcpy(mem.zTitle, zTitle, n); 370 mem.zTitle[n] = 0; 371 mem.nTitle = (n+7)&~7; 372 sqlite3_mutex_leave(mem.mutex); 373 } 374 375 void sqlite3MemdebugSync(){ 376 struct MemBlockHdr *pHdr; 377 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ 378 void **pBt = (void**)pHdr; 379 pBt -= pHdr->nBacktraceSlots; 380 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); 381 } 382 } 383 384 /* 385 ** Open the file indicated and write a log of all unfreed memory 386 ** allocations into that log. 387 */ 388 void sqlite3MemdebugDump(const char *zFilename){ 389 FILE *out; 390 struct MemBlockHdr *pHdr; 391 void **pBt; 392 int i; 393 out = fopen(zFilename, "w"); 394 if( out==0 ){ 395 fprintf(stderr, "** Unable to output memory debug output log: %s **\n", 396 zFilename); 397 return; 398 } 399 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ 400 char *z = (char*)pHdr; 401 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; 402 fprintf(out, "**** %lld bytes at %p from %s ****\n", 403 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); 404 if( pHdr->nBacktrace ){ 405 fflush(out); 406 pBt = (void**)pHdr; 407 pBt -= pHdr->nBacktraceSlots; 408 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); 409 fprintf(out, "\n"); 410 } 411 } 412 fprintf(out, "COUNTS:\n"); 413 for(i=0; i<NCSIZE-1; i++){ 414 if( mem.nAlloc[i] ){ 415 fprintf(out, " %5d: %10d %10d %10d\n", 416 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]); 417 } 418 } 419 if( mem.nAlloc[NCSIZE-1] ){ 420 fprintf(out, " %5d: %10d %10d %10d\n", 421 NCSIZE*8-8, mem.nAlloc[NCSIZE-1], 422 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]); 423 } 424 fclose(out); 425 } 426 427 /* 428 ** Return the number of times sqlite3MemMalloc() has been called. 429 */ 430 int sqlite3MemdebugMallocCount(){ 431 int i; 432 int nTotal = 0; 433 for(i=0; i<NCSIZE; i++){ 434 nTotal += mem.nAlloc[i]; 435 } 436 return nTotal; 437 } 438 439 440 #endif /* SQLITE_MEMDEBUG */ 441