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