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.34 2008/07/10 18:13:42 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) 0 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 ** sizeCnt[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 sizeCnt[NCSIZE]; 121 122 } mem; 123 124 /* 125 ** Given an allocation, find the MemBlockHdr for that allocation. 126 ** 127 ** This routine checks the guards at either end of the allocation and 128 ** if they are incorrect it asserts. 129 */ 130 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ 131 struct MemBlockHdr *p; 132 int *pInt; 133 u8 *pU8; 134 int nReserve; 135 136 p = (struct MemBlockHdr*)pAllocation; 137 p--; 138 assert( p->iForeGuard==FOREGUARD ); 139 nReserve = (p->iSize+7)&~7; 140 pInt = (int*)pAllocation; 141 pU8 = (u8*)pAllocation; 142 assert( pInt[nReserve/sizeof(int)]==REARGUARD ); 143 assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 ); 144 assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 ); 145 assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 ); 146 return p; 147 } 148 149 /* 150 ** Return the number of bytes currently allocated at address p. 151 */ 152 static int sqlite3MemSize(void *p){ 153 struct MemBlockHdr *pHdr; 154 if( !p ){ 155 return 0; 156 } 157 pHdr = sqlite3MemsysGetHeader(p); 158 return pHdr->iSize; 159 } 160 161 /* 162 ** Initialize the memory allocation subsystem. 163 */ 164 static int sqlite3MemInit(void *NotUsed){ 165 if( !sqlite3Config.bMemstat ){ 166 /* If memory status is enabled, then the malloc.c wrapper will already 167 ** hold the STATIC_MEM mutex when the routines here are invoked. */ 168 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); 169 } 170 return SQLITE_OK; 171 } 172 173 /* 174 ** Deinitialize the memory allocation subsystem. 175 */ 176 static void sqlite3MemShutdown(void *NotUsed){ 177 mem.mutex = 0; 178 } 179 180 /* 181 ** Round up a request size to the next valid allocation size. 182 */ 183 static int sqlite3MemRoundup(int n){ 184 return (n+7) & ~7; 185 } 186 187 /* 188 ** Allocate nByte bytes of memory. 189 */ 190 static void *sqlite3MemMalloc(int nByte){ 191 struct MemBlockHdr *pHdr; 192 void **pBt; 193 char *z; 194 int *pInt; 195 void *p = 0; 196 int totalSize; 197 int nReserve; 198 sqlite3_mutex_enter(mem.mutex); 199 assert( mem.disallow==0 ); 200 nReserve = (nByte+7)&~7; 201 if( nReserve/8>NCSIZE-1 ){ 202 mem.sizeCnt[NCSIZE-1]++; 203 }else{ 204 mem.sizeCnt[nReserve/8]++; 205 } 206 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + 207 mem.nBacktrace*sizeof(void*) + mem.nTitle; 208 p = malloc(totalSize); 209 if( p ){ 210 z = p; 211 pBt = (void**)&z[mem.nTitle]; 212 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; 213 pHdr->pNext = 0; 214 pHdr->pPrev = mem.pLast; 215 if( mem.pLast ){ 216 mem.pLast->pNext = pHdr; 217 }else{ 218 mem.pFirst = pHdr; 219 } 220 mem.pLast = pHdr; 221 pHdr->iForeGuard = FOREGUARD; 222 pHdr->nBacktraceSlots = mem.nBacktrace; 223 pHdr->nTitle = mem.nTitle; 224 if( mem.nBacktrace ){ 225 void *aAddr[40]; 226 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; 227 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); 228 if( mem.xBacktrace ){ 229 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); 230 } 231 }else{ 232 pHdr->nBacktrace = 0; 233 } 234 if( mem.nTitle ){ 235 memcpy(z, mem.zTitle, mem.nTitle); 236 } 237 pHdr->iSize = nByte; 238 pInt = (int*)&pHdr[1]; 239 pInt[nReserve/sizeof(int)] = REARGUARD; 240 memset(pInt, 0x65, nReserve); 241 p = (void*)pInt; 242 } 243 sqlite3_mutex_leave(mem.mutex); 244 return p; 245 } 246 247 /* 248 ** Free memory. 249 */ 250 static void sqlite3MemFree(void *pPrior){ 251 struct MemBlockHdr *pHdr; 252 void **pBt; 253 char *z; 254 assert( sqlite3Config.bMemstat || mem.mutex!=0 ); 255 pHdr = sqlite3MemsysGetHeader(pPrior); 256 pBt = (void**)pHdr; 257 pBt -= pHdr->nBacktraceSlots; 258 sqlite3_mutex_enter(mem.mutex); 259 if( pHdr->pPrev ){ 260 assert( pHdr->pPrev->pNext==pHdr ); 261 pHdr->pPrev->pNext = pHdr->pNext; 262 }else{ 263 assert( mem.pFirst==pHdr ); 264 mem.pFirst = pHdr->pNext; 265 } 266 if( pHdr->pNext ){ 267 assert( pHdr->pNext->pPrev==pHdr ); 268 pHdr->pNext->pPrev = pHdr->pPrev; 269 }else{ 270 assert( mem.pLast==pHdr ); 271 mem.pLast = pHdr->pPrev; 272 } 273 z = (char*)pBt; 274 z -= pHdr->nTitle; 275 memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + 276 pHdr->iSize + sizeof(int) + pHdr->nTitle); 277 free(z); 278 sqlite3_mutex_leave(mem.mutex); 279 } 280 281 /* 282 ** Change the size of an existing memory allocation. 283 ** 284 ** For this debugging implementation, we *always* make a copy of the 285 ** allocation into a new place in memory. In this way, if the 286 ** higher level code is using pointer to the old allocation, it is 287 ** much more likely to break and we are much more liking to find 288 ** the error. 289 */ 290 static void *sqlite3MemRealloc(void *pPrior, int nByte){ 291 struct MemBlockHdr *pOldHdr; 292 void *pNew; 293 assert( mem.disallow==0 ); 294 pOldHdr = sqlite3MemsysGetHeader(pPrior); 295 pNew = sqlite3MemMalloc(nByte); 296 if( pNew ){ 297 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize); 298 if( nByte>pOldHdr->iSize ){ 299 memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize); 300 } 301 sqlite3MemFree(pPrior); 302 } 303 return pNew; 304 } 305 306 307 /* 308 ** Populate the low-level memory allocation function pointers in 309 ** sqlite3Config.m with pointers to the routines in this file. 310 */ 311 void sqlite3MemSetDefault(void){ 312 static const sqlite3_mem_methods defaultMethods = { 313 sqlite3MemMalloc, 314 sqlite3MemFree, 315 sqlite3MemRealloc, 316 sqlite3MemSize, 317 sqlite3MemRoundup, 318 sqlite3MemInit, 319 sqlite3MemShutdown, 320 0 321 }; 322 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); 323 } 324 325 /* 326 ** Set the number of backtrace levels kept for each allocation. 327 ** A value of zero turns off backtracing. The number is always rounded 328 ** up to a multiple of 2. 329 */ 330 void sqlite3MemdebugBacktrace(int depth){ 331 if( depth<0 ){ depth = 0; } 332 if( depth>20 ){ depth = 20; } 333 depth = (depth+1)&0xfe; 334 mem.nBacktrace = depth; 335 } 336 337 void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ 338 mem.xBacktrace = xBacktrace; 339 } 340 341 /* 342 ** Set the title string for subsequent allocations. 343 */ 344 void sqlite3MemdebugSettitle(const char *zTitle){ 345 int n = strlen(zTitle) + 1; 346 sqlite3_mutex_enter(mem.mutex); 347 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; 348 memcpy(mem.zTitle, zTitle, n); 349 mem.zTitle[n] = 0; 350 mem.nTitle = (n+7)&~7; 351 sqlite3_mutex_leave(mem.mutex); 352 } 353 354 void sqlite3MemdebugSync(){ 355 struct MemBlockHdr *pHdr; 356 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ 357 void **pBt = (void**)pHdr; 358 pBt -= pHdr->nBacktraceSlots; 359 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); 360 } 361 } 362 363 /* 364 ** Open the file indicated and write a log of all unfreed memory 365 ** allocations into that log. 366 */ 367 void sqlite3MemdebugDump(const char *zFilename){ 368 FILE *out; 369 struct MemBlockHdr *pHdr; 370 void **pBt; 371 int i; 372 out = fopen(zFilename, "w"); 373 if( out==0 ){ 374 fprintf(stderr, "** Unable to output memory debug output log: %s **\n", 375 zFilename); 376 return; 377 } 378 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ 379 char *z = (char*)pHdr; 380 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; 381 fprintf(out, "**** %lld bytes at %p from %s ****\n", 382 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); 383 if( pHdr->nBacktrace ){ 384 fflush(out); 385 pBt = (void**)pHdr; 386 pBt -= pHdr->nBacktraceSlots; 387 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); 388 fprintf(out, "\n"); 389 } 390 } 391 fprintf(out, "COUNTS:\n"); 392 for(i=0; i<NCSIZE-1; i++){ 393 if( mem.sizeCnt[i] ){ 394 fprintf(out, " %3d: %d\n", i*8+8, mem.sizeCnt[i]); 395 } 396 } 397 if( mem.sizeCnt[NCSIZE-1] ){ 398 fprintf(out, " >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]); 399 } 400 fclose(out); 401 } 402 403 /* 404 ** Return the number of times sqlite3MemMalloc() has been called. 405 */ 406 int sqlite3MemdebugMallocCount(){ 407 int i; 408 int nTotal = 0; 409 for(i=0; i<NCSIZE; i++){ 410 nTotal += mem.sizeCnt[i]; 411 } 412 return nTotal; 413 } 414 415 416 #endif /* SQLITE_MEMDEBUG */ 417