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