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