mem2.c 14 KB

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