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