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