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