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; 223 assert( sqlite3_mutex_held(mem0.mutex) ); 224 assert( n>0 ); 225 226 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal 227 ** implementation of malloc_good_size(), which must be called in debug 228 ** mode and specifically when the DMD "Dark Matter Detector" is enabled 229 ** or else a crash results. Hence, do not attempt to optimize out the 230 ** following xRoundup() call. */ 231 nFull = sqlite3GlobalConfig.m.xRoundup(n); 232 233 #ifdef SQLITE_MAX_MEMORY 234 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){ 235 *pp = 0; 236 return; 237 } 238 #endif 239 240 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); 241 if( mem0.alarmThreshold>0 ){ 242 sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); 243 if( nUsed >= mem0.alarmThreshold - nFull ){ 244 mem0.nearlyFull = 1; 245 sqlite3MallocAlarm(nFull); 246 }else{ 247 mem0.nearlyFull = 0; 248 } 249 } 250 p = sqlite3GlobalConfig.m.xMalloc(nFull); 251 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT 252 if( p==0 && mem0.alarmThreshold>0 ){ 253 sqlite3MallocAlarm(nFull); 254 p = sqlite3GlobalConfig.m.xMalloc(nFull); 255 } 256 #endif 257 if( p ){ 258 nFull = sqlite3MallocSize(p); 259 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); 260 sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); 261 } 262 *pp = p; 263 } 264 265 /* 266 ** Allocate memory. This routine is like sqlite3_malloc() except that it 267 ** assumes the memory subsystem has already been initialized. 268 */ 269 void *sqlite3Malloc(u64 n){ 270 void *p; 271 if( n==0 || n>=0x7fffff00 ){ 272 /* A memory allocation of a number of bytes which is near the maximum 273 ** signed integer value might cause an integer overflow inside of the 274 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving 275 ** 255 bytes of overhead. SQLite itself will never use anything near 276 ** this amount. The only way to reach the limit is with sqlite3_malloc() */ 277 p = 0; 278 }else if( sqlite3GlobalConfig.bMemstat ){ 279 sqlite3_mutex_enter(mem0.mutex); 280 mallocWithAlarm((int)n, &p); 281 sqlite3_mutex_leave(mem0.mutex); 282 }else{ 283 p = sqlite3GlobalConfig.m.xMalloc((int)n); 284 } 285 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ 286 return p; 287 } 288 289 /* 290 ** This version of the memory allocation is for use by the application. 291 ** First make sure the memory subsystem is initialized, then do the 292 ** allocation. 293 */ 294 void *sqlite3_malloc(int n){ 295 #ifndef SQLITE_OMIT_AUTOINIT 296 if( sqlite3_initialize() ) return 0; 297 #endif 298 return n<=0 ? 0 : sqlite3Malloc(n); 299 } 300 void *sqlite3_malloc64(sqlite3_uint64 n){ 301 #ifndef SQLITE_OMIT_AUTOINIT 302 if( sqlite3_initialize() ) return 0; 303 #endif 304 return sqlite3Malloc(n); 305 } 306 307 /* 308 ** Each thread may only have a single outstanding allocation from 309 ** xScratchMalloc(). We verify this constraint in the single-threaded 310 ** case by setting scratchAllocOut to 1 when an allocation 311 ** is outstanding clearing it when the allocation is freed. 312 */ 313 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 314 static int scratchAllocOut = 0; 315 #endif 316 317 318 /* 319 ** Allocate memory that is to be used and released right away. 320 ** This routine is similar to alloca() in that it is not intended 321 ** for situations where the memory might be held long-term. This 322 ** routine is intended to get memory to old large transient data 323 ** structures that would not normally fit on the stack of an 324 ** embedded processor. 325 */ 326 void *sqlite3ScratchMalloc(int n){ 327 void *p; 328 assert( n>0 ); 329 330 sqlite3_mutex_enter(mem0.mutex); 331 sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n); 332 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ 333 p = mem0.pScratchFree; 334 mem0.pScratchFree = mem0.pScratchFree->pNext; 335 mem0.nScratchFree--; 336 sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1); 337 sqlite3_mutex_leave(mem0.mutex); 338 }else{ 339 sqlite3_mutex_leave(mem0.mutex); 340 p = sqlite3Malloc(n); 341 if( sqlite3GlobalConfig.bMemstat && p ){ 342 sqlite3_mutex_enter(mem0.mutex); 343 sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p)); 344 sqlite3_mutex_leave(mem0.mutex); 345 } 346 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); 347 } 348 assert( sqlite3_mutex_notheld(mem0.mutex) ); 349 350 351 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 352 /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch 353 ** buffers per thread. 354 ** 355 ** This can only be checked in single-threaded mode. 356 */ 357 assert( scratchAllocOut==0 ); 358 if( p ) scratchAllocOut++; 359 #endif 360 361 return p; 362 } 363 void sqlite3ScratchFree(void *p){ 364 if( p ){ 365 366 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 367 /* Verify that no more than two scratch allocation per thread 368 ** is outstanding at one time. (This is only checked in the 369 ** single-threaded case since checking in the multi-threaded case 370 ** would be much more complicated.) */ 371 assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); 372 scratchAllocOut--; 373 #endif 374 375 if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){ 376 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */ 377 ScratchFreeslot *pSlot; 378 pSlot = (ScratchFreeslot*)p; 379 sqlite3_mutex_enter(mem0.mutex); 380 pSlot->pNext = mem0.pScratchFree; 381 mem0.pScratchFree = pSlot; 382 mem0.nScratchFree++; 383 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); 384 sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1); 385 sqlite3_mutex_leave(mem0.mutex); 386 }else{ 387 /* Release memory back to the heap */ 388 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); 389 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) ); 390 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 391 if( sqlite3GlobalConfig.bMemstat ){ 392 int iSize = sqlite3MallocSize(p); 393 sqlite3_mutex_enter(mem0.mutex); 394 sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize); 395 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize); 396 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); 397 sqlite3GlobalConfig.m.xFree(p); 398 sqlite3_mutex_leave(mem0.mutex); 399 }else{ 400 sqlite3GlobalConfig.m.xFree(p); 401 } 402 } 403 } 404 } 405 406 /* 407 ** TRUE if p is a lookaside memory allocation from db 408 */ 409 #ifndef SQLITE_OMIT_LOOKASIDE 410 static int isLookaside(sqlite3 *db, void *p){ 411 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd); 412 } 413 #else 414 #define isLookaside(A,B) 0 415 #endif 416 417 /* 418 ** Return the size of a memory allocation previously obtained from 419 ** sqlite3Malloc() or sqlite3_malloc(). 420 */ 421 int sqlite3MallocSize(void *p){ 422 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 423 return sqlite3GlobalConfig.m.xSize(p); 424 } 425 int sqlite3DbMallocSize(sqlite3 *db, void *p){ 426 assert( p!=0 ); 427 if( db==0 || !isLookaside(db,p) ){ 428 #ifdef SQLITE_DEBUG 429 if( db==0 ){ 430 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 431 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 432 }else{ 433 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 434 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 435 } 436 #endif 437 return sqlite3GlobalConfig.m.xSize(p); 438 }else{ 439 assert( sqlite3_mutex_held(db->mutex) ); 440 return db->lookaside.sz; 441 } 442 } 443 sqlite3_uint64 sqlite3_msize(void *p){ 444 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 445 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 446 return p ? sqlite3GlobalConfig.m.xSize(p) : 0; 447 } 448 449 /* 450 ** Free memory previously obtained from sqlite3Malloc(). 451 */ 452 void sqlite3_free(void *p){ 453 if( p==0 ) return; /* IMP: R-49053-54554 */ 454 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 455 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 456 if( sqlite3GlobalConfig.bMemstat ){ 457 sqlite3_mutex_enter(mem0.mutex); 458 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); 459 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); 460 sqlite3GlobalConfig.m.xFree(p); 461 sqlite3_mutex_leave(mem0.mutex); 462 }else{ 463 sqlite3GlobalConfig.m.xFree(p); 464 } 465 } 466 467 /* 468 ** Add the size of memory allocation "p" to the count in 469 ** *db->pnBytesFreed. 470 */ 471 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ 472 *db->pnBytesFreed += sqlite3DbMallocSize(db,p); 473 } 474 475 /* 476 ** Free memory that might be associated with a particular database 477 ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op. 478 ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL. 479 */ 480 void sqlite3DbFreeNN(sqlite3 *db, void *p){ 481 assert( db==0 || sqlite3_mutex_held(db->mutex) ); 482 assert( p!=0 ); 483 if( db ){ 484 if( db->pnBytesFreed ){ 485 measureAllocationSize(db, p); 486 return; 487 } 488 if( isLookaside(db, p) ){ 489 LookasideSlot *pBuf = (LookasideSlot*)p; 490 #ifdef SQLITE_DEBUG 491 /* Trash all content in the buffer being freed */ 492 memset(p, 0xaa, db->lookaside.sz); 493 #endif 494 pBuf->pNext = db->lookaside.pFree; 495 db->lookaside.pFree = pBuf; 496 db->lookaside.nOut--; 497 return; 498 } 499 } 500 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 501 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 502 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); 503 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 504 sqlite3_free(p); 505 } 506 void sqlite3DbFree(sqlite3 *db, void *p){ 507 assert( db==0 || sqlite3_mutex_held(db->mutex) ); 508 if( p ) sqlite3DbFreeNN(db, p); 509 } 510 511 /* 512 ** Change the size of an existing memory allocation 513 */ 514 void *sqlite3Realloc(void *pOld, u64 nBytes){ 515 int nOld, nNew, nDiff; 516 void *pNew; 517 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); 518 assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); 519 if( pOld==0 ){ 520 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ 521 } 522 if( nBytes==0 ){ 523 sqlite3_free(pOld); /* IMP: R-26507-47431 */ 524 return 0; 525 } 526 if( nBytes>=0x7fffff00 ){ 527 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ 528 return 0; 529 } 530 nOld = sqlite3MallocSize(pOld); 531 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second 532 ** argument to xRealloc is always a value returned by a prior call to 533 ** xRoundup. */ 534 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); 535 if( nOld==nNew ){ 536 pNew = pOld; 537 }else if( sqlite3GlobalConfig.bMemstat ){ 538 sqlite3_mutex_enter(mem0.mutex); 539 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); 540 nDiff = nNew - nOld; 541 if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 542 mem0.alarmThreshold-nDiff ){ 543 sqlite3MallocAlarm(nDiff); 544 } 545 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); 546 if( pNew==0 && mem0.alarmThreshold>0 ){ 547 sqlite3MallocAlarm((int)nBytes); 548 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); 549 } 550 if( pNew ){ 551 nNew = sqlite3MallocSize(pNew); 552 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); 553 } 554 sqlite3_mutex_leave(mem0.mutex); 555 }else{ 556 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); 557 } 558 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ 559 return pNew; 560 } 561 562 /* 563 ** The public interface to sqlite3Realloc. Make sure that the memory 564 ** subsystem is initialized prior to invoking sqliteRealloc. 565 */ 566 void *sqlite3_realloc(void *pOld, int n){ 567 #ifndef SQLITE_OMIT_AUTOINIT 568 if( sqlite3_initialize() ) return 0; 569 #endif 570 if( n<0 ) n = 0; /* IMP: R-26507-47431 */ 571 return sqlite3Realloc(pOld, n); 572 } 573 void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ 574 #ifndef SQLITE_OMIT_AUTOINIT 575 if( sqlite3_initialize() ) return 0; 576 #endif 577 return sqlite3Realloc(pOld, n); 578 } 579 580 581 /* 582 ** Allocate and zero memory. 583 */ 584 void *sqlite3MallocZero(u64 n){ 585 void *p = sqlite3Malloc(n); 586 if( p ){ 587 memset(p, 0, (size_t)n); 588 } 589 return p; 590 } 591 592 /* 593 ** Allocate and zero memory. If the allocation fails, make 594 ** the mallocFailed flag in the connection pointer. 595 */ 596 void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ 597 void *p; 598 testcase( db==0 ); 599 p = sqlite3DbMallocRaw(db, n); 600 if( p ) memset(p, 0, (size_t)n); 601 return p; 602 } 603 604 605 /* Finish the work of sqlite3DbMallocRawNN for the unusual and 606 ** slower case when the allocation cannot be fulfilled using lookaside. 607 */ 608 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ 609 void *p; 610 assert( db!=0 ); 611 p = sqlite3Malloc(n); 612 if( !p ) sqlite3OomFault(db); 613 sqlite3MemdebugSetType(p, 614 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); 615 return p; 616 } 617 618 /* 619 ** Allocate memory, either lookaside (if possible) or heap. 620 ** If the allocation fails, set the mallocFailed flag in 621 ** the connection pointer. 622 ** 623 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc 624 ** failure on the same database connection) then always return 0. 625 ** Hence for a particular database connection, once malloc starts 626 ** failing, it fails consistently until mallocFailed is reset. 627 ** This is an important assumption. There are many places in the 628 ** code that do things like this: 629 ** 630 ** int *a = (int*)sqlite3DbMallocRaw(db, 100); 631 ** int *b = (int*)sqlite3DbMallocRaw(db, 200); 632 ** if( b ) a[10] = 9; 633 ** 634 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed 635 ** that all prior mallocs (ex: "a") worked too. 636 ** 637 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is 638 ** not a NULL pointer. 639 */ 640 void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ 641 void *p; 642 if( db ) return sqlite3DbMallocRawNN(db, n); 643 p = sqlite3Malloc(n); 644 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 645 return p; 646 } 647 void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ 648 #ifndef SQLITE_OMIT_LOOKASIDE 649 LookasideSlot *pBuf; 650 assert( db!=0 ); 651 assert( sqlite3_mutex_held(db->mutex) ); 652 assert( db->pnBytesFreed==0 ); 653 if( db->lookaside.bDisable==0 ){ 654 assert( db->mallocFailed==0 ); 655 if( n>db->lookaside.sz ){ 656 db->lookaside.anStat[1]++; 657 }else if( (pBuf = db->lookaside.pFree)==0 ){ 658 db->lookaside.anStat[2]++; 659 }else{ 660 db->lookaside.pFree = pBuf->pNext; 661 db->lookaside.nOut++; 662 db->lookaside.anStat[0]++; 663 if( db->lookaside.nOut>db->lookaside.mxOut ){ 664 db->lookaside.mxOut = db->lookaside.nOut; 665 } 666 return (void*)pBuf; 667 } 668 }else if( db->mallocFailed ){ 669 return 0; 670 } 671 #else 672 assert( db!=0 ); 673 assert( sqlite3_mutex_held(db->mutex) ); 674 assert( db->pnBytesFreed==0 ); 675 if( db->mallocFailed ){ 676 return 0; 677 } 678 #endif 679 return dbMallocRawFinish(db, n); 680 } 681 682 /* Forward declaration */ 683 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n); 684 685 /* 686 ** Resize the block of memory pointed to by p to n bytes. If the 687 ** resize fails, set the mallocFailed flag in the connection object. 688 */ 689 void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ 690 assert( db!=0 ); 691 if( p==0 ) return sqlite3DbMallocRawNN(db, n); 692 assert( sqlite3_mutex_held(db->mutex) ); 693 if( isLookaside(db,p) && n<=db->lookaside.sz ) return p; 694 return dbReallocFinish(db, p, n); 695 } 696 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ 697 void *pNew = 0; 698 assert( db!=0 ); 699 assert( p!=0 ); 700 if( db->mallocFailed==0 ){ 701 if( isLookaside(db, p) ){ 702 pNew = sqlite3DbMallocRawNN(db, n); 703 if( pNew ){ 704 memcpy(pNew, p, db->lookaside.sz); 705 sqlite3DbFree(db, p); 706 } 707 }else{ 708 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 709 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 710 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 711 pNew = sqlite3_realloc64(p, n); 712 if( !pNew ){ 713 sqlite3OomFault(db); 714 } 715 sqlite3MemdebugSetType(pNew, 716 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); 717 } 718 } 719 return pNew; 720 } 721 722 /* 723 ** Attempt to reallocate p. If the reallocation fails, then free p 724 ** and set the mallocFailed flag in the database connection. 725 */ 726 void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ 727 void *pNew; 728 pNew = sqlite3DbRealloc(db, p, n); 729 if( !pNew ){ 730 sqlite3DbFree(db, p); 731 } 732 return pNew; 733 } 734 735 /* 736 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 737 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This 738 ** is because when memory debugging is turned on, these two functions are 739 ** called via macros that record the current file and line number in the 740 ** ThreadData structure. 741 */ 742 char *sqlite3DbStrDup(sqlite3 *db, const char *z){ 743 char *zNew; 744 size_t n; 745 if( z==0 ){ 746 return 0; 747 } 748 n = strlen(z) + 1; 749 zNew = sqlite3DbMallocRaw(db, n); 750 if( zNew ){ 751 memcpy(zNew, z, n); 752 } 753 return zNew; 754 } 755 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ 756 char *zNew; 757 assert( db!=0 ); 758 if( z==0 ){ 759 return 0; 760 } 761 assert( (n&0x7fffffff)==n ); 762 zNew = sqlite3DbMallocRawNN(db, n+1); 763 if( zNew ){ 764 memcpy(zNew, z, (size_t)n); 765 zNew[n] = 0; 766 } 767 return zNew; 768 } 769 770 /* 771 ** Free any prior content in *pz and replace it with a copy of zNew. 772 */ 773 void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ 774 sqlite3DbFree(db, *pz); 775 *pz = sqlite3DbStrDup(db, zNew); 776 } 777 778 /* 779 ** Call this routine to record the fact that an OOM (out-of-memory) error 780 ** has happened. This routine will set db->mallocFailed, and also 781 ** temporarily disable the lookaside memory allocator and interrupt 782 ** any running VDBEs. 783 */ 784 void sqlite3OomFault(sqlite3 *db){ 785 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ 786 db->mallocFailed = 1; 787 if( db->nVdbeExec>0 ){ 788 db->u1.isInterrupted = 1; 789 } 790 db->lookaside.bDisable++; 791 } 792 } 793 794 /* 795 ** This routine reactivates the memory allocator and clears the 796 ** db->mallocFailed flag as necessary. 797 ** 798 ** The memory allocator is not restarted if there are running 799 ** VDBEs. 800 */ 801 void sqlite3OomClear(sqlite3 *db){ 802 if( db->mallocFailed && db->nVdbeExec==0 ){ 803 db->mallocFailed = 0; 804 db->u1.isInterrupted = 0; 805 assert( db->lookaside.bDisable>0 ); 806 db->lookaside.bDisable--; 807 } 808 } 809 810 /* 811 ** Take actions at the end of an API call to indicate an OOM error 812 */ 813 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ 814 sqlite3OomClear(db); 815 sqlite3Error(db, SQLITE_NOMEM); 816 return SQLITE_NOMEM_BKPT; 817 } 818 819 /* 820 ** This function must be called before exiting any API function (i.e. 821 ** returning control to the user) that has called sqlite3_malloc or 822 ** sqlite3_realloc. 823 ** 824 ** The returned value is normally a copy of the second argument to this 825 ** function. However, if a malloc() failure has occurred since the previous 826 ** invocation SQLITE_NOMEM is returned instead. 827 ** 828 ** If an OOM as occurred, then the connection error-code (the value 829 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. 830 */ 831 int sqlite3ApiExit(sqlite3* db, int rc){ 832 /* If the db handle must hold the connection handle mutex here. 833 ** Otherwise the read (and possible write) of db->mallocFailed 834 ** is unsafe, as is the call to sqlite3Error(). 835 */ 836 assert( db!=0 ); 837 assert( sqlite3_mutex_held(db->mutex) ); 838 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ 839 return apiOomError(db); 840 } 841 return rc & db->errMask; 842 } 843