xref: /sqlite-3.40.0/src/malloc.c (revision 666d34c7)
1 /*
2 ** 2001 September 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 ** Memory allocation functions used throughout sqlite.
14 */
15 #include "sqliteInt.h"
16 #include <stdarg.h>
17 
18 /*
19 ** Attempt to release up to n bytes of non-essential memory currently
20 ** held by SQLite. An example of non-essential memory is memory used to
21 ** cache database pages that are not currently in use.
22 */
23 int sqlite3_release_memory(int n){
24 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
25   return sqlite3PcacheReleaseMemory(n);
26 #else
27   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
28   ** is a no-op returning zero if SQLite is not compiled with
29   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
30   UNUSED_PARAMETER(n);
31   return 0;
32 #endif
33 }
34 
35 /*
36 ** An instance of the following object records the location of
37 ** each unused scratch buffer.
38 */
39 typedef struct ScratchFreeslot {
40   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
41 } ScratchFreeslot;
42 
43 /*
44 ** State information local to the memory allocation subsystem.
45 */
46 static SQLITE_WSD struct Mem0Global {
47   sqlite3_mutex *mutex;         /* Mutex to serialize access */
48   sqlite3_int64 alarmThreshold; /* The soft heap limit */
49 
50   /*
51   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
52   ** (so that a range test can be used to determine if an allocation
53   ** being freed came from pScratch) and a pointer to the list of
54   ** unused scratch allocations.
55   */
56   void *pScratchEnd;
57   ScratchFreeslot *pScratchFree;
58   u32 nScratchFree;
59 
60   /*
61   ** True if heap is nearly "full" where "full" is defined by the
62   ** sqlite3_soft_heap_limit() setting.
63   */
64   int nearlyFull;
65 } mem0 = { 0, 0, 0, 0, 0, 0 };
66 
67 #define mem0 GLOBAL(struct Mem0Global, mem0)
68 
69 /*
70 ** Return the memory allocator mutex. sqlite3_status() needs it.
71 */
72 sqlite3_mutex *sqlite3MallocMutex(void){
73   return mem0.mutex;
74 }
75 
76 #ifndef SQLITE_OMIT_DEPRECATED
77 /*
78 ** Deprecated external interface.  It used to set an alarm callback
79 ** that was invoked when memory usage grew too large.  Now it is a
80 ** no-op.
81 */
82 int sqlite3_memory_alarm(
83   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
84   void *pArg,
85   sqlite3_int64 iThreshold
86 ){
87   (void)xCallback;
88   (void)pArg;
89   (void)iThreshold;
90   return SQLITE_OK;
91 }
92 #endif
93 
94 /*
95 ** Set the soft heap-size limit for the library. Passing a zero or
96 ** negative value indicates no limit.
97 */
98 sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
99   sqlite3_int64 priorLimit;
100   sqlite3_int64 excess;
101   sqlite3_int64 nUsed;
102 #ifndef SQLITE_OMIT_AUTOINIT
103   int rc = sqlite3_initialize();
104   if( rc ) return -1;
105 #endif
106   sqlite3_mutex_enter(mem0.mutex);
107   priorLimit = mem0.alarmThreshold;
108   if( n<0 ){
109     sqlite3_mutex_leave(mem0.mutex);
110     return priorLimit;
111   }
112   mem0.alarmThreshold = n;
113   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
114   mem0.nearlyFull = (n>0 && n<=nUsed);
115   sqlite3_mutex_leave(mem0.mutex);
116   excess = sqlite3_memory_used() - n;
117   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
118   return priorLimit;
119 }
120 void sqlite3_soft_heap_limit(int n){
121   if( n<0 ) n = 0;
122   sqlite3_soft_heap_limit64(n);
123 }
124 
125 /*
126 ** Initialize the memory allocation subsystem.
127 */
128 int sqlite3MallocInit(void){
129   int rc;
130   if( sqlite3GlobalConfig.m.xMalloc==0 ){
131     sqlite3MemSetDefault();
132   }
133   memset(&mem0, 0, sizeof(mem0));
134   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
135   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
136       && sqlite3GlobalConfig.nScratch>0 ){
137     int i, n, sz;
138     ScratchFreeslot *pSlot;
139     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
140     sqlite3GlobalConfig.szScratch = sz;
141     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
142     n = sqlite3GlobalConfig.nScratch;
143     mem0.pScratchFree = pSlot;
144     mem0.nScratchFree = n;
145     for(i=0; i<n-1; i++){
146       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
147       pSlot = pSlot->pNext;
148     }
149     pSlot->pNext = 0;
150     mem0.pScratchEnd = (void*)&pSlot[1];
151   }else{
152     mem0.pScratchEnd = 0;
153     sqlite3GlobalConfig.pScratch = 0;
154     sqlite3GlobalConfig.szScratch = 0;
155     sqlite3GlobalConfig.nScratch = 0;
156   }
157   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
158       || sqlite3GlobalConfig.nPage<=0 ){
159     sqlite3GlobalConfig.pPage = 0;
160     sqlite3GlobalConfig.szPage = 0;
161   }
162   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
163   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
164   return rc;
165 }
166 
167 /*
168 ** Return true if the heap is currently under memory pressure - in other
169 ** words if the amount of heap used is close to the limit set by
170 ** sqlite3_soft_heap_limit().
171 */
172 int sqlite3HeapNearlyFull(void){
173   return mem0.nearlyFull;
174 }
175 
176 /*
177 ** Deinitialize the memory allocation subsystem.
178 */
179 void sqlite3MallocEnd(void){
180   if( sqlite3GlobalConfig.m.xShutdown ){
181     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
182   }
183   memset(&mem0, 0, sizeof(mem0));
184 }
185 
186 /*
187 ** Return the amount of memory currently checked out.
188 */
189 sqlite3_int64 sqlite3_memory_used(void){
190   sqlite3_int64 res, mx;
191   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
192   return res;
193 }
194 
195 /*
196 ** Return the maximum amount of memory that has ever been
197 ** checked out since either the beginning of this process
198 ** or since the most recent reset.
199 */
200 sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
201   sqlite3_int64 res, mx;
202   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
203   return mx;
204 }
205 
206 /*
207 ** Trigger the alarm
208 */
209 static void sqlite3MallocAlarm(int nByte){
210   if( mem0.alarmThreshold<=0 ) return;
211   sqlite3_mutex_leave(mem0.mutex);
212   sqlite3_release_memory(nByte);
213   sqlite3_mutex_enter(mem0.mutex);
214 }
215 
216 /*
217 ** Do a memory allocation with statistics and alarms.  Assume the
218 ** lock is already held.
219 */
220 static void mallocWithAlarm(int n, void **pp){
221   void *p;
222   int nFull = 0;
223   assert( sqlite3_mutex_held(mem0.mutex) );
224   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
225   if( mem0.alarmThreshold>0 ){
226     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
227     nFull = sqlite3GlobalConfig.m.xRoundup(n);
228     if( nUsed >= mem0.alarmThreshold - nFull ){
229       mem0.nearlyFull = 1;
230       sqlite3MallocAlarm(nFull);
231     }else{
232       mem0.nearlyFull = 0;
233     }
234   }
235   p = sqlite3GlobalConfig.m.xMalloc(n);
236 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
237   if( p==0 && mem0.alarmThreshold>0 ){
238     sqlite3MallocAlarm(nFull);
239     p = sqlite3GlobalConfig.m.xMalloc(n);
240   }
241 #endif
242   if( p ){
243     nFull = sqlite3MallocSize(p);
244     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
245     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
246   }
247   *pp = p;
248 }
249 
250 /*
251 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
252 ** assumes the memory subsystem has already been initialized.
253 */
254 void *sqlite3Malloc(u64 n){
255   void *p;
256   if( n==0 || n>=0x7fffff00 ){
257     /* A memory allocation of a number of bytes which is near the maximum
258     ** signed integer value might cause an integer overflow inside of the
259     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
260     ** 255 bytes of overhead.  SQLite itself will never use anything near
261     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
262     p = 0;
263   }else if( sqlite3GlobalConfig.bMemstat ){
264     sqlite3_mutex_enter(mem0.mutex);
265     mallocWithAlarm((int)n, &p);
266     sqlite3_mutex_leave(mem0.mutex);
267   }else{
268     p = sqlite3GlobalConfig.m.xMalloc((int)n);
269   }
270   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
271   return p;
272 }
273 
274 /*
275 ** This version of the memory allocation is for use by the application.
276 ** First make sure the memory subsystem is initialized, then do the
277 ** allocation.
278 */
279 void *sqlite3_malloc(int n){
280 #ifndef SQLITE_OMIT_AUTOINIT
281   if( sqlite3_initialize() ) return 0;
282 #endif
283   return n<=0 ? 0 : sqlite3Malloc(n);
284 }
285 void *sqlite3_malloc64(sqlite3_uint64 n){
286 #ifndef SQLITE_OMIT_AUTOINIT
287   if( sqlite3_initialize() ) return 0;
288 #endif
289   return sqlite3Malloc(n);
290 }
291 
292 /*
293 ** Each thread may only have a single outstanding allocation from
294 ** xScratchMalloc().  We verify this constraint in the single-threaded
295 ** case by setting scratchAllocOut to 1 when an allocation
296 ** is outstanding clearing it when the allocation is freed.
297 */
298 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
299 static int scratchAllocOut = 0;
300 #endif
301 
302 
303 /*
304 ** Allocate memory that is to be used and released right away.
305 ** This routine is similar to alloca() in that it is not intended
306 ** for situations where the memory might be held long-term.  This
307 ** routine is intended to get memory to old large transient data
308 ** structures that would not normally fit on the stack of an
309 ** embedded processor.
310 */
311 void *sqlite3ScratchMalloc(int n){
312   void *p;
313   assert( n>0 );
314 
315   sqlite3_mutex_enter(mem0.mutex);
316   sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
317   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
318     p = mem0.pScratchFree;
319     mem0.pScratchFree = mem0.pScratchFree->pNext;
320     mem0.nScratchFree--;
321     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
322     sqlite3_mutex_leave(mem0.mutex);
323   }else{
324     sqlite3_mutex_leave(mem0.mutex);
325     p = sqlite3Malloc(n);
326     if( sqlite3GlobalConfig.bMemstat && p ){
327       sqlite3_mutex_enter(mem0.mutex);
328       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
329       sqlite3_mutex_leave(mem0.mutex);
330     }
331     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
332   }
333   assert( sqlite3_mutex_notheld(mem0.mutex) );
334 
335 
336 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
337   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
338   ** buffers per thread.
339   **
340   ** This can only be checked in single-threaded mode.
341   */
342   assert( scratchAllocOut==0 );
343   if( p ) scratchAllocOut++;
344 #endif
345 
346   return p;
347 }
348 void sqlite3ScratchFree(void *p){
349   if( p ){
350 
351 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
352     /* Verify that no more than two scratch allocation per thread
353     ** is outstanding at one time.  (This is only checked in the
354     ** single-threaded case since checking in the multi-threaded case
355     ** would be much more complicated.) */
356     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
357     scratchAllocOut--;
358 #endif
359 
360     if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
361       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
362       ScratchFreeslot *pSlot;
363       pSlot = (ScratchFreeslot*)p;
364       sqlite3_mutex_enter(mem0.mutex);
365       pSlot->pNext = mem0.pScratchFree;
366       mem0.pScratchFree = pSlot;
367       mem0.nScratchFree++;
368       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
369       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
370       sqlite3_mutex_leave(mem0.mutex);
371     }else{
372       /* Release memory back to the heap */
373       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
374       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
375       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
376       if( sqlite3GlobalConfig.bMemstat ){
377         int iSize = sqlite3MallocSize(p);
378         sqlite3_mutex_enter(mem0.mutex);
379         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
380         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
381         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
382         sqlite3GlobalConfig.m.xFree(p);
383         sqlite3_mutex_leave(mem0.mutex);
384       }else{
385         sqlite3GlobalConfig.m.xFree(p);
386       }
387     }
388   }
389 }
390 
391 /*
392 ** TRUE if p is a lookaside memory allocation from db
393 */
394 #ifndef SQLITE_OMIT_LOOKASIDE
395 static int isLookaside(sqlite3 *db, void *p){
396   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
397 }
398 #else
399 #define isLookaside(A,B) 0
400 #endif
401 
402 /*
403 ** Return the size of a memory allocation previously obtained from
404 ** sqlite3Malloc() or sqlite3_malloc().
405 */
406 int sqlite3MallocSize(void *p){
407   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
408   return sqlite3GlobalConfig.m.xSize(p);
409 }
410 int sqlite3DbMallocSize(sqlite3 *db, void *p){
411   assert( p!=0 );
412   if( db==0 || !isLookaside(db,p) ){
413 #if SQLITE_DEBUG
414     if( db==0 ){
415       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
416       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
417     }else{
418       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
419       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
420     }
421 #endif
422     return sqlite3GlobalConfig.m.xSize(p);
423   }else{
424     assert( sqlite3_mutex_held(db->mutex) );
425     return db->lookaside.sz;
426   }
427 }
428 sqlite3_uint64 sqlite3_msize(void *p){
429   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
430   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
431   return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
432 }
433 
434 /*
435 ** Free memory previously obtained from sqlite3Malloc().
436 */
437 void sqlite3_free(void *p){
438   if( p==0 ) return;  /* IMP: R-49053-54554 */
439   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
440   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
441   if( sqlite3GlobalConfig.bMemstat ){
442     sqlite3_mutex_enter(mem0.mutex);
443     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
444     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
445     sqlite3GlobalConfig.m.xFree(p);
446     sqlite3_mutex_leave(mem0.mutex);
447   }else{
448     sqlite3GlobalConfig.m.xFree(p);
449   }
450 }
451 
452 /*
453 ** Add the size of memory allocation "p" to the count in
454 ** *db->pnBytesFreed.
455 */
456 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
457   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
458 }
459 
460 /*
461 ** Free memory that might be associated with a particular database
462 ** connection.
463 */
464 void sqlite3DbFree(sqlite3 *db, void *p){
465   assert( db==0 || sqlite3_mutex_held(db->mutex) );
466   if( p==0 ) return;
467   if( db ){
468     if( db->pnBytesFreed ){
469       measureAllocationSize(db, p);
470       return;
471     }
472     if( isLookaside(db, p) ){
473       LookasideSlot *pBuf = (LookasideSlot*)p;
474 #if SQLITE_DEBUG
475       /* Trash all content in the buffer being freed */
476       memset(p, 0xaa, db->lookaside.sz);
477 #endif
478       pBuf->pNext = db->lookaside.pFree;
479       db->lookaside.pFree = pBuf;
480       db->lookaside.nOut--;
481       return;
482     }
483   }
484   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
485   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
486   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
487   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
488   sqlite3_free(p);
489 }
490 
491 /*
492 ** Change the size of an existing memory allocation
493 */
494 void *sqlite3Realloc(void *pOld, u64 nBytes){
495   int nOld, nNew, nDiff;
496   void *pNew;
497   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
498   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
499   if( pOld==0 ){
500     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
501   }
502   if( nBytes==0 ){
503     sqlite3_free(pOld); /* IMP: R-26507-47431 */
504     return 0;
505   }
506   if( nBytes>=0x7fffff00 ){
507     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
508     return 0;
509   }
510   nOld = sqlite3MallocSize(pOld);
511   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
512   ** argument to xRealloc is always a value returned by a prior call to
513   ** xRoundup. */
514   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
515   if( nOld==nNew ){
516     pNew = pOld;
517   }else if( sqlite3GlobalConfig.bMemstat ){
518     sqlite3_mutex_enter(mem0.mutex);
519     sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
520     nDiff = nNew - nOld;
521     if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
522           mem0.alarmThreshold-nDiff ){
523       sqlite3MallocAlarm(nDiff);
524     }
525     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
526     if( pNew==0 && mem0.alarmThreshold>0 ){
527       sqlite3MallocAlarm((int)nBytes);
528       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
529     }
530     if( pNew ){
531       nNew = sqlite3MallocSize(pNew);
532       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
533     }
534     sqlite3_mutex_leave(mem0.mutex);
535   }else{
536     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
537   }
538   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
539   return pNew;
540 }
541 
542 /*
543 ** The public interface to sqlite3Realloc.  Make sure that the memory
544 ** subsystem is initialized prior to invoking sqliteRealloc.
545 */
546 void *sqlite3_realloc(void *pOld, int n){
547 #ifndef SQLITE_OMIT_AUTOINIT
548   if( sqlite3_initialize() ) return 0;
549 #endif
550   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
551   return sqlite3Realloc(pOld, n);
552 }
553 void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
554 #ifndef SQLITE_OMIT_AUTOINIT
555   if( sqlite3_initialize() ) return 0;
556 #endif
557   return sqlite3Realloc(pOld, n);
558 }
559 
560 
561 /*
562 ** Allocate and zero memory.
563 */
564 void *sqlite3MallocZero(u64 n){
565   void *p = sqlite3Malloc(n);
566   if( p ){
567     memset(p, 0, (size_t)n);
568   }
569   return p;
570 }
571 
572 /*
573 ** Allocate and zero memory.  If the allocation fails, make
574 ** the mallocFailed flag in the connection pointer.
575 */
576 void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
577   void *p;
578   testcase( db==0 );
579   p = sqlite3DbMallocRaw(db, n);
580   if( p ) memset(p, 0, (size_t)n);
581   return p;
582 }
583 
584 
585 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
586 ** slower case when the allocation cannot be fulfilled using lookaside.
587 */
588 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
589   void *p;
590   assert( db!=0 );
591   p = sqlite3Malloc(n);
592   if( !p ) sqlite3OomFault(db);
593   sqlite3MemdebugSetType(p,
594          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
595   return p;
596 }
597 
598 /*
599 ** Allocate memory, either lookaside (if possible) or heap.
600 ** If the allocation fails, set the mallocFailed flag in
601 ** the connection pointer.
602 **
603 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
604 ** failure on the same database connection) then always return 0.
605 ** Hence for a particular database connection, once malloc starts
606 ** failing, it fails consistently until mallocFailed is reset.
607 ** This is an important assumption.  There are many places in the
608 ** code that do things like this:
609 **
610 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
611 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
612 **         if( b ) a[10] = 9;
613 **
614 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
615 ** that all prior mallocs (ex: "a") worked too.
616 **
617 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
618 ** not a NULL pointer.
619 */
620 void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
621   void *p;
622   if( db ) return sqlite3DbMallocRawNN(db, n);
623   p = sqlite3Malloc(n);
624   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
625   return p;
626 }
627 void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
628 #ifndef SQLITE_OMIT_LOOKASIDE
629   LookasideSlot *pBuf;
630   assert( db!=0 );
631   assert( sqlite3_mutex_held(db->mutex) );
632   assert( db->pnBytesFreed==0 );
633   if( db->lookaside.bDisable==0 ){
634     assert( db->mallocFailed==0 );
635     if( n>db->lookaside.sz ){
636       db->lookaside.anStat[1]++;
637     }else if( (pBuf = db->lookaside.pFree)==0 ){
638       db->lookaside.anStat[2]++;
639     }else{
640       db->lookaside.pFree = pBuf->pNext;
641       db->lookaside.nOut++;
642       db->lookaside.anStat[0]++;
643       if( db->lookaside.nOut>db->lookaside.mxOut ){
644         db->lookaside.mxOut = db->lookaside.nOut;
645       }
646       return (void*)pBuf;
647     }
648   }else if( db->mallocFailed ){
649     return 0;
650   }
651 #else
652   assert( db!=0 );
653   assert( sqlite3_mutex_held(db->mutex) );
654   assert( db->pnBytesFreed==0 );
655   if( db->mallocFailed ){
656     return 0;
657   }
658 #endif
659   return dbMallocRawFinish(db, n);
660 }
661 
662 /* Forward declaration */
663 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
664 
665 /*
666 ** Resize the block of memory pointed to by p to n bytes. If the
667 ** resize fails, set the mallocFailed flag in the connection object.
668 */
669 void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
670   assert( db!=0 );
671   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
672   assert( sqlite3_mutex_held(db->mutex) );
673   if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
674   return dbReallocFinish(db, p, n);
675 }
676 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
677   void *pNew = 0;
678   assert( db!=0 );
679   assert( p!=0 );
680   if( db->mallocFailed==0 ){
681     if( isLookaside(db, p) ){
682       pNew = sqlite3DbMallocRawNN(db, n);
683       if( pNew ){
684         memcpy(pNew, p, db->lookaside.sz);
685         sqlite3DbFree(db, p);
686       }
687     }else{
688       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
689       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
690       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
691       pNew = sqlite3_realloc64(p, n);
692       if( !pNew ){
693         sqlite3OomFault(db);
694       }
695       sqlite3MemdebugSetType(pNew,
696             (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
697     }
698   }
699   return pNew;
700 }
701 
702 /*
703 ** Attempt to reallocate p.  If the reallocation fails, then free p
704 ** and set the mallocFailed flag in the database connection.
705 */
706 void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
707   void *pNew;
708   pNew = sqlite3DbRealloc(db, p, n);
709   if( !pNew ){
710     sqlite3DbFree(db, p);
711   }
712   return pNew;
713 }
714 
715 /*
716 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
717 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
718 ** is because when memory debugging is turned on, these two functions are
719 ** called via macros that record the current file and line number in the
720 ** ThreadData structure.
721 */
722 char *sqlite3DbStrDup(sqlite3 *db, const char *z){
723   char *zNew;
724   size_t n;
725   if( z==0 ){
726     return 0;
727   }
728   n = strlen(z) + 1;
729   zNew = sqlite3DbMallocRaw(db, n);
730   if( zNew ){
731     memcpy(zNew, z, n);
732   }
733   return zNew;
734 }
735 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
736   char *zNew;
737   assert( db!=0 );
738   if( z==0 ){
739     return 0;
740   }
741   assert( (n&0x7fffffff)==n );
742   zNew = sqlite3DbMallocRawNN(db, n+1);
743   if( zNew ){
744     memcpy(zNew, z, (size_t)n);
745     zNew[n] = 0;
746   }
747   return zNew;
748 }
749 
750 /*
751 ** Free any prior content in *pz and replace it with a copy of zNew.
752 */
753 void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
754   sqlite3DbFree(db, *pz);
755   *pz = sqlite3DbStrDup(db, zNew);
756 }
757 
758 /*
759 ** Call this routine to record the fact that an OOM (out-of-memory) error
760 ** has happened.  This routine will set db->mallocFailed, and also
761 ** temporarily disable the lookaside memory allocator and interrupt
762 ** any running VDBEs.
763 */
764 void sqlite3OomFault(sqlite3 *db){
765   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
766     db->mallocFailed = 1;
767     if( db->nVdbeExec>0 ){
768       db->u1.isInterrupted = 1;
769     }
770     db->lookaside.bDisable++;
771   }
772 }
773 
774 /*
775 ** This routine reactivates the memory allocator and clears the
776 ** db->mallocFailed flag as necessary.
777 **
778 ** The memory allocator is not restarted if there are running
779 ** VDBEs.
780 */
781 void sqlite3OomClear(sqlite3 *db){
782   if( db->mallocFailed && db->nVdbeExec==0 ){
783     db->mallocFailed = 0;
784     db->u1.isInterrupted = 0;
785     assert( db->lookaside.bDisable>0 );
786     db->lookaside.bDisable--;
787   }
788 }
789 
790 /*
791 ** Take actions at the end of an API call to indicate an OOM error
792 */
793 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
794   sqlite3OomClear(db);
795   sqlite3Error(db, SQLITE_NOMEM);
796   return SQLITE_NOMEM_BKPT;
797 }
798 
799 /*
800 ** This function must be called before exiting any API function (i.e.
801 ** returning control to the user) that has called sqlite3_malloc or
802 ** sqlite3_realloc.
803 **
804 ** The returned value is normally a copy of the second argument to this
805 ** function. However, if a malloc() failure has occurred since the previous
806 ** invocation SQLITE_NOMEM is returned instead.
807 **
808 ** If an OOM as occurred, then the connection error-code (the value
809 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
810 */
811 int sqlite3ApiExit(sqlite3* db, int rc){
812   /* If the db handle must hold the connection handle mutex here.
813   ** Otherwise the read (and possible write) of db->mallocFailed
814   ** is unsafe, as is the call to sqlite3Error().
815   */
816   assert( db!=0 );
817   assert( sqlite3_mutex_held(db->mutex) );
818   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
819     return apiOomError(db);
820   }
821   return rc & db->errMask;
822 }
823