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