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 if( sqlite3GlobalConfig.bCoreMutex ){ 135 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); 136 } 137 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 138 && sqlite3GlobalConfig.nScratch>0 ){ 139 int i, n, sz; 140 ScratchFreeslot *pSlot; 141 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); 142 sqlite3GlobalConfig.szScratch = sz; 143 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; 144 n = sqlite3GlobalConfig.nScratch; 145 mem0.pScratchFree = pSlot; 146 mem0.nScratchFree = n; 147 for(i=0; i<n-1; i++){ 148 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot); 149 pSlot = pSlot->pNext; 150 } 151 pSlot->pNext = 0; 152 mem0.pScratchEnd = (void*)&pSlot[1]; 153 }else{ 154 mem0.pScratchEnd = 0; 155 sqlite3GlobalConfig.pScratch = 0; 156 sqlite3GlobalConfig.szScratch = 0; 157 sqlite3GlobalConfig.nScratch = 0; 158 } 159 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 160 || sqlite3GlobalConfig.nPage<=0 ){ 161 sqlite3GlobalConfig.pPage = 0; 162 sqlite3GlobalConfig.szPage = 0; 163 } 164 rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); 165 if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); 166 return rc; 167 } 168 169 /* 170 ** Return true if the heap is currently under memory pressure - in other 171 ** words if the amount of heap used is close to the limit set by 172 ** sqlite3_soft_heap_limit(). 173 */ 174 int sqlite3HeapNearlyFull(void){ 175 return mem0.nearlyFull; 176 } 177 178 /* 179 ** Deinitialize the memory allocation subsystem. 180 */ 181 void sqlite3MallocEnd(void){ 182 if( sqlite3GlobalConfig.m.xShutdown ){ 183 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); 184 } 185 memset(&mem0, 0, sizeof(mem0)); 186 } 187 188 /* 189 ** Return the amount of memory currently checked out. 190 */ 191 sqlite3_int64 sqlite3_memory_used(void){ 192 sqlite3_int64 res, mx; 193 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); 194 return res; 195 } 196 197 /* 198 ** Return the maximum amount of memory that has ever been 199 ** checked out since either the beginning of this process 200 ** or since the most recent reset. 201 */ 202 sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ 203 sqlite3_int64 res, mx; 204 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); 205 return mx; 206 } 207 208 /* 209 ** Trigger the alarm 210 */ 211 static void sqlite3MallocAlarm(int nByte){ 212 if( mem0.alarmThreshold<=0 ) return; 213 sqlite3_mutex_leave(mem0.mutex); 214 sqlite3_release_memory(nByte); 215 sqlite3_mutex_enter(mem0.mutex); 216 } 217 218 /* 219 ** Do a memory allocation with statistics and alarms. Assume the 220 ** lock is already held. 221 */ 222 static int mallocWithAlarm(int n, void **pp){ 223 int nFull; 224 void *p; 225 assert( sqlite3_mutex_held(mem0.mutex) ); 226 nFull = sqlite3GlobalConfig.m.xRoundup(n); 227 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n); 228 if( mem0.alarmThreshold>0 ){ 229 sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); 230 if( nUsed >= mem0.alarmThreshold - nFull ){ 231 mem0.nearlyFull = 1; 232 sqlite3MallocAlarm(nFull); 233 }else{ 234 mem0.nearlyFull = 0; 235 } 236 } 237 p = sqlite3GlobalConfig.m.xMalloc(nFull); 238 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT 239 if( p==0 && mem0.alarmThreshold>0 ){ 240 sqlite3MallocAlarm(nFull); 241 p = sqlite3GlobalConfig.m.xMalloc(nFull); 242 } 243 #endif 244 if( p ){ 245 nFull = sqlite3MallocSize(p); 246 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); 247 sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); 248 } 249 *pp = p; 250 return nFull; 251 } 252 253 /* 254 ** Allocate memory. This routine is like sqlite3_malloc() except that it 255 ** assumes the memory subsystem has already been initialized. 256 */ 257 void *sqlite3Malloc(u64 n){ 258 void *p; 259 if( n==0 || n>=0x7fffff00 ){ 260 /* A memory allocation of a number of bytes which is near the maximum 261 ** signed integer value might cause an integer overflow inside of the 262 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving 263 ** 255 bytes of overhead. SQLite itself will never use anything near 264 ** this amount. The only way to reach the limit is with sqlite3_malloc() */ 265 p = 0; 266 }else if( sqlite3GlobalConfig.bMemstat ){ 267 sqlite3_mutex_enter(mem0.mutex); 268 mallocWithAlarm((int)n, &p); 269 sqlite3_mutex_leave(mem0.mutex); 270 }else{ 271 p = sqlite3GlobalConfig.m.xMalloc((int)n); 272 } 273 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ 274 return p; 275 } 276 277 /* 278 ** This version of the memory allocation is for use by the application. 279 ** First make sure the memory subsystem is initialized, then do the 280 ** allocation. 281 */ 282 void *sqlite3_malloc(int n){ 283 #ifndef SQLITE_OMIT_AUTOINIT 284 if( sqlite3_initialize() ) return 0; 285 #endif 286 return n<=0 ? 0 : sqlite3Malloc(n); 287 } 288 void *sqlite3_malloc64(sqlite3_uint64 n){ 289 #ifndef SQLITE_OMIT_AUTOINIT 290 if( sqlite3_initialize() ) return 0; 291 #endif 292 return sqlite3Malloc(n); 293 } 294 295 /* 296 ** Each thread may only have a single outstanding allocation from 297 ** xScratchMalloc(). We verify this constraint in the single-threaded 298 ** case by setting scratchAllocOut to 1 when an allocation 299 ** is outstanding clearing it when the allocation is freed. 300 */ 301 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 302 static int scratchAllocOut = 0; 303 #endif 304 305 306 /* 307 ** Allocate memory that is to be used and released right away. 308 ** This routine is similar to alloca() in that it is not intended 309 ** for situations where the memory might be held long-term. This 310 ** routine is intended to get memory to old large transient data 311 ** structures that would not normally fit on the stack of an 312 ** embedded processor. 313 */ 314 void *sqlite3ScratchMalloc(int n){ 315 void *p; 316 assert( n>0 ); 317 318 sqlite3_mutex_enter(mem0.mutex); 319 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); 320 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ 321 p = mem0.pScratchFree; 322 mem0.pScratchFree = mem0.pScratchFree->pNext; 323 mem0.nScratchFree--; 324 sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1); 325 sqlite3_mutex_leave(mem0.mutex); 326 }else{ 327 sqlite3_mutex_leave(mem0.mutex); 328 p = sqlite3Malloc(n); 329 if( sqlite3GlobalConfig.bMemstat && p ){ 330 sqlite3_mutex_enter(mem0.mutex); 331 sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p)); 332 sqlite3_mutex_leave(mem0.mutex); 333 } 334 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); 335 } 336 assert( sqlite3_mutex_notheld(mem0.mutex) ); 337 338 339 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 340 /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch 341 ** buffers per thread. 342 ** 343 ** This can only be checked in single-threaded mode. 344 */ 345 assert( scratchAllocOut==0 ); 346 if( p ) scratchAllocOut++; 347 #endif 348 349 return p; 350 } 351 void sqlite3ScratchFree(void *p){ 352 if( p ){ 353 354 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) 355 /* Verify that no more than two scratch allocation per thread 356 ** is outstanding at one time. (This is only checked in the 357 ** single-threaded case since checking in the multi-threaded case 358 ** would be much more complicated.) */ 359 assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); 360 scratchAllocOut--; 361 #endif 362 363 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){ 364 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */ 365 ScratchFreeslot *pSlot; 366 pSlot = (ScratchFreeslot*)p; 367 sqlite3_mutex_enter(mem0.mutex); 368 pSlot->pNext = mem0.pScratchFree; 369 mem0.pScratchFree = pSlot; 370 mem0.nScratchFree++; 371 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); 372 sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1); 373 sqlite3_mutex_leave(mem0.mutex); 374 }else{ 375 /* Release memory back to the heap */ 376 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); 377 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) ); 378 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 379 if( sqlite3GlobalConfig.bMemstat ){ 380 int iSize = sqlite3MallocSize(p); 381 sqlite3_mutex_enter(mem0.mutex); 382 sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize); 383 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize); 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 394 /* 395 ** TRUE if p is a lookaside memory allocation from db 396 */ 397 #ifndef SQLITE_OMIT_LOOKASIDE 398 static int isLookaside(sqlite3 *db, void *p){ 399 return p>=db->lookaside.pStart && p<db->lookaside.pEnd; 400 } 401 #else 402 #define isLookaside(A,B) 0 403 #endif 404 405 /* 406 ** Return the size of a memory allocation previously obtained from 407 ** sqlite3Malloc() or sqlite3_malloc(). 408 */ 409 int sqlite3MallocSize(void *p){ 410 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 411 return sqlite3GlobalConfig.m.xSize(p); 412 } 413 int sqlite3DbMallocSize(sqlite3 *db, void *p){ 414 if( db==0 || !isLookaside(db,p) ){ 415 #if SQLITE_DEBUG 416 if( db==0 ){ 417 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 418 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 419 }else{ 420 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 421 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 422 } 423 #endif 424 return sqlite3GlobalConfig.m.xSize(p); 425 }else{ 426 assert( sqlite3_mutex_held(db->mutex) ); 427 return db->lookaside.sz; 428 } 429 } 430 sqlite3_uint64 sqlite3_msize(void *p){ 431 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 432 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 433 return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p); 434 } 435 436 /* 437 ** Free memory previously obtained from sqlite3Malloc(). 438 */ 439 void sqlite3_free(void *p){ 440 if( p==0 ) return; /* IMP: R-49053-54554 */ 441 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); 442 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); 443 if( sqlite3GlobalConfig.bMemstat ){ 444 sqlite3_mutex_enter(mem0.mutex); 445 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); 446 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); 447 sqlite3GlobalConfig.m.xFree(p); 448 sqlite3_mutex_leave(mem0.mutex); 449 }else{ 450 sqlite3GlobalConfig.m.xFree(p); 451 } 452 } 453 454 /* 455 ** Add the size of memory allocation "p" to the count in 456 ** *db->pnBytesFreed. 457 */ 458 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ 459 *db->pnBytesFreed += sqlite3DbMallocSize(db,p); 460 } 461 462 /* 463 ** Free memory that might be associated with a particular database 464 ** connection. 465 */ 466 void sqlite3DbFree(sqlite3 *db, void *p){ 467 assert( db==0 || sqlite3_mutex_held(db->mutex) ); 468 if( p==0 ) return; 469 if( db ){ 470 if( db->pnBytesFreed ){ 471 measureAllocationSize(db, p); 472 return; 473 } 474 if( isLookaside(db, p) ){ 475 LookasideSlot *pBuf = (LookasideSlot*)p; 476 #if SQLITE_DEBUG 477 /* Trash all content in the buffer being freed */ 478 memset(p, 0xaa, db->lookaside.sz); 479 #endif 480 pBuf->pNext = db->lookaside.pFree; 481 db->lookaside.pFree = pBuf; 482 db->lookaside.nOut--; 483 return; 484 } 485 } 486 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 487 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 488 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); 489 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 490 sqlite3_free(p); 491 } 492 493 /* 494 ** Change the size of an existing memory allocation 495 */ 496 void *sqlite3Realloc(void *pOld, u64 nBytes){ 497 int nOld, nNew, nDiff; 498 void *pNew; 499 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); 500 assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); 501 if( pOld==0 ){ 502 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ 503 } 504 if( nBytes==0 ){ 505 sqlite3_free(pOld); /* IMP: R-26507-47431 */ 506 return 0; 507 } 508 if( nBytes>=0x7fffff00 ){ 509 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ 510 return 0; 511 } 512 nOld = sqlite3MallocSize(pOld); 513 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second 514 ** argument to xRealloc is always a value returned by a prior call to 515 ** xRoundup. */ 516 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); 517 if( nOld==nNew ){ 518 pNew = pOld; 519 }else if( sqlite3GlobalConfig.bMemstat ){ 520 sqlite3_mutex_enter(mem0.mutex); 521 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); 522 nDiff = nNew - nOld; 523 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 524 mem0.alarmThreshold-nDiff ){ 525 sqlite3MallocAlarm(nDiff); 526 } 527 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); 528 if( pNew==0 && mem0.alarmThreshold>0 ){ 529 sqlite3MallocAlarm((int)nBytes); 530 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); 531 } 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 = sqlite3DbMallocRaw(db, n); 580 if( p ){ 581 memset(p, 0, (size_t)n); 582 } 583 return p; 584 } 585 586 /* 587 ** Allocate and zero memory. If the allocation fails, make 588 ** the mallocFailed flag in the connection pointer. 589 ** 590 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc 591 ** failure on the same database connection) then always return 0. 592 ** Hence for a particular database connection, once malloc starts 593 ** failing, it fails consistently until mallocFailed is reset. 594 ** This is an important assumption. There are many places in the 595 ** code that do things like this: 596 ** 597 ** int *a = (int*)sqlite3DbMallocRaw(db, 100); 598 ** int *b = (int*)sqlite3DbMallocRaw(db, 200); 599 ** if( b ) a[10] = 9; 600 ** 601 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed 602 ** that all prior mallocs (ex: "a") worked too. 603 */ 604 void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ 605 void *p; 606 assert( db==0 || sqlite3_mutex_held(db->mutex) ); 607 assert( db==0 || db->pnBytesFreed==0 ); 608 #ifndef SQLITE_OMIT_LOOKASIDE 609 if( db ){ 610 LookasideSlot *pBuf; 611 if( db->mallocFailed ){ 612 return 0; 613 } 614 if( db->lookaside.bEnabled ){ 615 if( n>db->lookaside.sz ){ 616 db->lookaside.anStat[1]++; 617 }else if( (pBuf = db->lookaside.pFree)==0 ){ 618 db->lookaside.anStat[2]++; 619 }else{ 620 db->lookaside.pFree = pBuf->pNext; 621 db->lookaside.nOut++; 622 db->lookaside.anStat[0]++; 623 if( db->lookaside.nOut>db->lookaside.mxOut ){ 624 db->lookaside.mxOut = db->lookaside.nOut; 625 } 626 return (void*)pBuf; 627 } 628 } 629 } 630 #else 631 if( db && db->mallocFailed ){ 632 return 0; 633 } 634 #endif 635 p = sqlite3Malloc(n); 636 if( !p && db ){ 637 db->mallocFailed = 1; 638 } 639 sqlite3MemdebugSetType(p, 640 (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); 641 return p; 642 } 643 644 /* 645 ** Resize the block of memory pointed to by p to n bytes. If the 646 ** resize fails, set the mallocFailed flag in the connection object. 647 */ 648 void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ 649 void *pNew = 0; 650 assert( db!=0 ); 651 assert( sqlite3_mutex_held(db->mutex) ); 652 if( db->mallocFailed==0 ){ 653 if( p==0 ){ 654 return sqlite3DbMallocRaw(db, n); 655 } 656 if( isLookaside(db, p) ){ 657 if( n<=db->lookaside.sz ){ 658 return p; 659 } 660 pNew = sqlite3DbMallocRaw(db, n); 661 if( pNew ){ 662 memcpy(pNew, p, db->lookaside.sz); 663 sqlite3DbFree(db, p); 664 } 665 }else{ 666 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 667 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); 668 sqlite3MemdebugSetType(p, MEMTYPE_HEAP); 669 pNew = sqlite3_realloc64(p, n); 670 if( !pNew ){ 671 db->mallocFailed = 1; 672 } 673 sqlite3MemdebugSetType(pNew, 674 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); 675 } 676 } 677 return pNew; 678 } 679 680 /* 681 ** Attempt to reallocate p. If the reallocation fails, then free p 682 ** and set the mallocFailed flag in the database connection. 683 */ 684 void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ 685 void *pNew; 686 pNew = sqlite3DbRealloc(db, p, n); 687 if( !pNew ){ 688 sqlite3DbFree(db, p); 689 } 690 return pNew; 691 } 692 693 /* 694 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 695 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This 696 ** is because when memory debugging is turned on, these two functions are 697 ** called via macros that record the current file and line number in the 698 ** ThreadData structure. 699 */ 700 char *sqlite3DbStrDup(sqlite3 *db, const char *z){ 701 char *zNew; 702 size_t n; 703 if( z==0 ){ 704 return 0; 705 } 706 n = sqlite3Strlen30(z) + 1; 707 assert( (n&0x7fffffff)==n ); 708 zNew = sqlite3DbMallocRaw(db, (int)n); 709 if( zNew ){ 710 memcpy(zNew, z, n); 711 } 712 return zNew; 713 } 714 char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ 715 char *zNew; 716 if( z==0 ){ 717 return 0; 718 } 719 assert( (n&0x7fffffff)==n ); 720 zNew = sqlite3DbMallocRaw(db, n+1); 721 if( zNew ){ 722 memcpy(zNew, z, (size_t)n); 723 zNew[n] = 0; 724 } 725 return zNew; 726 } 727 728 /* 729 ** Free any prior content in *pz and replace it with a copy of zNew. 730 */ 731 void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ 732 sqlite3DbFree(db, *pz); 733 *pz = sqlite3DbStrDup(db, zNew); 734 } 735 736 /* 737 ** Take actions at the end of an API call to indicate an OOM error 738 */ 739 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ 740 db->mallocFailed = 0; 741 sqlite3Error(db, SQLITE_NOMEM); 742 return SQLITE_NOMEM; 743 } 744 745 /* 746 ** This function must be called before exiting any API function (i.e. 747 ** returning control to the user) that has called sqlite3_malloc or 748 ** sqlite3_realloc. 749 ** 750 ** The returned value is normally a copy of the second argument to this 751 ** function. However, if a malloc() failure has occurred since the previous 752 ** invocation SQLITE_NOMEM is returned instead. 753 ** 754 ** If an OOM as occurred, then the connection error-code (the value 755 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. 756 */ 757 int sqlite3ApiExit(sqlite3* db, int rc){ 758 /* If the db handle must hold the connection handle mutex here. 759 ** Otherwise the read (and possible write) of db->mallocFailed 760 ** is unsafe, as is the call to sqlite3Error(). 761 */ 762 assert( db!=0 ); 763 assert( sqlite3_mutex_held(db->mutex) ); 764 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ 765 return apiOomError(db); 766 } 767 return rc & db->errMask; 768 } 769