interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / malloc.c

898 lines · 26521 bytes Raw Blame History
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*/
23int 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*/
45static 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*/
62sqlite3_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*/
72int 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*/
95sqlite3_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}
120void 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*/
137sqlite3_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*/
159int 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*/
180int sqlite3HeapNearlyFull(void){
181 return AtomicLoad(&mem0.nearlyFull);
182}
183
184/*
185** Deinitialize the memory allocation subsystem.
186*/
187void 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*/
197sqlite3_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*/
208sqlite3_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*/
217static 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#ifdef SQLITE_DEBUG
225/*
226** This routine is called whenever an out-of-memory condition is seen,
227** It's only purpose to to serve as a breakpoint for gdb or similar
228** code debuggers when working on out-of-memory conditions, for example
229** caused by PRAGMA hard_heap_limit=N.
230*/
231static SQLITE_NOINLINE void test_oom_breakpoint(u64 n){
232 static u64 nOomFault = 0;
233 nOomFault += n;
234 /* The assert() is never reached in a human lifetime. It is here mostly
235 ** to prevent code optimizers from optimizing out this function. */
236 assert( (nOomFault>>32) < 0xffffffff );
237}
238#else
239# define test_oom_breakpoint(X) /* No-op for production builds */
240#endif
241
242/*
243** Do a memory allocation with statistics and alarms. Assume the
244** lock is already held.
245*/
246static void mallocWithAlarm(int n, void **pp){
247 void *p;
248 int nFull;
249 assert( sqlite3_mutex_held(mem0.mutex) );
250 assert( n>0 );
251
252 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
253 ** implementation of malloc_good_size(), which must be called in debug
254 ** mode and specifically when the DMD "Dark Matter Detector" is enabled
255 ** or else a crash results. Hence, do not attempt to optimize out the
256 ** following xRoundup() call. */
257 nFull = sqlite3GlobalConfig.m.xRoundup(n);
258
259 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
260 if( mem0.alarmThreshold>0 ){
261 sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
262 if( nUsed >= mem0.alarmThreshold - nFull ){
263 AtomicStore(&mem0.nearlyFull, 1);
264 sqlite3MallocAlarm(nFull);
265 if( mem0.hardLimit ){
266 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
267 if( nUsed >= mem0.hardLimit - nFull ){
268 test_oom_breakpoint(1);
269 *pp = 0;
270 return;
271 }
272 }
273 }else{
274 AtomicStore(&mem0.nearlyFull, 0);
275 }
276 }
277 p = sqlite3GlobalConfig.m.xMalloc(nFull);
278#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
279 if( p==0 && mem0.alarmThreshold>0 ){
280 sqlite3MallocAlarm(nFull);
281 p = sqlite3GlobalConfig.m.xMalloc(nFull);
282 }
283#endif
284 if( p ){
285 nFull = sqlite3MallocSize(p);
286 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
287 sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
288 }
289 *pp = p;
290}
291
292/*
293** Allocate memory. This routine is like sqlite3_malloc() except that it
294** assumes the memory subsystem has already been initialized.
295*/
296void *sqlite3Malloc(u64 n){
297 void *p;
298 if( n==0 || n>SQLITE_MAX_ALLOCATION_SIZE ){
299 p = 0;
300 }else if( sqlite3GlobalConfig.bMemstat ){
301 sqlite3_mutex_enter(mem0.mutex);
302 mallocWithAlarm((int)n, &p);
303 sqlite3_mutex_leave(mem0.mutex);
304 }else{
305 p = sqlite3GlobalConfig.m.xMalloc((int)n);
306 }
307 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
308 return p;
309}
310
311/*
312** This version of the memory allocation is for use by the application.
313** First make sure the memory subsystem is initialized, then do the
314** allocation.
315*/
316void *sqlite3_malloc(int n){
317#ifndef SQLITE_OMIT_AUTOINIT
318 if( sqlite3_initialize() ) return 0;
319#endif
320 return n<=0 ? 0 : sqlite3Malloc(n);
321}
322void *sqlite3_malloc64(sqlite3_uint64 n){
323#ifndef SQLITE_OMIT_AUTOINIT
324 if( sqlite3_initialize() ) return 0;
325#endif
326 return sqlite3Malloc(n);
327}
328
329/*
330** TRUE if p is a lookaside memory allocation from db
331*/
332#ifndef SQLITE_OMIT_LOOKASIDE
333static int isLookaside(sqlite3 *db, const void *p){
334 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pTrueEnd);
335}
336#else
337#define isLookaside(A,B) 0
338#endif
339
340/*
341** Return the size of a memory allocation previously obtained from
342** sqlite3Malloc() or sqlite3_malloc().
343*/
344int sqlite3MallocSize(const void *p){
345 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
346 return sqlite3GlobalConfig.m.xSize((void*)p);
347}
348static int lookasideMallocSize(sqlite3 *db, const void *p){
349#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
350 return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
351#else
352 return db->lookaside.szTrue;
353#endif
354}
355int sqlite3DbMallocSize(sqlite3 *db, const void *p){
356 assert( p!=0 );
357#ifdef SQLITE_DEBUG
358 if( db==0 ){
359 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
360 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
361 }else if( !isLookaside(db,p) ){
362 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
363 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
364 }
365#endif
366 if( db ){
367 if( ((uptr)p)<(uptr)(db->lookaside.pTrueEnd) ){
368#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
369 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
370 assert( sqlite3_mutex_held(db->mutex) );
371 return LOOKASIDE_SMALL;
372 }
373#endif
374 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
375 assert( sqlite3_mutex_held(db->mutex) );
376 return db->lookaside.szTrue;
377 }
378 }
379 }
380 return sqlite3GlobalConfig.m.xSize((void*)p);
381}
382sqlite3_uint64 sqlite3_msize(void *p){
383 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
384 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
385 return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
386}
387
388/*
389** Free memory previously obtained from sqlite3Malloc().
390*/
391void sqlite3_free(void *p){
392 if( p==0 ) return; /* IMP: R-49053-54554 */
393 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
394 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
395 if( sqlite3GlobalConfig.bMemstat ){
396 sqlite3_mutex_enter(mem0.mutex);
397 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
398 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
399 sqlite3GlobalConfig.m.xFree(p);
400 sqlite3_mutex_leave(mem0.mutex);
401 }else{
402 sqlite3GlobalConfig.m.xFree(p);
403 }
404}
405
406/*
407** Add the size of memory allocation "p" to the count in
408** *db->pnBytesFreed.
409*/
410static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
411 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
412}
413
414/*
415** Free memory that might be associated with a particular database
416** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
417** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
418*/
419void sqlite3DbFreeNN(sqlite3 *db, void *p){
420 assert( db==0 || sqlite3_mutex_held(db->mutex) );
421 assert( p!=0 );
422 if( db ){
423 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
424#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
425 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
426 LookasideSlot *pBuf = (LookasideSlot*)p;
427 assert( db->pnBytesFreed==0 );
428#ifdef SQLITE_DEBUG
429 memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */
430#endif
431 pBuf->pNext = db->lookaside.pSmallFree;
432 db->lookaside.pSmallFree = pBuf;
433 return;
434 }
435#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
436 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
437 LookasideSlot *pBuf = (LookasideSlot*)p;
438 assert( db->pnBytesFreed==0 );
439#ifdef SQLITE_DEBUG
440 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
441#endif
442 pBuf->pNext = db->lookaside.pFree;
443 db->lookaside.pFree = pBuf;
444 return;
445 }
446 }
447 if( db->pnBytesFreed ){
448 measureAllocationSize(db, p);
449 return;
450 }
451 }
452 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
453 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
454 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
455 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
456 sqlite3_free(p);
457}
458void sqlite3DbNNFreeNN(sqlite3 *db, void *p){
459 assert( db!=0 );
460 assert( sqlite3_mutex_held(db->mutex) );
461 assert( p!=0 );
462 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
463#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
464 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
465 LookasideSlot *pBuf = (LookasideSlot*)p;
466 assert( db->pnBytesFreed==0 );
467#ifdef SQLITE_DEBUG
468 memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */
469#endif
470 pBuf->pNext = db->lookaside.pSmallFree;
471 db->lookaside.pSmallFree = pBuf;
472 return;
473 }
474#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
475 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
476 LookasideSlot *pBuf = (LookasideSlot*)p;
477 assert( db->pnBytesFreed==0 );
478#ifdef SQLITE_DEBUG
479 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
480#endif
481 pBuf->pNext = db->lookaside.pFree;
482 db->lookaside.pFree = pBuf;
483 return;
484 }
485 }
486 if( db->pnBytesFreed ){
487 measureAllocationSize(db, p);
488 return;
489 }
490 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
491 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
492 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
493 sqlite3_free(p);
494}
495void sqlite3DbFree(sqlite3 *db, void *p){
496 assert( db==0 || sqlite3_mutex_held(db->mutex) );
497 if( p ) sqlite3DbFreeNN(db, p);
498}
499
500/*
501** Change the size of an existing memory allocation
502*/
503void *sqlite3Realloc(void *pOld, u64 nBytes){
504 int nOld, nNew, nDiff;
505 void *pNew;
506 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
507 assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
508 if( pOld==0 ){
509 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
510 }
511 if( nBytes==0 ){
512 sqlite3_free(pOld); /* IMP: R-26507-47431 */
513 return 0;
514 }
515 if( nBytes>SQLITE_MAX_ALLOCATION_SIZE ){
516 return 0;
517 }
518 nOld = sqlite3MallocSize(pOld);
519 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
520 ** argument to xRealloc is always a value returned by a prior call to
521 ** xRoundup. */
522 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
523 if( nOld==nNew ){
524 pNew = pOld;
525 }else if( sqlite3GlobalConfig.bMemstat ){
526 sqlite3_int64 nUsed;
527 sqlite3_mutex_enter(mem0.mutex);
528 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
529 nDiff = nNew - nOld;
530 if( nDiff>0 && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)) >=
531 mem0.alarmThreshold-nDiff ){
532 sqlite3MallocAlarm(nDiff);
533 if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){
534 sqlite3_mutex_leave(mem0.mutex);
535 test_oom_breakpoint(1);
536 return 0;
537 }
538 }
539 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
540#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
541 if( pNew==0 && mem0.alarmThreshold>0 ){
542 sqlite3MallocAlarm((int)nBytes);
543 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
544 }
545#endif
546 if( pNew ){
547 nNew = sqlite3MallocSize(pNew);
548 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
549 }
550 sqlite3_mutex_leave(mem0.mutex);
551 }else{
552 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
553 }
554 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
555 return pNew;
556}
557
558/*
559** The public interface to sqlite3Realloc. Make sure that the memory
560** subsystem is initialized prior to invoking sqliteRealloc.
561*/
562void *sqlite3_realloc(void *pOld, int n){
563#ifndef SQLITE_OMIT_AUTOINIT
564 if( sqlite3_initialize() ) return 0;
565#endif
566 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
567 return sqlite3Realloc(pOld, n);
568}
569void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
570#ifndef SQLITE_OMIT_AUTOINIT
571 if( sqlite3_initialize() ) return 0;
572#endif
573 return sqlite3Realloc(pOld, n);
574}
575
576
577/*
578** Allocate and zero memory.
579*/
580void *sqlite3MallocZero(u64 n){
581 void *p = sqlite3Malloc(n);
582 if( p ){
583 memset(p, 0, (size_t)n);
584 }
585 return p;
586}
587
588/*
589** Allocate and zero memory. If the allocation fails, make
590** the mallocFailed flag in the connection pointer.
591*/
592void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
593 void *p;
594 testcase( db==0 );
595 p = sqlite3DbMallocRaw(db, n);
596 if( p ) memset(p, 0, (size_t)n);
597 return p;
598}
599
600
601/* Finish the work of sqlite3DbMallocRawNN for the unusual and
602** slower case when the allocation cannot be fulfilled using lookaside.
603*/
604static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
605 void *p;
606 assert( db!=0 );
607 p = sqlite3Malloc(n);
608 if( !p ) sqlite3OomFault(db);
609 sqlite3MemdebugSetType(p,
610 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
611 return p;
612}
613
614/*
615** Allocate memory, either lookaside (if possible) or heap.
616** If the allocation fails, set the mallocFailed flag in
617** the connection pointer.
618**
619** If db!=0 and db->mallocFailed is true (indicating a prior malloc
620** failure on the same database connection) then always return 0.
621** Hence for a particular database connection, once malloc starts
622** failing, it fails consistently until mallocFailed is reset.
623** This is an important assumption. There are many places in the
624** code that do things like this:
625**
626** int *a = (int*)sqlite3DbMallocRaw(db, 100);
627** int *b = (int*)sqlite3DbMallocRaw(db, 200);
628** if( b ) a[10] = 9;
629**
630** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
631** that all prior mallocs (ex: "a") worked too.
632**
633** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
634** not a NULL pointer.
635*/
636void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
637 void *p;
638 if( db ) return sqlite3DbMallocRawNN(db, n);
639 p = sqlite3Malloc(n);
640 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
641 return p;
642}
643void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
644#ifndef SQLITE_OMIT_LOOKASIDE
645 LookasideSlot *pBuf;
646 assert( db!=0 );
647 assert( sqlite3_mutex_held(db->mutex) );
648 assert( db->pnBytesFreed==0 );
649 if( n>db->lookaside.sz ){
650 if( !db->lookaside.bDisable ){
651 db->lookaside.anStat[1]++;
652 }else if( db->mallocFailed ){
653 return 0;
654 }
655 return dbMallocRawFinish(db, n);
656 }
657#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
658 if( n<=LOOKASIDE_SMALL ){
659 if( (pBuf = db->lookaside.pSmallFree)!=0 ){
660 db->lookaside.pSmallFree = pBuf->pNext;
661 db->lookaside.anStat[0]++;
662 return (void*)pBuf;
663 }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
664 db->lookaside.pSmallInit = pBuf->pNext;
665 db->lookaside.anStat[0]++;
666 return (void*)pBuf;
667 }
668 }
669#endif
670 if( (pBuf = db->lookaside.pFree)!=0 ){
671 db->lookaside.pFree = pBuf->pNext;
672 db->lookaside.anStat[0]++;
673 return (void*)pBuf;
674 }else if( (pBuf = db->lookaside.pInit)!=0 ){
675 db->lookaside.pInit = pBuf->pNext;
676 db->lookaside.anStat[0]++;
677 return (void*)pBuf;
678 }else{
679 db->lookaside.anStat[2]++;
680 }
681#else
682 assert( db!=0 );
683 assert( sqlite3_mutex_held(db->mutex) );
684 assert( db->pnBytesFreed==0 );
685 if( db->mallocFailed ){
686 return 0;
687 }
688#endif
689 return dbMallocRawFinish(db, n);
690}
691
692/* Forward declaration */
693static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
694
695/*
696** Resize the block of memory pointed to by p to n bytes. If the
697** resize fails, set the mallocFailed flag in the connection object.
698*/
699void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
700 assert( db!=0 );
701 if( p==0 ) return sqlite3DbMallocRawNN(db, n);
702 assert( sqlite3_mutex_held(db->mutex) );
703 if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
704#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
705 if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
706 if( n<=LOOKASIDE_SMALL ) return p;
707 }else
708#endif
709 if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
710 if( n<=db->lookaside.szTrue ) return p;
711 }
712 }
713 return dbReallocFinish(db, p, n);
714}
715static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
716 void *pNew = 0;
717 assert( db!=0 );
718 assert( p!=0 );
719 if( db->mallocFailed==0 ){
720 if( isLookaside(db, p) ){
721 pNew = sqlite3DbMallocRawNN(db, n);
722 if( pNew ){
723 memcpy(pNew, p, lookasideMallocSize(db, p));
724 sqlite3DbFree(db, p);
725 }
726 }else{
727 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
728 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
729 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
730 pNew = sqlite3Realloc(p, n);
731 if( !pNew ){
732 sqlite3OomFault(db);
733 }
734 sqlite3MemdebugSetType(pNew,
735 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
736 }
737 }
738 return pNew;
739}
740
741/*
742** Attempt to reallocate p. If the reallocation fails, then free p
743** and set the mallocFailed flag in the database connection.
744*/
745void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
746 void *pNew;
747 pNew = sqlite3DbRealloc(db, p, n);
748 if( !pNew ){
749 sqlite3DbFree(db, p);
750 }
751 return pNew;
752}
753
754/*
755** Make a copy of a string in memory obtained from sqliteMalloc(). These
756** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
757** is because when memory debugging is turned on, these two functions are
758** called via macros that record the current file and line number in the
759** ThreadData structure.
760*/
761char *sqlite3DbStrDup(sqlite3 *db, const char *z){
762 char *zNew;
763 size_t n;
764 if( z==0 ){
765 return 0;
766 }
767 n = strlen(z) + 1;
768 zNew = sqlite3DbMallocRaw(db, n);
769 if( zNew ){
770 memcpy(zNew, z, n);
771 }
772 return zNew;
773}
774char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
775 char *zNew;
776 assert( db!=0 );
777 assert( z!=0 || n==0 );
778 assert( (n&0x7fffffff)==n );
779 zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0;
780 if( zNew ){
781 memcpy(zNew, z, (size_t)n);
782 zNew[n] = 0;
783 }
784 return zNew;
785}
786
787/*
788** The text between zStart and zEnd represents a phrase within a larger
789** SQL statement. Make a copy of this phrase in space obtained form
790** sqlite3DbMalloc(). Omit leading and trailing whitespace.
791*/
792char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
793 int n;
794#ifdef SQLITE_DEBUG
795 /* Because of the way the parser works, the span is guaranteed to contain
796 ** at least one non-space character */
797 for(n=0; sqlite3Isspace(zStart[n]); n++){ assert( &zStart[n]<zEnd ); }
798#endif
799 while( sqlite3Isspace(zStart[0]) ) zStart++;
800 n = (int)(zEnd - zStart);
801 while( sqlite3Isspace(zStart[n-1]) ) n--;
802 return sqlite3DbStrNDup(db, zStart, n);
803}
804
805/*
806** Free any prior content in *pz and replace it with a copy of zNew.
807*/
808void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
809 char *z = sqlite3DbStrDup(db, zNew);
810 sqlite3DbFree(db, *pz);
811 *pz = z;
812}
813
814/*
815** Call this routine to record the fact that an OOM (out-of-memory) error
816** has happened. This routine will set db->mallocFailed, and also
817** temporarily disable the lookaside memory allocator and interrupt
818** any running VDBEs.
819**
820** Always return a NULL pointer so that this routine can be invoked using
821**
822** return sqlite3OomFault(db);
823**
824** and thereby avoid unnecessary stack frame allocations for the overwhelmingly
825** common case where no OOM occurs.
826*/
827void *sqlite3OomFault(sqlite3 *db){
828 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
829 db->mallocFailed = 1;
830 if( db->nVdbeExec>0 ){
831 AtomicStore(&db->u1.isInterrupted, 1);
832 }
833 DisableLookaside;
834 if( db->pParse ){
835 Parse *pParse;
836 sqlite3ErrorMsg(db->pParse, "out of memory");
837 db->pParse->rc = SQLITE_NOMEM_BKPT;
838 for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){
839 pParse->nErr++;
840 pParse->rc = SQLITE_NOMEM;
841 }
842 }
843 }
844 return 0;
845}
846
847/*
848** This routine reactivates the memory allocator and clears the
849** db->mallocFailed flag as necessary.
850**
851** The memory allocator is not restarted if there are running
852** VDBEs.
853*/
854void sqlite3OomClear(sqlite3 *db){
855 if( db->mallocFailed && db->nVdbeExec==0 ){
856 db->mallocFailed = 0;
857 AtomicStore(&db->u1.isInterrupted, 0);
858 assert( db->lookaside.bDisable>0 );
859 EnableLookaside;
860 }
861}
862
863/*
864** Take actions at the end of an API call to deal with error codes.
865*/
866static SQLITE_NOINLINE int apiHandleError(sqlite3 *db, int rc){
867 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
868 sqlite3OomClear(db);
869 sqlite3Error(db, SQLITE_NOMEM);
870 return SQLITE_NOMEM_BKPT;
871 }
872 return rc & db->errMask;
873}
874
875/*
876** This function must be called before exiting any API function (i.e.
877** returning control to the user) that has called sqlite3_malloc or
878** sqlite3_realloc.
879**
880** The returned value is normally a copy of the second argument to this
881** function. However, if a malloc() failure has occurred since the previous
882** invocation SQLITE_NOMEM is returned instead.
883**
884** If an OOM as occurred, then the connection error-code (the value
885** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
886*/
887int sqlite3ApiExit(sqlite3* db, int rc){
888 /* If the db handle must hold the connection handle mutex here.
889 ** Otherwise the read (and possible write) of db->mallocFailed
890 ** is unsafe, as is the call to sqlite3Error().
891 */
892 assert( db!=0 );
893 assert( sqlite3_mutex_held(db->mutex) );
894 if( db->mallocFailed || rc ){
895 return apiHandleError(db, rc);
896 }
897 return 0;
898}