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