mem2.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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.18 2007/11/29 18:36:49 drh Exp $
  16. */
  17. /*
  18. ** This version of the memory allocator is used only if the
  19. ** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION
  20. ** is not defined.
  21. */
  22. #if defined(SQLITE_MEMDEBUG)
  23. /*
  24. ** We will eventually construct multiple memory allocation subsystems
  25. ** suitable for use in various contexts:
  26. **
  27. ** * Normal multi-threaded builds
  28. ** * Normal single-threaded builds
  29. ** * Debugging builds
  30. **
  31. ** This version is suitable for use in debugging builds.
  32. **
  33. ** Features:
  34. **
  35. ** * Every allocate has guards at both ends.
  36. ** * New allocations are initialized with randomness
  37. ** * Allocations are overwritten with randomness when freed
  38. ** * Optional logs of malloc activity generated
  39. ** * Summary of outstanding allocations with backtraces to the
  40. ** point of allocation.
  41. ** * The ability to simulate memory allocation failure
  42. */
  43. #include "sqliteInt.h"
  44. #include <stdio.h>
  45. /*
  46. ** The backtrace functionality is only available with GLIBC
  47. */
  48. #ifdef __GLIBC__
  49. extern int backtrace(void**,int);
  50. extern void backtrace_symbols_fd(void*const*,int,int);
  51. #else
  52. # define backtrace(A,B) 0
  53. # define backtrace_symbols_fd(A,B,C)
  54. #endif
  55. /*
  56. ** Each memory allocation looks like this:
  57. **
  58. ** ------------------------------------------------------------------------
  59. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  60. ** ------------------------------------------------------------------------
  61. **
  62. ** The application code sees only a pointer to the allocation. We have
  63. ** to back up from the allocation pointer to find the MemBlockHdr. The
  64. ** MemBlockHdr tells us the size of the allocation and the number of
  65. ** backtrace pointers. There is also a guard word at the end of the
  66. ** MemBlockHdr.
  67. */
  68. struct MemBlockHdr {
  69. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  70. int iSize; /* Size of this allocation */
  71. char nBacktrace; /* Number of backtraces on this alloc */
  72. char nBacktraceSlots; /* Available backtrace slots */
  73. short nTitle; /* Bytes of title; includes '\0' */
  74. int iForeGuard; /* Guard word for sanity */
  75. };
  76. /*
  77. ** Guard words
  78. */
  79. #define FOREGUARD 0x80F5E153
  80. #define REARGUARD 0xE4676B53
  81. /*
  82. ** Number of malloc size increments to track.
  83. */
  84. #define NCSIZE 1000
  85. /*
  86. ** All of the static variables used by this module are collected
  87. ** into a single structure named "mem". This is to keep the
  88. ** static variables organized and to reduce namespace pollution
  89. ** when this module is combined with other in the amalgamation.
  90. */
  91. static struct {
  92. /*
  93. ** The alarm callback and its arguments. The mem.mutex lock will
  94. ** be held while the callback is running. Recursive calls into
  95. ** the memory subsystem are allowed, but no new callbacks will be
  96. ** issued. The alarmBusy variable is set to prevent recursive
  97. ** callbacks.
  98. */
  99. sqlite3_int64 alarmThreshold;
  100. void (*alarmCallback)(void*, sqlite3_int64, int);
  101. void *alarmArg;
  102. int alarmBusy;
  103. /*
  104. ** Mutex to control access to the memory allocation subsystem.
  105. */
  106. sqlite3_mutex *mutex;
  107. /*
  108. ** Current allocation and high-water mark.
  109. */
  110. sqlite3_int64 nowUsed;
  111. sqlite3_int64 mxUsed;
  112. /*
  113. ** Head and tail of a linked list of all outstanding allocations
  114. */
  115. struct MemBlockHdr *pFirst;
  116. struct MemBlockHdr *pLast;
  117. /*
  118. ** The number of levels of backtrace to save in new allocations.
  119. */
  120. int nBacktrace;
  121. /*
  122. ** Title text to insert in front of each block
  123. */
  124. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  125. char zTitle[100]; /* The title text */
  126. /*
  127. ** These values are used to simulate malloc failures. When
  128. ** iFail is 1, simulate a malloc failures and reset the value
  129. ** to iReset.
  130. */
  131. int iFail; /* Decrement and fail malloc when this is 1 */
  132. int iReset; /* When malloc fails set iiFail to this value */
  133. int iFailCnt; /* Number of failures */
  134. int iBenignFailCnt; /* Number of benign failures */
  135. int iNextIsBenign; /* True if the next call to malloc may fail benignly */
  136. int iIsBenign; /* All malloc calls may fail benignly */
  137. /*
  138. ** sqlite3MallocDisallow() increments the following counter.
  139. ** sqlite3MallocAllow() decrements it.
  140. */
  141. int disallow; /* Do not allow memory allocation */
  142. /*
  143. ** Gather statistics on the sizes of memory allocations.
  144. ** sizeCnt[i] is the number of allocation attempts of i*8
  145. ** bytes. i==NCSIZE is the number of allocation attempts for
  146. ** sizes more than NCSIZE*8 bytes.
  147. */
  148. int sizeCnt[NCSIZE];
  149. } mem;
  150. /*
  151. ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
  152. */
  153. static void enterMem(void){
  154. if( mem.mutex==0 ){
  155. mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
  156. }
  157. sqlite3_mutex_enter(mem.mutex);
  158. }
  159. /*
  160. ** Return the amount of memory currently checked out.
  161. */
  162. sqlite3_int64 sqlite3_memory_used(void){
  163. sqlite3_int64 n;
  164. enterMem();
  165. n = mem.nowUsed;
  166. sqlite3_mutex_leave(mem.mutex);
  167. return n;
  168. }
  169. /*
  170. ** Return the maximum amount of memory that has ever been
  171. ** checked out since either the beginning of this process
  172. ** or since the most recent reset.
  173. */
  174. sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  175. sqlite3_int64 n;
  176. enterMem();
  177. n = mem.mxUsed;
  178. if( resetFlag ){
  179. mem.mxUsed = mem.nowUsed;
  180. }
  181. sqlite3_mutex_leave(mem.mutex);
  182. return n;
  183. }
  184. /*
  185. ** Change the alarm callback
  186. */
  187. int sqlite3_memory_alarm(
  188. void(*xCallback)(void *pArg, sqlite3_int64 used, int N),
  189. void *pArg,
  190. sqlite3_int64 iThreshold
  191. ){
  192. enterMem();
  193. mem.alarmCallback = xCallback;
  194. mem.alarmArg = pArg;
  195. mem.alarmThreshold = iThreshold;
  196. sqlite3_mutex_leave(mem.mutex);
  197. return SQLITE_OK;
  198. }
  199. /*
  200. ** Trigger the alarm
  201. */
  202. static void sqlite3MemsysAlarm(int nByte){
  203. void (*xCallback)(void*,sqlite3_int64,int);
  204. sqlite3_int64 nowUsed;
  205. void *pArg;
  206. if( mem.alarmCallback==0 || mem.alarmBusy ) return;
  207. mem.alarmBusy = 1;
  208. xCallback = mem.alarmCallback;
  209. nowUsed = mem.nowUsed;
  210. pArg = mem.alarmArg;
  211. sqlite3_mutex_leave(mem.mutex);
  212. xCallback(pArg, nowUsed, nByte);
  213. sqlite3_mutex_enter(mem.mutex);
  214. mem.alarmBusy = 0;
  215. }
  216. /*
  217. ** Given an allocation, find the MemBlockHdr for that allocation.
  218. **
  219. ** This routine checks the guards at either end of the allocation and
  220. ** if they are incorrect it asserts.
  221. */
  222. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  223. struct MemBlockHdr *p;
  224. int *pInt;
  225. p = (struct MemBlockHdr*)pAllocation;
  226. p--;
  227. assert( p->iForeGuard==FOREGUARD );
  228. assert( (p->iSize & 3)==0 );
  229. pInt = (int*)pAllocation;
  230. assert( pInt[p->iSize/sizeof(int)]==REARGUARD );
  231. return p;
  232. }
  233. /*
  234. ** This routine is called once the first time a simulated memory
  235. ** failure occurs. The sole purpose of this routine is to provide
  236. ** a convenient place to set a debugger breakpoint when debugging
  237. ** errors related to malloc() failures.
  238. */
  239. static void sqlite3MemsysFailed(void){
  240. mem.iFailCnt = 0;
  241. mem.iBenignFailCnt = 0;
  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. if( nByte>0 ){
  254. enterMem();
  255. assert( mem.disallow==0 );
  256. if( mem.alarmCallback!=0 && mem.nowUsed+nByte>=mem.alarmThreshold ){
  257. sqlite3MemsysAlarm(nByte);
  258. }
  259. nByte = (nByte+3)&~3;
  260. if( nByte/8>NCSIZE-1 ){
  261. mem.sizeCnt[NCSIZE-1]++;
  262. }else{
  263. mem.sizeCnt[nByte/8]++;
  264. }
  265. totalSize = nByte + sizeof(*pHdr) + sizeof(int) +
  266. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  267. if( mem.iFail>0 ){
  268. if( mem.iFail==1 ){
  269. p = 0;
  270. mem.iFail = mem.iReset;
  271. if( mem.iFailCnt==0 ){
  272. sqlite3MemsysFailed(); /* A place to set a breakpoint */
  273. }
  274. mem.iFailCnt++;
  275. if( mem.iNextIsBenign || mem.iIsBenign ){
  276. mem.iBenignFailCnt++;
  277. }
  278. }else{
  279. p = malloc(totalSize);
  280. mem.iFail--;
  281. }
  282. }else{
  283. p = malloc(totalSize);
  284. if( p==0 ){
  285. sqlite3MemsysAlarm(nByte);
  286. p = malloc(totalSize);
  287. }
  288. }
  289. if( p ){
  290. z = p;
  291. pBt = (void**)&z[mem.nTitle];
  292. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  293. pHdr->pNext = 0;
  294. pHdr->pPrev = mem.pLast;
  295. if( mem.pLast ){
  296. mem.pLast->pNext = pHdr;
  297. }else{
  298. mem.pFirst = pHdr;
  299. }
  300. mem.pLast = pHdr;
  301. pHdr->iForeGuard = FOREGUARD;
  302. pHdr->nBacktraceSlots = mem.nBacktrace;
  303. pHdr->nTitle = mem.nTitle;
  304. if( mem.nBacktrace ){
  305. void *aAddr[40];
  306. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  307. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  308. }else{
  309. pHdr->nBacktrace = 0;
  310. }
  311. if( mem.nTitle ){
  312. memcpy(z, mem.zTitle, mem.nTitle);
  313. }
  314. pHdr->iSize = nByte;
  315. pInt = (int*)&pHdr[1];
  316. pInt[nByte/sizeof(int)] = REARGUARD;
  317. memset(pInt, 0x65, nByte);
  318. mem.nowUsed += nByte;
  319. if( mem.nowUsed>mem.mxUsed ){
  320. mem.mxUsed = mem.nowUsed;
  321. }
  322. p = (void*)pInt;
  323. }
  324. sqlite3_mutex_leave(mem.mutex);
  325. }
  326. mem.iNextIsBenign = 0;
  327. return p;
  328. }
  329. /*
  330. ** Free memory.
  331. */
  332. void sqlite3_free(void *pPrior){
  333. struct MemBlockHdr *pHdr;
  334. void **pBt;
  335. char *z;
  336. if( pPrior==0 ){
  337. return;
  338. }
  339. assert( mem.mutex!=0 );
  340. pHdr = sqlite3MemsysGetHeader(pPrior);
  341. pBt = (void**)pHdr;
  342. pBt -= pHdr->nBacktraceSlots;
  343. sqlite3_mutex_enter(mem.mutex);
  344. mem.nowUsed -= pHdr->iSize;
  345. if( pHdr->pPrev ){
  346. assert( pHdr->pPrev->pNext==pHdr );
  347. pHdr->pPrev->pNext = pHdr->pNext;
  348. }else{
  349. assert( mem.pFirst==pHdr );
  350. mem.pFirst = pHdr->pNext;
  351. }
  352. if( pHdr->pNext ){
  353. assert( pHdr->pNext->pPrev==pHdr );
  354. pHdr->pNext->pPrev = pHdr->pPrev;
  355. }else{
  356. assert( mem.pLast==pHdr );
  357. mem.pLast = pHdr->pPrev;
  358. }
  359. z = (char*)pBt;
  360. z -= pHdr->nTitle;
  361. memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  362. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  363. free(z);
  364. sqlite3_mutex_leave(mem.mutex);
  365. }
  366. /*
  367. ** Change the size of an existing memory allocation.
  368. **
  369. ** For this debugging implementation, we *always* make a copy of the
  370. ** allocation into a new place in memory. In this way, if the
  371. ** higher level code is using pointer to the old allocation, it is
  372. ** much more likely to break and we are much more liking to find
  373. ** the error.
  374. */
  375. void *sqlite3_realloc(void *pPrior, int nByte){
  376. struct MemBlockHdr *pOldHdr;
  377. void *pNew;
  378. if( pPrior==0 ){
  379. return sqlite3_malloc(nByte);
  380. }
  381. if( nByte<=0 ){
  382. sqlite3_free(pPrior);
  383. return 0;
  384. }
  385. assert( mem.disallow==0 );
  386. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  387. pNew = sqlite3_malloc(nByte);
  388. if( pNew ){
  389. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  390. if( nByte>pOldHdr->iSize ){
  391. memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
  392. }
  393. sqlite3_free(pPrior);
  394. }
  395. return pNew;
  396. }
  397. /*
  398. ** Set the number of backtrace levels kept for each allocation.
  399. ** A value of zero turns of backtracing. The number is always rounded
  400. ** up to a multiple of 2.
  401. */
  402. void sqlite3_memdebug_backtrace(int depth){
  403. if( depth<0 ){ depth = 0; }
  404. if( depth>20 ){ depth = 20; }
  405. depth = (depth+1)&0xfe;
  406. mem.nBacktrace = depth;
  407. }
  408. /*
  409. ** Set the title string for subsequent allocations.
  410. */
  411. void sqlite3_memdebug_settitle(const char *zTitle){
  412. int n = strlen(zTitle) + 1;
  413. enterMem();
  414. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  415. memcpy(mem.zTitle, zTitle, n);
  416. mem.zTitle[n] = 0;
  417. mem.nTitle = (n+3)&~3;
  418. sqlite3_mutex_leave(mem.mutex);
  419. }
  420. /*
  421. ** Open the file indicated and write a log of all unfreed memory
  422. ** allocations into that log.
  423. */
  424. void sqlite3_memdebug_dump(const char *zFilename){
  425. FILE *out;
  426. struct MemBlockHdr *pHdr;
  427. void **pBt;
  428. int i;
  429. out = fopen(zFilename, "w");
  430. if( out==0 ){
  431. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  432. zFilename);
  433. return;
  434. }
  435. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  436. char *z = (char*)pHdr;
  437. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  438. fprintf(out, "**** %d bytes at %p from %s ****\n",
  439. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  440. if( pHdr->nBacktrace ){
  441. fflush(out);
  442. pBt = (void**)pHdr;
  443. pBt -= pHdr->nBacktraceSlots;
  444. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  445. fprintf(out, "\n");
  446. }
  447. }
  448. fprintf(out, "COUNTS:\n");
  449. for(i=0; i<NCSIZE-1; i++){
  450. if( mem.sizeCnt[i] ){
  451. fprintf(out, " %3d: %d\n", i*8+8, mem.sizeCnt[i]);
  452. }
  453. }
  454. if( mem.sizeCnt[NCSIZE-1] ){
  455. fprintf(out, " >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]);
  456. }
  457. fclose(out);
  458. }
  459. /*
  460. ** This routine is used to simulate malloc failures.
  461. **
  462. ** After calling this routine, there will be iFail successful
  463. ** memory allocations and then a failure. If iRepeat is 1
  464. ** all subsequent memory allocations will fail. If iRepeat is
  465. ** 0, only a single allocation will fail. If iRepeat is negative
  466. ** then the previous setting for iRepeat is unchanged.
  467. **
  468. ** Each call to this routine overrides the previous. To disable
  469. ** the simulated allocation failure mechanism, set iFail to -1.
  470. **
  471. ** This routine returns the number of simulated failures that have
  472. ** occurred since the previous call.
  473. */
  474. int sqlite3_memdebug_fail(int iFail, int iRepeat, int *piBenign){
  475. int n = mem.iFailCnt;
  476. if( piBenign ){
  477. *piBenign = mem.iBenignFailCnt;
  478. }
  479. mem.iFail = iFail+1;
  480. if( iRepeat>=0 ){
  481. mem.iReset = iRepeat;
  482. }
  483. mem.iFailCnt = 0;
  484. mem.iBenignFailCnt = 0;
  485. return n;
  486. }
  487. int sqlite3_memdebug_pending(){
  488. return (mem.iFail-1);
  489. }
  490. /*
  491. ** The following three functions are used to indicate to the test
  492. ** infrastructure which malloc() calls may fail benignly without
  493. ** affecting functionality. This can happen when resizing hash tables
  494. ** (failing to resize a hash-table is a performance hit, but not an
  495. ** error) or sometimes during a rollback operation.
  496. **
  497. ** If the argument is true, sqlite3MallocBenignFailure() indicates that the
  498. ** next call to allocate memory may fail benignly.
  499. **
  500. ** If sqlite3MallocEnterBenignBlock() is called with a non-zero argument,
  501. ** then all memory allocations requested before the next call to
  502. ** sqlite3MallocLeaveBenignBlock() may fail benignly.
  503. */
  504. void sqlite3MallocBenignFailure(int isBenign){
  505. if( isBenign ){
  506. mem.iNextIsBenign = 1;
  507. }
  508. }
  509. void sqlite3MallocEnterBenignBlock(int isBenign){
  510. if( isBenign ){
  511. mem.iIsBenign = 1;
  512. }
  513. }
  514. void sqlite3MallocLeaveBenignBlock(){
  515. mem.iIsBenign = 0;
  516. }
  517. /*
  518. ** The following two routines are used to assert that no memory
  519. ** allocations occur between one call and the next. The use of
  520. ** these routines does not change the computed results in any way.
  521. ** These routines are like asserts.
  522. */
  523. void sqlite3MallocDisallow(void){
  524. assert( mem.mutex!=0 );
  525. sqlite3_mutex_enter(mem.mutex);
  526. mem.disallow++;
  527. sqlite3_mutex_leave(mem.mutex);
  528. }
  529. void sqlite3MallocAllow(void){
  530. assert( mem.mutex );
  531. sqlite3_mutex_enter(mem.mutex);
  532. assert( mem.disallow>0 );
  533. mem.disallow--;
  534. sqlite3_mutex_leave(mem.mutex);
  535. }
  536. #endif /* SQLITE_MEMDEBUG && !SQLITE_OMIT_MEMORY_ALLOCATION */