xref: /sqlite-3.40.0/src/mem2.c (revision 6695f47e)
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 ** Allocate nByte bytes of memory.
215 */
216 static void *sqlite3MemMalloc(int nByte){
217   struct MemBlockHdr *pHdr;
218   void **pBt;
219   char *z;
220   int *pInt;
221   void *p = 0;
222   int totalSize;
223   int nReserve;
224   sqlite3_mutex_enter(mem.mutex);
225   assert( mem.disallow==0 );
226   nReserve = ROUND8(nByte);
227   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
228                mem.nBacktrace*sizeof(void*) + mem.nTitle;
229   p = malloc(totalSize);
230   if( p ){
231     z = p;
232     pBt = (void**)&z[mem.nTitle];
233     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
234     pHdr->pNext = 0;
235     pHdr->pPrev = mem.pLast;
236     if( mem.pLast ){
237       mem.pLast->pNext = pHdr;
238     }else{
239       mem.pFirst = pHdr;
240     }
241     mem.pLast = pHdr;
242     pHdr->iForeGuard = FOREGUARD;
243     pHdr->nBacktraceSlots = mem.nBacktrace;
244     pHdr->nTitle = mem.nTitle;
245     if( mem.nBacktrace ){
246       void *aAddr[40];
247       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
248       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
249       assert(pBt[0]);
250       if( mem.xBacktrace ){
251         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
252       }
253     }else{
254       pHdr->nBacktrace = 0;
255     }
256     if( mem.nTitle ){
257       memcpy(z, mem.zTitle, mem.nTitle);
258     }
259     pHdr->iSize = nByte;
260     adjustStats(nByte, +1);
261     pInt = (int*)&pHdr[1];
262     pInt[nReserve/sizeof(int)] = REARGUARD;
263     memset(pInt, 0x65, nReserve);
264     p = (void*)pInt;
265   }
266   sqlite3_mutex_leave(mem.mutex);
267   return p;
268 }
269 
270 /*
271 ** Free memory.
272 */
273 static void sqlite3MemFree(void *pPrior){
274   struct MemBlockHdr *pHdr;
275   void **pBt;
276   char *z;
277   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
278   pHdr = sqlite3MemsysGetHeader(pPrior);
279   pBt = (void**)pHdr;
280   pBt -= pHdr->nBacktraceSlots;
281   sqlite3_mutex_enter(mem.mutex);
282   if( pHdr->pPrev ){
283     assert( pHdr->pPrev->pNext==pHdr );
284     pHdr->pPrev->pNext = pHdr->pNext;
285   }else{
286     assert( mem.pFirst==pHdr );
287     mem.pFirst = pHdr->pNext;
288   }
289   if( pHdr->pNext ){
290     assert( pHdr->pNext->pPrev==pHdr );
291     pHdr->pNext->pPrev = pHdr->pPrev;
292   }else{
293     assert( mem.pLast==pHdr );
294     mem.pLast = pHdr->pPrev;
295   }
296   z = (char*)pBt;
297   z -= pHdr->nTitle;
298   adjustStats(pHdr->iSize, -1);
299   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
300                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
301   free(z);
302   sqlite3_mutex_leave(mem.mutex);
303 }
304 
305 /*
306 ** Change the size of an existing memory allocation.
307 **
308 ** For this debugging implementation, we *always* make a copy of the
309 ** allocation into a new place in memory.  In this way, if the
310 ** higher level code is using pointer to the old allocation, it is
311 ** much more likely to break and we are much more liking to find
312 ** the error.
313 */
314 static void *sqlite3MemRealloc(void *pPrior, int nByte){
315   struct MemBlockHdr *pOldHdr;
316   void *pNew;
317   assert( mem.disallow==0 );
318   pOldHdr = sqlite3MemsysGetHeader(pPrior);
319   pNew = sqlite3MemMalloc(nByte);
320   if( pNew ){
321     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
322     if( nByte>pOldHdr->iSize ){
323       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
324     }
325     sqlite3MemFree(pPrior);
326   }
327   return pNew;
328 }
329 
330 /*
331 ** Populate the low-level memory allocation function pointers in
332 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
333 */
334 void sqlite3MemSetDefault(void){
335   static const sqlite3_mem_methods defaultMethods = {
336      sqlite3MemMalloc,
337      sqlite3MemFree,
338      sqlite3MemRealloc,
339      sqlite3MemSize,
340      sqlite3MemRoundup,
341      sqlite3MemInit,
342      sqlite3MemShutdown,
343      0
344   };
345   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
346 }
347 
348 /*
349 ** Set the number of backtrace levels kept for each allocation.
350 ** A value of zero turns off backtracing.  The number is always rounded
351 ** up to a multiple of 2.
352 */
353 void sqlite3MemdebugBacktrace(int depth){
354   if( depth<0 ){ depth = 0; }
355   if( depth>20 ){ depth = 20; }
356   depth = (depth+1)&0xfe;
357   mem.nBacktrace = depth;
358 }
359 
360 void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
361   mem.xBacktrace = xBacktrace;
362 }
363 
364 /*
365 ** Set the title string for subsequent allocations.
366 */
367 void sqlite3MemdebugSettitle(const char *zTitle){
368   unsigned int n = sqlite3Strlen30(zTitle) + 1;
369   sqlite3_mutex_enter(mem.mutex);
370   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
371   memcpy(mem.zTitle, zTitle, n);
372   mem.zTitle[n] = 0;
373   mem.nTitle = ROUND8(n);
374   sqlite3_mutex_leave(mem.mutex);
375 }
376 
377 void sqlite3MemdebugSync(){
378   struct MemBlockHdr *pHdr;
379   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
380     void **pBt = (void**)pHdr;
381     pBt -= pHdr->nBacktraceSlots;
382     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
383   }
384 }
385 
386 /*
387 ** Open the file indicated and write a log of all unfreed memory
388 ** allocations into that log.
389 */
390 void sqlite3MemdebugDump(const char *zFilename){
391   FILE *out;
392   struct MemBlockHdr *pHdr;
393   void **pBt;
394   int i;
395   out = fopen(zFilename, "w");
396   if( out==0 ){
397     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
398                     zFilename);
399     return;
400   }
401   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
402     char *z = (char*)pHdr;
403     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
404     fprintf(out, "**** %lld bytes at %p from %s ****\n",
405             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
406     if( pHdr->nBacktrace ){
407       fflush(out);
408       pBt = (void**)pHdr;
409       pBt -= pHdr->nBacktraceSlots;
410       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
411       fprintf(out, "\n");
412     }
413   }
414   fprintf(out, "COUNTS:\n");
415   for(i=0; i<NCSIZE-1; i++){
416     if( mem.nAlloc[i] ){
417       fprintf(out, "   %5d: %10d %10d %10d\n",
418             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
419     }
420   }
421   if( mem.nAlloc[NCSIZE-1] ){
422     fprintf(out, "   %5d: %10d %10d %10d\n",
423              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
424              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
425   }
426   fclose(out);
427 }
428 
429 /*
430 ** Return the number of times sqlite3MemMalloc() has been called.
431 */
432 int sqlite3MemdebugMallocCount(){
433   int i;
434   int nTotal = 0;
435   for(i=0; i<NCSIZE; i++){
436     nTotal += mem.nAlloc[i];
437   }
438   return nTotal;
439 }
440 
441 
442 #endif /* SQLITE_MEMDEBUG */
443