1 /* 2 ** 2004 April 6 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 ** This file implements an external (disk-based) database using BTrees. 13 ** See the header comment on "btreeInt.h" for additional information. 14 ** Including a description of file format and an overview of operation. 15 */ 16 #include "btreeInt.h" 17 18 /* 19 ** The header string that appears at the beginning of every 20 ** SQLite database. 21 */ 22 static const char zMagicHeader[] = SQLITE_FILE_HEADER; 23 24 /* 25 ** Set this global variable to 1 to enable tracing using the TRACE 26 ** macro. 27 */ 28 #if 0 29 int sqlite3BtreeTrace=1; /* True to enable tracing */ 30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} 31 #else 32 # define TRACE(X) 33 #endif 34 35 /* 36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes. 37 ** But if the value is zero, make it 65536. 38 ** 39 ** This routine is used to extract the "offset to cell content area" value 40 ** from the header of a btree page. If the page size is 65536 and the page 41 ** is empty, the offset should be 65536, but the 2-byte value stores zero. 42 ** This routine makes the necessary adjustment to 65536. 43 */ 44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) 45 46 /* 47 ** Values passed as the 5th argument to allocateBtreePage() 48 */ 49 #define BTALLOC_ANY 0 /* Allocate any page */ 50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */ 51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */ 52 53 /* 54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 55 ** defined, or 0 if it is. For example: 56 ** 57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); 58 */ 59 #ifndef SQLITE_OMIT_AUTOVACUUM 60 #define IfNotOmitAV(expr) (expr) 61 #else 62 #define IfNotOmitAV(expr) 0 63 #endif 64 65 #ifndef SQLITE_OMIT_SHARED_CACHE 66 /* 67 ** A list of BtShared objects that are eligible for participation 68 ** in shared cache. This variable has file scope during normal builds, 69 ** but the test harness needs to access it so we make it global for 70 ** test builds. 71 ** 72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. 73 */ 74 #ifdef SQLITE_TEST 75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; 76 #else 77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; 78 #endif 79 #endif /* SQLITE_OMIT_SHARED_CACHE */ 80 81 #ifndef SQLITE_OMIT_SHARED_CACHE 82 /* 83 ** Enable or disable the shared pager and schema features. 84 ** 85 ** This routine has no effect on existing database connections. 86 ** The shared cache setting effects only future calls to 87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). 88 */ 89 int sqlite3_enable_shared_cache(int enable){ 90 sqlite3GlobalConfig.sharedCacheEnabled = enable; 91 return SQLITE_OK; 92 } 93 #endif 94 95 96 97 #ifdef SQLITE_OMIT_SHARED_CACHE 98 /* 99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), 100 ** and clearAllSharedCacheTableLocks() 101 ** manipulate entries in the BtShared.pLock linked list used to store 102 ** shared-cache table level locks. If the library is compiled with the 103 ** shared-cache feature disabled, then there is only ever one user 104 ** of each BtShared structure and so this locking is not necessary. 105 ** So define the lock related functions as no-ops. 106 */ 107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK 108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK 109 #define clearAllSharedCacheTableLocks(a) 110 #define downgradeAllSharedCacheTableLocks(a) 111 #define hasSharedCacheTableLock(a,b,c,d) 1 112 #define hasReadConflicts(a, b) 0 113 #endif 114 115 #ifndef SQLITE_OMIT_SHARED_CACHE 116 117 #ifdef SQLITE_DEBUG 118 /* 119 **** This function is only used as part of an assert() statement. *** 120 ** 121 ** Check to see if pBtree holds the required locks to read or write to the 122 ** table with root page iRoot. Return 1 if it does and 0 if not. 123 ** 124 ** For example, when writing to a table with root-page iRoot via 125 ** Btree connection pBtree: 126 ** 127 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); 128 ** 129 ** When writing to an index that resides in a sharable database, the 130 ** caller should have first obtained a lock specifying the root page of 131 ** the corresponding table. This makes things a bit more complicated, 132 ** as this module treats each table as a separate structure. To determine 133 ** the table corresponding to the index being written, this 134 ** function has to search through the database schema. 135 ** 136 ** Instead of a lock on the table/index rooted at page iRoot, the caller may 137 ** hold a write-lock on the schema table (root page 1). This is also 138 ** acceptable. 139 */ 140 static int hasSharedCacheTableLock( 141 Btree *pBtree, /* Handle that must hold lock */ 142 Pgno iRoot, /* Root page of b-tree */ 143 int isIndex, /* True if iRoot is the root of an index b-tree */ 144 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ 145 ){ 146 Schema *pSchema = (Schema *)pBtree->pBt->pSchema; 147 Pgno iTab = 0; 148 BtLock *pLock; 149 150 /* If this database is not shareable, or if the client is reading 151 ** and has the read-uncommitted flag set, then no lock is required. 152 ** Return true immediately. 153 */ 154 if( (pBtree->sharable==0) 155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) 156 ){ 157 return 1; 158 } 159 160 /* If the client is reading or writing an index and the schema is 161 ** not loaded, then it is too difficult to actually check to see if 162 ** the correct locks are held. So do not bother - just return true. 163 ** This case does not come up very often anyhow. 164 */ 165 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ 166 return 1; 167 } 168 169 /* Figure out the root-page that the lock should be held on. For table 170 ** b-trees, this is just the root page of the b-tree being read or 171 ** written. For index b-trees, it is the root page of the associated 172 ** table. */ 173 if( isIndex ){ 174 HashElem *p; 175 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ 176 Index *pIdx = (Index *)sqliteHashData(p); 177 if( pIdx->tnum==(int)iRoot ){ 178 if( iTab ){ 179 /* Two or more indexes share the same root page. There must 180 ** be imposter tables. So just return true. The assert is not 181 ** useful in that case. */ 182 return 1; 183 } 184 iTab = pIdx->pTable->tnum; 185 } 186 } 187 }else{ 188 iTab = iRoot; 189 } 190 191 /* Search for the required lock. Either a write-lock on root-page iTab, a 192 ** write-lock on the schema table, or (if the client is reading) a 193 ** read-lock on iTab will suffice. Return 1 if any of these are found. */ 194 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ 195 if( pLock->pBtree==pBtree 196 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) 197 && pLock->eLock>=eLockType 198 ){ 199 return 1; 200 } 201 } 202 203 /* Failed to find the required lock. */ 204 return 0; 205 } 206 #endif /* SQLITE_DEBUG */ 207 208 #ifdef SQLITE_DEBUG 209 /* 210 **** This function may be used as part of assert() statements only. **** 211 ** 212 ** Return true if it would be illegal for pBtree to write into the 213 ** table or index rooted at iRoot because other shared connections are 214 ** simultaneously reading that same table or index. 215 ** 216 ** It is illegal for pBtree to write if some other Btree object that 217 ** shares the same BtShared object is currently reading or writing 218 ** the iRoot table. Except, if the other Btree object has the 219 ** read-uncommitted flag set, then it is OK for the other object to 220 ** have a read cursor. 221 ** 222 ** For example, before writing to any part of the table or index 223 ** rooted at page iRoot, one should call: 224 ** 225 ** assert( !hasReadConflicts(pBtree, iRoot) ); 226 */ 227 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ 228 BtCursor *p; 229 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 230 if( p->pgnoRoot==iRoot 231 && p->pBtree!=pBtree 232 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) 233 ){ 234 return 1; 235 } 236 } 237 return 0; 238 } 239 #endif /* #ifdef SQLITE_DEBUG */ 240 241 /* 242 ** Query to see if Btree handle p may obtain a lock of type eLock 243 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return 244 ** SQLITE_OK if the lock may be obtained (by calling 245 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. 246 */ 247 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ 248 BtShared *pBt = p->pBt; 249 BtLock *pIter; 250 251 assert( sqlite3BtreeHoldsMutex(p) ); 252 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 253 assert( p->db!=0 ); 254 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); 255 256 /* If requesting a write-lock, then the Btree must have an open write 257 ** transaction on this file. And, obviously, for this to be so there 258 ** must be an open write transaction on the file itself. 259 */ 260 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); 261 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); 262 263 /* This routine is a no-op if the shared-cache is not enabled */ 264 if( !p->sharable ){ 265 return SQLITE_OK; 266 } 267 268 /* If some other connection is holding an exclusive lock, the 269 ** requested lock may not be obtained. 270 */ 271 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ 272 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); 273 return SQLITE_LOCKED_SHAREDCACHE; 274 } 275 276 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 277 /* The condition (pIter->eLock!=eLock) in the following if(...) 278 ** statement is a simplification of: 279 ** 280 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) 281 ** 282 ** since we know that if eLock==WRITE_LOCK, then no other connection 283 ** may hold a WRITE_LOCK on any table in this file (since there can 284 ** only be a single writer). 285 */ 286 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); 287 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); 288 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ 289 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); 290 if( eLock==WRITE_LOCK ){ 291 assert( p==pBt->pWriter ); 292 pBt->btsFlags |= BTS_PENDING; 293 } 294 return SQLITE_LOCKED_SHAREDCACHE; 295 } 296 } 297 return SQLITE_OK; 298 } 299 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 300 301 #ifndef SQLITE_OMIT_SHARED_CACHE 302 /* 303 ** Add a lock on the table with root-page iTable to the shared-btree used 304 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 305 ** WRITE_LOCK. 306 ** 307 ** This function assumes the following: 308 ** 309 ** (a) The specified Btree object p is connected to a sharable 310 ** database (one with the BtShared.sharable flag set), and 311 ** 312 ** (b) No other Btree objects hold a lock that conflicts 313 ** with the requested lock (i.e. querySharedCacheTableLock() has 314 ** already been called and returned SQLITE_OK). 315 ** 316 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 317 ** is returned if a malloc attempt fails. 318 */ 319 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ 320 BtShared *pBt = p->pBt; 321 BtLock *pLock = 0; 322 BtLock *pIter; 323 324 assert( sqlite3BtreeHoldsMutex(p) ); 325 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 326 assert( p->db!=0 ); 327 328 /* A connection with the read-uncommitted flag set will never try to 329 ** obtain a read-lock using this function. The only read-lock obtained 330 ** by a connection in read-uncommitted mode is on the sqlite_master 331 ** table, and that lock is obtained in BtreeBeginTrans(). */ 332 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); 333 334 /* This function should only be called on a sharable b-tree after it 335 ** has been determined that no other b-tree holds a conflicting lock. */ 336 assert( p->sharable ); 337 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); 338 339 /* First search the list for an existing lock on this table. */ 340 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 341 if( pIter->iTable==iTable && pIter->pBtree==p ){ 342 pLock = pIter; 343 break; 344 } 345 } 346 347 /* If the above search did not find a BtLock struct associating Btree p 348 ** with table iTable, allocate one and link it into the list. 349 */ 350 if( !pLock ){ 351 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); 352 if( !pLock ){ 353 return SQLITE_NOMEM; 354 } 355 pLock->iTable = iTable; 356 pLock->pBtree = p; 357 pLock->pNext = pBt->pLock; 358 pBt->pLock = pLock; 359 } 360 361 /* Set the BtLock.eLock variable to the maximum of the current lock 362 ** and the requested lock. This means if a write-lock was already held 363 ** and a read-lock requested, we don't incorrectly downgrade the lock. 364 */ 365 assert( WRITE_LOCK>READ_LOCK ); 366 if( eLock>pLock->eLock ){ 367 pLock->eLock = eLock; 368 } 369 370 return SQLITE_OK; 371 } 372 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 373 374 #ifndef SQLITE_OMIT_SHARED_CACHE 375 /* 376 ** Release all the table locks (locks obtained via calls to 377 ** the setSharedCacheTableLock() procedure) held by Btree object p. 378 ** 379 ** This function assumes that Btree p has an open read or write 380 ** transaction. If it does not, then the BTS_PENDING flag 381 ** may be incorrectly cleared. 382 */ 383 static void clearAllSharedCacheTableLocks(Btree *p){ 384 BtShared *pBt = p->pBt; 385 BtLock **ppIter = &pBt->pLock; 386 387 assert( sqlite3BtreeHoldsMutex(p) ); 388 assert( p->sharable || 0==*ppIter ); 389 assert( p->inTrans>0 ); 390 391 while( *ppIter ){ 392 BtLock *pLock = *ppIter; 393 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); 394 assert( pLock->pBtree->inTrans>=pLock->eLock ); 395 if( pLock->pBtree==p ){ 396 *ppIter = pLock->pNext; 397 assert( pLock->iTable!=1 || pLock==&p->lock ); 398 if( pLock->iTable!=1 ){ 399 sqlite3_free(pLock); 400 } 401 }else{ 402 ppIter = &pLock->pNext; 403 } 404 } 405 406 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); 407 if( pBt->pWriter==p ){ 408 pBt->pWriter = 0; 409 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 410 }else if( pBt->nTransaction==2 ){ 411 /* This function is called when Btree p is concluding its 412 ** transaction. If there currently exists a writer, and p is not 413 ** that writer, then the number of locks held by connections other 414 ** than the writer must be about to drop to zero. In this case 415 ** set the BTS_PENDING flag to 0. 416 ** 417 ** If there is not currently a writer, then BTS_PENDING must 418 ** be zero already. So this next line is harmless in that case. 419 */ 420 pBt->btsFlags &= ~BTS_PENDING; 421 } 422 } 423 424 /* 425 ** This function changes all write-locks held by Btree p into read-locks. 426 */ 427 static void downgradeAllSharedCacheTableLocks(Btree *p){ 428 BtShared *pBt = p->pBt; 429 if( pBt->pWriter==p ){ 430 BtLock *pLock; 431 pBt->pWriter = 0; 432 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 433 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ 434 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); 435 pLock->eLock = READ_LOCK; 436 } 437 } 438 } 439 440 #endif /* SQLITE_OMIT_SHARED_CACHE */ 441 442 static void releasePage(MemPage *pPage); /* Forward reference */ 443 444 /* 445 ***** This routine is used inside of assert() only **** 446 ** 447 ** Verify that the cursor holds the mutex on its BtShared 448 */ 449 #ifdef SQLITE_DEBUG 450 static int cursorHoldsMutex(BtCursor *p){ 451 return sqlite3_mutex_held(p->pBt->mutex); 452 } 453 #endif 454 455 /* 456 ** Invalidate the overflow cache of the cursor passed as the first argument. 457 ** on the shared btree structure pBt. 458 */ 459 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) 460 461 /* 462 ** Invalidate the overflow page-list cache for all cursors opened 463 ** on the shared btree structure pBt. 464 */ 465 static void invalidateAllOverflowCache(BtShared *pBt){ 466 BtCursor *p; 467 assert( sqlite3_mutex_held(pBt->mutex) ); 468 for(p=pBt->pCursor; p; p=p->pNext){ 469 invalidateOverflowCache(p); 470 } 471 } 472 473 #ifndef SQLITE_OMIT_INCRBLOB 474 /* 475 ** This function is called before modifying the contents of a table 476 ** to invalidate any incrblob cursors that are open on the 477 ** row or one of the rows being modified. 478 ** 479 ** If argument isClearTable is true, then the entire contents of the 480 ** table is about to be deleted. In this case invalidate all incrblob 481 ** cursors open on any row within the table with root-page pgnoRoot. 482 ** 483 ** Otherwise, if argument isClearTable is false, then the row with 484 ** rowid iRow is being replaced or deleted. In this case invalidate 485 ** only those incrblob cursors open on that specific row. 486 */ 487 static void invalidateIncrblobCursors( 488 Btree *pBtree, /* The database file to check */ 489 i64 iRow, /* The rowid that might be changing */ 490 int isClearTable /* True if all rows are being deleted */ 491 ){ 492 BtCursor *p; 493 if( pBtree->hasIncrblobCur==0 ) return; 494 assert( sqlite3BtreeHoldsMutex(pBtree) ); 495 pBtree->hasIncrblobCur = 0; 496 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 497 if( (p->curFlags & BTCF_Incrblob)!=0 ){ 498 pBtree->hasIncrblobCur = 1; 499 if( isClearTable || p->info.nKey==iRow ){ 500 p->eState = CURSOR_INVALID; 501 } 502 } 503 } 504 } 505 506 #else 507 /* Stub function when INCRBLOB is omitted */ 508 #define invalidateIncrblobCursors(x,y,z) 509 #endif /* SQLITE_OMIT_INCRBLOB */ 510 511 /* 512 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 513 ** when a page that previously contained data becomes a free-list leaf 514 ** page. 515 ** 516 ** The BtShared.pHasContent bitvec exists to work around an obscure 517 ** bug caused by the interaction of two useful IO optimizations surrounding 518 ** free-list leaf pages: 519 ** 520 ** 1) When all data is deleted from a page and the page becomes 521 ** a free-list leaf page, the page is not written to the database 522 ** (as free-list leaf pages contain no meaningful data). Sometimes 523 ** such a page is not even journalled (as it will not be modified, 524 ** why bother journalling it?). 525 ** 526 ** 2) When a free-list leaf page is reused, its content is not read 527 ** from the database or written to the journal file (why should it 528 ** be, if it is not at all meaningful?). 529 ** 530 ** By themselves, these optimizations work fine and provide a handy 531 ** performance boost to bulk delete or insert operations. However, if 532 ** a page is moved to the free-list and then reused within the same 533 ** transaction, a problem comes up. If the page is not journalled when 534 ** it is moved to the free-list and it is also not journalled when it 535 ** is extracted from the free-list and reused, then the original data 536 ** may be lost. In the event of a rollback, it may not be possible 537 ** to restore the database to its original configuration. 538 ** 539 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 540 ** moved to become a free-list leaf page, the corresponding bit is 541 ** set in the bitvec. Whenever a leaf page is extracted from the free-list, 542 ** optimization 2 above is omitted if the corresponding bit is already 543 ** set in BtShared.pHasContent. The contents of the bitvec are cleared 544 ** at the end of every transaction. 545 */ 546 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ 547 int rc = SQLITE_OK; 548 if( !pBt->pHasContent ){ 549 assert( pgno<=pBt->nPage ); 550 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); 551 if( !pBt->pHasContent ){ 552 rc = SQLITE_NOMEM; 553 } 554 } 555 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ 556 rc = sqlite3BitvecSet(pBt->pHasContent, pgno); 557 } 558 return rc; 559 } 560 561 /* 562 ** Query the BtShared.pHasContent vector. 563 ** 564 ** This function is called when a free-list leaf page is removed from the 565 ** free-list for reuse. It returns false if it is safe to retrieve the 566 ** page from the pager layer with the 'no-content' flag set. True otherwise. 567 */ 568 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ 569 Bitvec *p = pBt->pHasContent; 570 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); 571 } 572 573 /* 574 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be 575 ** invoked at the conclusion of each write-transaction. 576 */ 577 static void btreeClearHasContent(BtShared *pBt){ 578 sqlite3BitvecDestroy(pBt->pHasContent); 579 pBt->pHasContent = 0; 580 } 581 582 /* 583 ** Release all of the apPage[] pages for a cursor. 584 */ 585 static void btreeReleaseAllCursorPages(BtCursor *pCur){ 586 int i; 587 for(i=0; i<=pCur->iPage; i++){ 588 releasePage(pCur->apPage[i]); 589 pCur->apPage[i] = 0; 590 } 591 pCur->iPage = -1; 592 } 593 594 /* 595 ** The cursor passed as the only argument must point to a valid entry 596 ** when this function is called (i.e. have eState==CURSOR_VALID). This 597 ** function saves the current cursor key in variables pCur->nKey and 598 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 599 ** code otherwise. 600 ** 601 ** If the cursor is open on an intkey table, then the integer key 602 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to 603 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 604 ** set to point to a malloced buffer pCur->nKey bytes in size containing 605 ** the key. 606 */ 607 static int saveCursorKey(BtCursor *pCur){ 608 int rc; 609 assert( CURSOR_VALID==pCur->eState ); 610 assert( 0==pCur->pKey ); 611 assert( cursorHoldsMutex(pCur) ); 612 613 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); 614 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */ 615 616 /* If this is an intKey table, then the above call to BtreeKeySize() 617 ** stores the integer key in pCur->nKey. In this case this value is 618 ** all that is required. Otherwise, if pCur is not open on an intKey 619 ** table, then malloc space for and store the pCur->nKey bytes of key 620 ** data. */ 621 if( 0==pCur->curIntKey ){ 622 void *pKey = sqlite3Malloc( pCur->nKey ); 623 if( pKey ){ 624 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); 625 if( rc==SQLITE_OK ){ 626 pCur->pKey = pKey; 627 }else{ 628 sqlite3_free(pKey); 629 } 630 }else{ 631 rc = SQLITE_NOMEM; 632 } 633 } 634 assert( !pCur->curIntKey || !pCur->pKey ); 635 return rc; 636 } 637 638 /* 639 ** Save the current cursor position in the variables BtCursor.nKey 640 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. 641 ** 642 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) 643 ** prior to calling this routine. 644 */ 645 static int saveCursorPosition(BtCursor *pCur){ 646 int rc; 647 648 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); 649 assert( 0==pCur->pKey ); 650 assert( cursorHoldsMutex(pCur) ); 651 652 if( pCur->eState==CURSOR_SKIPNEXT ){ 653 pCur->eState = CURSOR_VALID; 654 }else{ 655 pCur->skipNext = 0; 656 } 657 658 rc = saveCursorKey(pCur); 659 if( rc==SQLITE_OK ){ 660 btreeReleaseAllCursorPages(pCur); 661 pCur->eState = CURSOR_REQUIRESEEK; 662 } 663 664 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); 665 return rc; 666 } 667 668 /* Forward reference */ 669 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); 670 671 /* 672 ** Save the positions of all cursors (except pExcept) that are open on 673 ** the table with root-page iRoot. "Saving the cursor position" means that 674 ** the location in the btree is remembered in such a way that it can be 675 ** moved back to the same spot after the btree has been modified. This 676 ** routine is called just before cursor pExcept is used to modify the 677 ** table, for example in BtreeDelete() or BtreeInsert(). 678 ** 679 ** If there are two or more cursors on the same btree, then all such 680 ** cursors should have their BTCF_Multiple flag set. The btreeCursor() 681 ** routine enforces that rule. This routine only needs to be called in 682 ** the uncommon case when pExpect has the BTCF_Multiple flag set. 683 ** 684 ** If pExpect!=NULL and if no other cursors are found on the same root-page, 685 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another 686 ** pointless call to this routine. 687 ** 688 ** Implementation note: This routine merely checks to see if any cursors 689 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) 690 ** event that cursors are in need to being saved. 691 */ 692 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ 693 BtCursor *p; 694 assert( sqlite3_mutex_held(pBt->mutex) ); 695 assert( pExcept==0 || pExcept->pBt==pBt ); 696 for(p=pBt->pCursor; p; p=p->pNext){ 697 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; 698 } 699 if( p ) return saveCursorsOnList(p, iRoot, pExcept); 700 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; 701 return SQLITE_OK; 702 } 703 704 /* This helper routine to saveAllCursors does the actual work of saving 705 ** the cursors if and when a cursor is found that actually requires saving. 706 ** The common case is that no cursors need to be saved, so this routine is 707 ** broken out from its caller to avoid unnecessary stack pointer movement. 708 */ 709 static int SQLITE_NOINLINE saveCursorsOnList( 710 BtCursor *p, /* The first cursor that needs saving */ 711 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ 712 BtCursor *pExcept /* Do not save this cursor */ 713 ){ 714 do{ 715 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ 716 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 717 int rc = saveCursorPosition(p); 718 if( SQLITE_OK!=rc ){ 719 return rc; 720 } 721 }else{ 722 testcase( p->iPage>0 ); 723 btreeReleaseAllCursorPages(p); 724 } 725 } 726 p = p->pNext; 727 }while( p ); 728 return SQLITE_OK; 729 } 730 731 /* 732 ** Clear the current cursor position. 733 */ 734 void sqlite3BtreeClearCursor(BtCursor *pCur){ 735 assert( cursorHoldsMutex(pCur) ); 736 sqlite3_free(pCur->pKey); 737 pCur->pKey = 0; 738 pCur->eState = CURSOR_INVALID; 739 } 740 741 /* 742 ** In this version of BtreeMoveto, pKey is a packed index record 743 ** such as is generated by the OP_MakeRecord opcode. Unpack the 744 ** record and then call BtreeMovetoUnpacked() to do the work. 745 */ 746 static int btreeMoveto( 747 BtCursor *pCur, /* Cursor open on the btree to be searched */ 748 const void *pKey, /* Packed key if the btree is an index */ 749 i64 nKey, /* Integer key for tables. Size of pKey for indices */ 750 int bias, /* Bias search to the high end */ 751 int *pRes /* Write search results here */ 752 ){ 753 int rc; /* Status code */ 754 UnpackedRecord *pIdxKey; /* Unpacked index key */ 755 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */ 756 char *pFree = 0; 757 758 if( pKey ){ 759 assert( nKey==(i64)(int)nKey ); 760 pIdxKey = sqlite3VdbeAllocUnpackedRecord( 761 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree 762 ); 763 if( pIdxKey==0 ) return SQLITE_NOMEM; 764 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); 765 if( pIdxKey->nField==0 ){ 766 sqlite3DbFree(pCur->pKeyInfo->db, pFree); 767 return SQLITE_CORRUPT_BKPT; 768 } 769 }else{ 770 pIdxKey = 0; 771 } 772 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); 773 if( pFree ){ 774 sqlite3DbFree(pCur->pKeyInfo->db, pFree); 775 } 776 return rc; 777 } 778 779 /* 780 ** Restore the cursor to the position it was in (or as close to as possible) 781 ** when saveCursorPosition() was called. Note that this call deletes the 782 ** saved position info stored by saveCursorPosition(), so there can be 783 ** at most one effective restoreCursorPosition() call after each 784 ** saveCursorPosition(). 785 */ 786 static int btreeRestoreCursorPosition(BtCursor *pCur){ 787 int rc; 788 int skipNext; 789 assert( cursorHoldsMutex(pCur) ); 790 assert( pCur->eState>=CURSOR_REQUIRESEEK ); 791 if( pCur->eState==CURSOR_FAULT ){ 792 return pCur->skipNext; 793 } 794 pCur->eState = CURSOR_INVALID; 795 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); 796 if( rc==SQLITE_OK ){ 797 sqlite3_free(pCur->pKey); 798 pCur->pKey = 0; 799 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); 800 pCur->skipNext |= skipNext; 801 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ 802 pCur->eState = CURSOR_SKIPNEXT; 803 } 804 } 805 return rc; 806 } 807 808 #define restoreCursorPosition(p) \ 809 (p->eState>=CURSOR_REQUIRESEEK ? \ 810 btreeRestoreCursorPosition(p) : \ 811 SQLITE_OK) 812 813 /* 814 ** Determine whether or not a cursor has moved from the position where 815 ** it was last placed, or has been invalidated for any other reason. 816 ** Cursors can move when the row they are pointing at is deleted out 817 ** from under them, for example. Cursor might also move if a btree 818 ** is rebalanced. 819 ** 820 ** Calling this routine with a NULL cursor pointer returns false. 821 ** 822 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor 823 ** back to where it ought to be if this routine returns true. 824 */ 825 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ 826 return pCur->eState!=CURSOR_VALID; 827 } 828 829 /* 830 ** This routine restores a cursor back to its original position after it 831 ** has been moved by some outside activity (such as a btree rebalance or 832 ** a row having been deleted out from under the cursor). 833 ** 834 ** On success, the *pDifferentRow parameter is false if the cursor is left 835 ** pointing at exactly the same row. *pDifferntRow is the row the cursor 836 ** was pointing to has been deleted, forcing the cursor to point to some 837 ** nearby row. 838 ** 839 ** This routine should only be called for a cursor that just returned 840 ** TRUE from sqlite3BtreeCursorHasMoved(). 841 */ 842 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ 843 int rc; 844 845 assert( pCur!=0 ); 846 assert( pCur->eState!=CURSOR_VALID ); 847 rc = restoreCursorPosition(pCur); 848 if( rc ){ 849 *pDifferentRow = 1; 850 return rc; 851 } 852 if( pCur->eState!=CURSOR_VALID ){ 853 *pDifferentRow = 1; 854 }else{ 855 assert( pCur->skipNext==0 ); 856 *pDifferentRow = 0; 857 } 858 return SQLITE_OK; 859 } 860 861 #ifndef SQLITE_OMIT_AUTOVACUUM 862 /* 863 ** Given a page number of a regular database page, return the page 864 ** number for the pointer-map page that contains the entry for the 865 ** input page number. 866 ** 867 ** Return 0 (not a valid page) for pgno==1 since there is 868 ** no pointer map associated with page 1. The integrity_check logic 869 ** requires that ptrmapPageno(*,1)!=1. 870 */ 871 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ 872 int nPagesPerMapPage; 873 Pgno iPtrMap, ret; 874 assert( sqlite3_mutex_held(pBt->mutex) ); 875 if( pgno<2 ) return 0; 876 nPagesPerMapPage = (pBt->usableSize/5)+1; 877 iPtrMap = (pgno-2)/nPagesPerMapPage; 878 ret = (iPtrMap*nPagesPerMapPage) + 2; 879 if( ret==PENDING_BYTE_PAGE(pBt) ){ 880 ret++; 881 } 882 return ret; 883 } 884 885 /* 886 ** Write an entry into the pointer map. 887 ** 888 ** This routine updates the pointer map entry for page number 'key' 889 ** so that it maps to type 'eType' and parent page number 'pgno'. 890 ** 891 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is 892 ** a no-op. If an error occurs, the appropriate error code is written 893 ** into *pRC. 894 */ 895 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ 896 DbPage *pDbPage; /* The pointer map page */ 897 u8 *pPtrmap; /* The pointer map data */ 898 Pgno iPtrmap; /* The pointer map page number */ 899 int offset; /* Offset in pointer map page */ 900 int rc; /* Return code from subfunctions */ 901 902 if( *pRC ) return; 903 904 assert( sqlite3_mutex_held(pBt->mutex) ); 905 /* The master-journal page number must never be used as a pointer map page */ 906 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); 907 908 assert( pBt->autoVacuum ); 909 if( key==0 ){ 910 *pRC = SQLITE_CORRUPT_BKPT; 911 return; 912 } 913 iPtrmap = PTRMAP_PAGENO(pBt, key); 914 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); 915 if( rc!=SQLITE_OK ){ 916 *pRC = rc; 917 return; 918 } 919 offset = PTRMAP_PTROFFSET(iPtrmap, key); 920 if( offset<0 ){ 921 *pRC = SQLITE_CORRUPT_BKPT; 922 goto ptrmap_exit; 923 } 924 assert( offset <= (int)pBt->usableSize-5 ); 925 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 926 927 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ 928 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); 929 *pRC= rc = sqlite3PagerWrite(pDbPage); 930 if( rc==SQLITE_OK ){ 931 pPtrmap[offset] = eType; 932 put4byte(&pPtrmap[offset+1], parent); 933 } 934 } 935 936 ptrmap_exit: 937 sqlite3PagerUnref(pDbPage); 938 } 939 940 /* 941 ** Read an entry from the pointer map. 942 ** 943 ** This routine retrieves the pointer map entry for page 'key', writing 944 ** the type and parent page number to *pEType and *pPgno respectively. 945 ** An error code is returned if something goes wrong, otherwise SQLITE_OK. 946 */ 947 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ 948 DbPage *pDbPage; /* The pointer map page */ 949 int iPtrmap; /* Pointer map page index */ 950 u8 *pPtrmap; /* Pointer map page data */ 951 int offset; /* Offset of entry in pointer map */ 952 int rc; 953 954 assert( sqlite3_mutex_held(pBt->mutex) ); 955 956 iPtrmap = PTRMAP_PAGENO(pBt, key); 957 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); 958 if( rc!=0 ){ 959 return rc; 960 } 961 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 962 963 offset = PTRMAP_PTROFFSET(iPtrmap, key); 964 if( offset<0 ){ 965 sqlite3PagerUnref(pDbPage); 966 return SQLITE_CORRUPT_BKPT; 967 } 968 assert( offset <= (int)pBt->usableSize-5 ); 969 assert( pEType!=0 ); 970 *pEType = pPtrmap[offset]; 971 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); 972 973 sqlite3PagerUnref(pDbPage); 974 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; 975 return SQLITE_OK; 976 } 977 978 #else /* if defined SQLITE_OMIT_AUTOVACUUM */ 979 #define ptrmapPut(w,x,y,z,rc) 980 #define ptrmapGet(w,x,y,z) SQLITE_OK 981 #define ptrmapPutOvflPtr(x, y, rc) 982 #endif 983 984 /* 985 ** Given a btree page and a cell index (0 means the first cell on 986 ** the page, 1 means the second cell, and so forth) return a pointer 987 ** to the cell content. 988 ** 989 ** findCellPastPtr() does the same except it skips past the initial 990 ** 4-byte child pointer found on interior pages, if there is one. 991 ** 992 ** This routine works only for pages that do not contain overflow cells. 993 */ 994 #define findCell(P,I) \ 995 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 996 #define findCellPastPtr(P,I) \ 997 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 998 999 1000 /* 1001 ** This is common tail processing for btreeParseCellPtr() and 1002 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely 1003 ** on a single B-tree page. Make necessary adjustments to the CellInfo 1004 ** structure. 1005 */ 1006 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( 1007 MemPage *pPage, /* Page containing the cell */ 1008 u8 *pCell, /* Pointer to the cell text. */ 1009 CellInfo *pInfo /* Fill in this structure */ 1010 ){ 1011 /* If the payload will not fit completely on the local page, we have 1012 ** to decide how much to store locally and how much to spill onto 1013 ** overflow pages. The strategy is to minimize the amount of unused 1014 ** space on overflow pages while keeping the amount of local storage 1015 ** in between minLocal and maxLocal. 1016 ** 1017 ** Warning: changing the way overflow payload is distributed in any 1018 ** way will result in an incompatible file format. 1019 */ 1020 int minLocal; /* Minimum amount of payload held locally */ 1021 int maxLocal; /* Maximum amount of payload held locally */ 1022 int surplus; /* Overflow payload available for local storage */ 1023 1024 minLocal = pPage->minLocal; 1025 maxLocal = pPage->maxLocal; 1026 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); 1027 testcase( surplus==maxLocal ); 1028 testcase( surplus==maxLocal+1 ); 1029 if( surplus <= maxLocal ){ 1030 pInfo->nLocal = (u16)surplus; 1031 }else{ 1032 pInfo->nLocal = (u16)minLocal; 1033 } 1034 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell); 1035 pInfo->nSize = pInfo->iOverflow + 4; 1036 } 1037 1038 /* 1039 ** The following routines are implementations of the MemPage.xParseCell() 1040 ** method. 1041 ** 1042 ** Parse a cell content block and fill in the CellInfo structure. 1043 ** 1044 ** btreeParseCellPtr() => table btree leaf nodes 1045 ** btreeParseCellNoPayload() => table btree internal nodes 1046 ** btreeParseCellPtrIndex() => index btree nodes 1047 ** 1048 ** There is also a wrapper function btreeParseCell() that works for 1049 ** all MemPage types and that references the cell by index rather than 1050 ** by pointer. 1051 */ 1052 static void btreeParseCellPtrNoPayload( 1053 MemPage *pPage, /* Page containing the cell */ 1054 u8 *pCell, /* Pointer to the cell text. */ 1055 CellInfo *pInfo /* Fill in this structure */ 1056 ){ 1057 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1058 assert( pPage->leaf==0 ); 1059 assert( pPage->noPayload ); 1060 assert( pPage->childPtrSize==4 ); 1061 #ifndef SQLITE_DEBUG 1062 UNUSED_PARAMETER(pPage); 1063 #endif 1064 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); 1065 pInfo->nPayload = 0; 1066 pInfo->nLocal = 0; 1067 pInfo->iOverflow = 0; 1068 pInfo->pPayload = 0; 1069 return; 1070 } 1071 static void btreeParseCellPtr( 1072 MemPage *pPage, /* Page containing the cell */ 1073 u8 *pCell, /* Pointer to the cell text. */ 1074 CellInfo *pInfo /* Fill in this structure */ 1075 ){ 1076 u8 *pIter; /* For scanning through pCell */ 1077 u32 nPayload; /* Number of bytes of cell payload */ 1078 u64 iKey; /* Extracted Key value */ 1079 1080 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1081 assert( pPage->leaf==0 || pPage->leaf==1 ); 1082 assert( pPage->intKeyLeaf || pPage->noPayload ); 1083 assert( pPage->noPayload==0 ); 1084 assert( pPage->intKeyLeaf ); 1085 assert( pPage->childPtrSize==0 ); 1086 pIter = pCell; 1087 1088 /* The next block of code is equivalent to: 1089 ** 1090 ** pIter += getVarint32(pIter, nPayload); 1091 ** 1092 ** The code is inlined to avoid a function call. 1093 */ 1094 nPayload = *pIter; 1095 if( nPayload>=0x80 ){ 1096 u8 *pEnd = &pIter[8]; 1097 nPayload &= 0x7f; 1098 do{ 1099 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1100 }while( (*pIter)>=0x80 && pIter<pEnd ); 1101 } 1102 pIter++; 1103 1104 /* The next block of code is equivalent to: 1105 ** 1106 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); 1107 ** 1108 ** The code is inlined to avoid a function call. 1109 */ 1110 iKey = *pIter; 1111 if( iKey>=0x80 ){ 1112 u8 *pEnd = &pIter[7]; 1113 iKey &= 0x7f; 1114 while(1){ 1115 iKey = (iKey<<7) | (*++pIter & 0x7f); 1116 if( (*pIter)<0x80 ) break; 1117 if( pIter>=pEnd ){ 1118 iKey = (iKey<<8) | *++pIter; 1119 break; 1120 } 1121 } 1122 } 1123 pIter++; 1124 1125 pInfo->nKey = *(i64*)&iKey; 1126 pInfo->nPayload = nPayload; 1127 pInfo->pPayload = pIter; 1128 testcase( nPayload==pPage->maxLocal ); 1129 testcase( nPayload==pPage->maxLocal+1 ); 1130 if( nPayload<=pPage->maxLocal ){ 1131 /* This is the (easy) common case where the entire payload fits 1132 ** on the local page. No overflow is required. 1133 */ 1134 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1135 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1136 pInfo->nLocal = (u16)nPayload; 1137 pInfo->iOverflow = 0; 1138 }else{ 1139 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1140 } 1141 } 1142 static void btreeParseCellPtrIndex( 1143 MemPage *pPage, /* Page containing the cell */ 1144 u8 *pCell, /* Pointer to the cell text. */ 1145 CellInfo *pInfo /* Fill in this structure */ 1146 ){ 1147 u8 *pIter; /* For scanning through pCell */ 1148 u32 nPayload; /* Number of bytes of cell payload */ 1149 1150 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1151 assert( pPage->leaf==0 || pPage->leaf==1 ); 1152 assert( pPage->intKeyLeaf==0 ); 1153 assert( pPage->noPayload==0 ); 1154 pIter = pCell + pPage->childPtrSize; 1155 nPayload = *pIter; 1156 if( nPayload>=0x80 ){ 1157 u8 *pEnd = &pIter[8]; 1158 nPayload &= 0x7f; 1159 do{ 1160 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1161 }while( *(pIter)>=0x80 && pIter<pEnd ); 1162 } 1163 pIter++; 1164 pInfo->nKey = nPayload; 1165 pInfo->nPayload = nPayload; 1166 pInfo->pPayload = pIter; 1167 testcase( nPayload==pPage->maxLocal ); 1168 testcase( nPayload==pPage->maxLocal+1 ); 1169 if( nPayload<=pPage->maxLocal ){ 1170 /* This is the (easy) common case where the entire payload fits 1171 ** on the local page. No overflow is required. 1172 */ 1173 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1174 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1175 pInfo->nLocal = (u16)nPayload; 1176 pInfo->iOverflow = 0; 1177 }else{ 1178 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1179 } 1180 } 1181 static void btreeParseCell( 1182 MemPage *pPage, /* Page containing the cell */ 1183 int iCell, /* The cell index. First cell is 0 */ 1184 CellInfo *pInfo /* Fill in this structure */ 1185 ){ 1186 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); 1187 } 1188 1189 /* 1190 ** The following routines are implementations of the MemPage.xCellSize 1191 ** method. 1192 ** 1193 ** Compute the total number of bytes that a Cell needs in the cell 1194 ** data area of the btree-page. The return number includes the cell 1195 ** data header and the local payload, but not any overflow page or 1196 ** the space used by the cell pointer. 1197 ** 1198 ** cellSizePtrNoPayload() => table internal nodes 1199 ** cellSizePtr() => all index nodes & table leaf nodes 1200 */ 1201 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ 1202 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ 1203 u8 *pEnd; /* End mark for a varint */ 1204 u32 nSize; /* Size value to return */ 1205 1206 #ifdef SQLITE_DEBUG 1207 /* The value returned by this function should always be the same as 1208 ** the (CellInfo.nSize) value found by doing a full parse of the 1209 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1210 ** this function verifies that this invariant is not violated. */ 1211 CellInfo debuginfo; 1212 pPage->xParseCell(pPage, pCell, &debuginfo); 1213 #endif 1214 1215 assert( pPage->noPayload==0 ); 1216 nSize = *pIter; 1217 if( nSize>=0x80 ){ 1218 pEnd = &pIter[8]; 1219 nSize &= 0x7f; 1220 do{ 1221 nSize = (nSize<<7) | (*++pIter & 0x7f); 1222 }while( *(pIter)>=0x80 && pIter<pEnd ); 1223 } 1224 pIter++; 1225 if( pPage->intKey ){ 1226 /* pIter now points at the 64-bit integer key value, a variable length 1227 ** integer. The following block moves pIter to point at the first byte 1228 ** past the end of the key value. */ 1229 pEnd = &pIter[9]; 1230 while( (*pIter++)&0x80 && pIter<pEnd ); 1231 } 1232 testcase( nSize==pPage->maxLocal ); 1233 testcase( nSize==pPage->maxLocal+1 ); 1234 if( nSize<=pPage->maxLocal ){ 1235 nSize += (u32)(pIter - pCell); 1236 if( nSize<4 ) nSize = 4; 1237 }else{ 1238 int minLocal = pPage->minLocal; 1239 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); 1240 testcase( nSize==pPage->maxLocal ); 1241 testcase( nSize==pPage->maxLocal+1 ); 1242 if( nSize>pPage->maxLocal ){ 1243 nSize = minLocal; 1244 } 1245 nSize += 4 + (u16)(pIter - pCell); 1246 } 1247 assert( nSize==debuginfo.nSize || CORRUPT_DB ); 1248 return (u16)nSize; 1249 } 1250 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ 1251 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ 1252 u8 *pEnd; /* End mark for a varint */ 1253 1254 #ifdef SQLITE_DEBUG 1255 /* The value returned by this function should always be the same as 1256 ** the (CellInfo.nSize) value found by doing a full parse of the 1257 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1258 ** this function verifies that this invariant is not violated. */ 1259 CellInfo debuginfo; 1260 pPage->xParseCell(pPage, pCell, &debuginfo); 1261 #else 1262 UNUSED_PARAMETER(pPage); 1263 #endif 1264 1265 assert( pPage->childPtrSize==4 ); 1266 pEnd = pIter + 9; 1267 while( (*pIter++)&0x80 && pIter<pEnd ); 1268 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB ); 1269 return (u16)(pIter - pCell); 1270 } 1271 1272 1273 #ifdef SQLITE_DEBUG 1274 /* This variation on cellSizePtr() is used inside of assert() statements 1275 ** only. */ 1276 static u16 cellSize(MemPage *pPage, int iCell){ 1277 return pPage->xCellSize(pPage, findCell(pPage, iCell)); 1278 } 1279 #endif 1280 1281 #ifndef SQLITE_OMIT_AUTOVACUUM 1282 /* 1283 ** If the cell pCell, part of page pPage contains a pointer 1284 ** to an overflow page, insert an entry into the pointer-map 1285 ** for the overflow page. 1286 */ 1287 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ 1288 CellInfo info; 1289 if( *pRC ) return; 1290 assert( pCell!=0 ); 1291 pPage->xParseCell(pPage, pCell, &info); 1292 if( info.iOverflow ){ 1293 Pgno ovfl = get4byte(&pCell[info.iOverflow]); 1294 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); 1295 } 1296 } 1297 #endif 1298 1299 1300 /* 1301 ** Defragment the page given. All Cells are moved to the 1302 ** end of the page and all free space is collected into one 1303 ** big FreeBlk that occurs in between the header and cell 1304 ** pointer array and the cell content area. 1305 ** 1306 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a 1307 ** b-tree page so that there are no freeblocks or fragment bytes, all 1308 ** unused bytes are contained in the unallocated space region, and all 1309 ** cells are packed tightly at the end of the page. 1310 */ 1311 static int defragmentPage(MemPage *pPage){ 1312 int i; /* Loop counter */ 1313 int pc; /* Address of the i-th cell */ 1314 int hdr; /* Offset to the page header */ 1315 int size; /* Size of a cell */ 1316 int usableSize; /* Number of usable bytes on a page */ 1317 int cellOffset; /* Offset to the cell pointer array */ 1318 int cbrk; /* Offset to the cell content area */ 1319 int nCell; /* Number of cells on the page */ 1320 unsigned char *data; /* The page data */ 1321 unsigned char *temp; /* Temp area for cell content */ 1322 unsigned char *src; /* Source of content */ 1323 int iCellFirst; /* First allowable cell index */ 1324 int iCellLast; /* Last possible cell index */ 1325 1326 1327 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1328 assert( pPage->pBt!=0 ); 1329 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); 1330 assert( pPage->nOverflow==0 ); 1331 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1332 temp = 0; 1333 src = data = pPage->aData; 1334 hdr = pPage->hdrOffset; 1335 cellOffset = pPage->cellOffset; 1336 nCell = pPage->nCell; 1337 assert( nCell==get2byte(&data[hdr+3]) ); 1338 usableSize = pPage->pBt->usableSize; 1339 cbrk = usableSize; 1340 iCellFirst = cellOffset + 2*nCell; 1341 iCellLast = usableSize - 4; 1342 for(i=0; i<nCell; i++){ 1343 u8 *pAddr; /* The i-th cell pointer */ 1344 pAddr = &data[cellOffset + i*2]; 1345 pc = get2byte(pAddr); 1346 testcase( pc==iCellFirst ); 1347 testcase( pc==iCellLast ); 1348 /* These conditions have already been verified in btreeInitPage() 1349 ** if PRAGMA cell_size_check=ON. 1350 */ 1351 if( pc<iCellFirst || pc>iCellLast ){ 1352 return SQLITE_CORRUPT_BKPT; 1353 } 1354 assert( pc>=iCellFirst && pc<=iCellLast ); 1355 size = pPage->xCellSize(pPage, &src[pc]); 1356 cbrk -= size; 1357 if( cbrk<iCellFirst || pc+size>usableSize ){ 1358 return SQLITE_CORRUPT_BKPT; 1359 } 1360 assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); 1361 testcase( cbrk+size==usableSize ); 1362 testcase( pc+size==usableSize ); 1363 put2byte(pAddr, cbrk); 1364 if( temp==0 ){ 1365 int x; 1366 if( cbrk==pc ) continue; 1367 temp = sqlite3PagerTempSpace(pPage->pBt->pPager); 1368 x = get2byte(&data[hdr+5]); 1369 memcpy(&temp[x], &data[x], (cbrk+size) - x); 1370 src = temp; 1371 } 1372 memcpy(&data[cbrk], &src[pc], size); 1373 } 1374 assert( cbrk>=iCellFirst ); 1375 put2byte(&data[hdr+5], cbrk); 1376 data[hdr+1] = 0; 1377 data[hdr+2] = 0; 1378 data[hdr+7] = 0; 1379 memset(&data[iCellFirst], 0, cbrk-iCellFirst); 1380 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1381 if( cbrk-iCellFirst!=pPage->nFree ){ 1382 return SQLITE_CORRUPT_BKPT; 1383 } 1384 return SQLITE_OK; 1385 } 1386 1387 /* 1388 ** Search the free-list on page pPg for space to store a cell nByte bytes in 1389 ** size. If one can be found, return a pointer to the space and remove it 1390 ** from the free-list. 1391 ** 1392 ** If no suitable space can be found on the free-list, return NULL. 1393 ** 1394 ** This function may detect corruption within pPg. If corruption is 1395 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. 1396 ** 1397 ** Slots on the free list that are between 1 and 3 bytes larger than nByte 1398 ** will be ignored if adding the extra space to the fragmentation count 1399 ** causes the fragmentation count to exceed 60. 1400 */ 1401 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ 1402 const int hdr = pPg->hdrOffset; 1403 u8 * const aData = pPg->aData; 1404 int iAddr = hdr + 1; 1405 int pc = get2byte(&aData[iAddr]); 1406 int x; 1407 int usableSize = pPg->pBt->usableSize; 1408 1409 assert( pc>0 ); 1410 do{ 1411 int size; /* Size of the free slot */ 1412 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of 1413 ** increasing offset. */ 1414 if( pc>usableSize-4 || pc<iAddr+4 ){ 1415 *pRc = SQLITE_CORRUPT_BKPT; 1416 return 0; 1417 } 1418 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each 1419 ** freeblock form a big-endian integer which is the size of the freeblock 1420 ** in bytes, including the 4-byte header. */ 1421 size = get2byte(&aData[pc+2]); 1422 if( (x = size - nByte)>=0 ){ 1423 testcase( x==4 ); 1424 testcase( x==3 ); 1425 if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){ 1426 *pRc = SQLITE_CORRUPT_BKPT; 1427 return 0; 1428 }else if( x<4 ){ 1429 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total 1430 ** number of bytes in fragments may not exceed 60. */ 1431 if( aData[hdr+7]>57 ) return 0; 1432 1433 /* Remove the slot from the free-list. Update the number of 1434 ** fragmented bytes within the page. */ 1435 memcpy(&aData[iAddr], &aData[pc], 2); 1436 aData[hdr+7] += (u8)x; 1437 }else{ 1438 /* The slot remains on the free-list. Reduce its size to account 1439 ** for the portion used by the new allocation. */ 1440 put2byte(&aData[pc+2], x); 1441 } 1442 return &aData[pc + x]; 1443 } 1444 iAddr = pc; 1445 pc = get2byte(&aData[pc]); 1446 }while( pc ); 1447 1448 return 0; 1449 } 1450 1451 /* 1452 ** Allocate nByte bytes of space from within the B-Tree page passed 1453 ** as the first argument. Write into *pIdx the index into pPage->aData[] 1454 ** of the first byte of allocated space. Return either SQLITE_OK or 1455 ** an error code (usually SQLITE_CORRUPT). 1456 ** 1457 ** The caller guarantees that there is sufficient space to make the 1458 ** allocation. This routine might need to defragment in order to bring 1459 ** all the space together, however. This routine will avoid using 1460 ** the first two bytes past the cell pointer area since presumably this 1461 ** allocation is being made in order to insert a new cell, so we will 1462 ** also end up needing a new cell pointer. 1463 */ 1464 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ 1465 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ 1466 u8 * const data = pPage->aData; /* Local cache of pPage->aData */ 1467 int top; /* First byte of cell content area */ 1468 int rc = SQLITE_OK; /* Integer return code */ 1469 int gap; /* First byte of gap between cell pointers and cell content */ 1470 1471 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1472 assert( pPage->pBt ); 1473 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1474 assert( nByte>=0 ); /* Minimum cell size is 4 */ 1475 assert( pPage->nFree>=nByte ); 1476 assert( pPage->nOverflow==0 ); 1477 assert( nByte < (int)(pPage->pBt->usableSize-8) ); 1478 1479 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); 1480 gap = pPage->cellOffset + 2*pPage->nCell; 1481 assert( gap<=65536 ); 1482 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size 1483 ** and the reserved space is zero (the usual value for reserved space) 1484 ** then the cell content offset of an empty page wants to be 65536. 1485 ** However, that integer is too large to be stored in a 2-byte unsigned 1486 ** integer, so a value of 0 is used in its place. */ 1487 top = get2byte(&data[hdr+5]); 1488 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */ 1489 if( gap>top ){ 1490 if( top==0 && pPage->pBt->usableSize==65536 ){ 1491 top = 65536; 1492 }else{ 1493 return SQLITE_CORRUPT_BKPT; 1494 } 1495 } 1496 1497 /* If there is enough space between gap and top for one more cell pointer 1498 ** array entry offset, and if the freelist is not empty, then search the 1499 ** freelist looking for a free slot big enough to satisfy the request. 1500 */ 1501 testcase( gap+2==top ); 1502 testcase( gap+1==top ); 1503 testcase( gap==top ); 1504 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ 1505 u8 *pSpace = pageFindSlot(pPage, nByte, &rc); 1506 if( pSpace ){ 1507 assert( pSpace>=data && (pSpace - data)<65536 ); 1508 *pIdx = (int)(pSpace - data); 1509 return SQLITE_OK; 1510 }else if( rc ){ 1511 return rc; 1512 } 1513 } 1514 1515 /* The request could not be fulfilled using a freelist slot. Check 1516 ** to see if defragmentation is necessary. 1517 */ 1518 testcase( gap+2+nByte==top ); 1519 if( gap+2+nByte>top ){ 1520 assert( pPage->nCell>0 || CORRUPT_DB ); 1521 rc = defragmentPage(pPage); 1522 if( rc ) return rc; 1523 top = get2byteNotZero(&data[hdr+5]); 1524 assert( gap+nByte<=top ); 1525 } 1526 1527 1528 /* Allocate memory from the gap in between the cell pointer array 1529 ** and the cell content area. The btreeInitPage() call has already 1530 ** validated the freelist. Given that the freelist is valid, there 1531 ** is no way that the allocation can extend off the end of the page. 1532 ** The assert() below verifies the previous sentence. 1533 */ 1534 top -= nByte; 1535 put2byte(&data[hdr+5], top); 1536 assert( top+nByte <= (int)pPage->pBt->usableSize ); 1537 *pIdx = top; 1538 return SQLITE_OK; 1539 } 1540 1541 /* 1542 ** Return a section of the pPage->aData to the freelist. 1543 ** The first byte of the new free block is pPage->aData[iStart] 1544 ** and the size of the block is iSize bytes. 1545 ** 1546 ** Adjacent freeblocks are coalesced. 1547 ** 1548 ** Note that even though the freeblock list was checked by btreeInitPage(), 1549 ** that routine will not detect overlap between cells or freeblocks. Nor 1550 ** does it detect cells or freeblocks that encrouch into the reserved bytes 1551 ** at the end of the page. So do additional corruption checks inside this 1552 ** routine and return SQLITE_CORRUPT if any problems are found. 1553 */ 1554 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ 1555 u16 iPtr; /* Address of ptr to next freeblock */ 1556 u16 iFreeBlk; /* Address of the next freeblock */ 1557 u8 hdr; /* Page header size. 0 or 100 */ 1558 u8 nFrag = 0; /* Reduction in fragmentation */ 1559 u16 iOrigSize = iSize; /* Original value of iSize */ 1560 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */ 1561 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ 1562 unsigned char *data = pPage->aData; /* Page content */ 1563 1564 assert( pPage->pBt!=0 ); 1565 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1566 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); 1567 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); 1568 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1569 assert( iSize>=4 ); /* Minimum cell size is 4 */ 1570 assert( iStart<=iLast ); 1571 1572 /* Overwrite deleted information with zeros when the secure_delete 1573 ** option is enabled */ 1574 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ 1575 memset(&data[iStart], 0, iSize); 1576 } 1577 1578 /* The list of freeblocks must be in ascending order. Find the 1579 ** spot on the list where iStart should be inserted. 1580 */ 1581 hdr = pPage->hdrOffset; 1582 iPtr = hdr + 1; 1583 if( data[iPtr+1]==0 && data[iPtr]==0 ){ 1584 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ 1585 }else{ 1586 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){ 1587 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT; 1588 iPtr = iFreeBlk; 1589 } 1590 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT; 1591 assert( iFreeBlk>iPtr || iFreeBlk==0 ); 1592 1593 /* At this point: 1594 ** iFreeBlk: First freeblock after iStart, or zero if none 1595 ** iPtr: The address of a pointer to iFreeBlk 1596 ** 1597 ** Check to see if iFreeBlk should be coalesced onto the end of iStart. 1598 */ 1599 if( iFreeBlk && iEnd+3>=iFreeBlk ){ 1600 nFrag = iFreeBlk - iEnd; 1601 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT; 1602 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); 1603 if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT; 1604 iSize = iEnd - iStart; 1605 iFreeBlk = get2byte(&data[iFreeBlk]); 1606 } 1607 1608 /* If iPtr is another freeblock (that is, if iPtr is not the freelist 1609 ** pointer in the page header) then check to see if iStart should be 1610 ** coalesced onto the end of iPtr. 1611 */ 1612 if( iPtr>hdr+1 ){ 1613 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); 1614 if( iPtrEnd+3>=iStart ){ 1615 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT; 1616 nFrag += iStart - iPtrEnd; 1617 iSize = iEnd - iPtr; 1618 iStart = iPtr; 1619 } 1620 } 1621 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT; 1622 data[hdr+7] -= nFrag; 1623 } 1624 if( iStart==get2byte(&data[hdr+5]) ){ 1625 /* The new freeblock is at the beginning of the cell content area, 1626 ** so just extend the cell content area rather than create another 1627 ** freelist entry */ 1628 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT; 1629 put2byte(&data[hdr+1], iFreeBlk); 1630 put2byte(&data[hdr+5], iEnd); 1631 }else{ 1632 /* Insert the new freeblock into the freelist */ 1633 put2byte(&data[iPtr], iStart); 1634 put2byte(&data[iStart], iFreeBlk); 1635 put2byte(&data[iStart+2], iSize); 1636 } 1637 pPage->nFree += iOrigSize; 1638 return SQLITE_OK; 1639 } 1640 1641 /* 1642 ** Decode the flags byte (the first byte of the header) for a page 1643 ** and initialize fields of the MemPage structure accordingly. 1644 ** 1645 ** Only the following combinations are supported. Anything different 1646 ** indicates a corrupt database files: 1647 ** 1648 ** PTF_ZERODATA 1649 ** PTF_ZERODATA | PTF_LEAF 1650 ** PTF_LEAFDATA | PTF_INTKEY 1651 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF 1652 */ 1653 static int decodeFlags(MemPage *pPage, int flagByte){ 1654 BtShared *pBt; /* A copy of pPage->pBt */ 1655 1656 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); 1657 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1658 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); 1659 flagByte &= ~PTF_LEAF; 1660 pPage->childPtrSize = 4-4*pPage->leaf; 1661 pPage->xCellSize = cellSizePtr; 1662 pBt = pPage->pBt; 1663 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ 1664 /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior 1665 ** table b-tree page. */ 1666 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); 1667 /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf 1668 ** table b-tree page. */ 1669 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); 1670 pPage->intKey = 1; 1671 if( pPage->leaf ){ 1672 pPage->intKeyLeaf = 1; 1673 pPage->noPayload = 0; 1674 pPage->xParseCell = btreeParseCellPtr; 1675 }else{ 1676 pPage->intKeyLeaf = 0; 1677 pPage->noPayload = 1; 1678 pPage->xCellSize = cellSizePtrNoPayload; 1679 pPage->xParseCell = btreeParseCellPtrNoPayload; 1680 } 1681 pPage->maxLocal = pBt->maxLeaf; 1682 pPage->minLocal = pBt->minLeaf; 1683 }else if( flagByte==PTF_ZERODATA ){ 1684 /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior 1685 ** index b-tree page. */ 1686 assert( (PTF_ZERODATA)==2 ); 1687 /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf 1688 ** index b-tree page. */ 1689 assert( (PTF_ZERODATA|PTF_LEAF)==10 ); 1690 pPage->intKey = 0; 1691 pPage->intKeyLeaf = 0; 1692 pPage->noPayload = 0; 1693 pPage->xParseCell = btreeParseCellPtrIndex; 1694 pPage->maxLocal = pBt->maxLocal; 1695 pPage->minLocal = pBt->minLocal; 1696 }else{ 1697 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is 1698 ** an error. */ 1699 return SQLITE_CORRUPT_BKPT; 1700 } 1701 pPage->max1bytePayload = pBt->max1bytePayload; 1702 return SQLITE_OK; 1703 } 1704 1705 /* 1706 ** Initialize the auxiliary information for a disk block. 1707 ** 1708 ** Return SQLITE_OK on success. If we see that the page does 1709 ** not contain a well-formed database page, then return 1710 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not 1711 ** guarantee that the page is well-formed. It only shows that 1712 ** we failed to detect any corruption. 1713 */ 1714 static int btreeInitPage(MemPage *pPage){ 1715 1716 assert( pPage->pBt!=0 ); 1717 assert( pPage->pBt->db!=0 ); 1718 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1719 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); 1720 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); 1721 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); 1722 1723 if( !pPage->isInit ){ 1724 u16 pc; /* Address of a freeblock within pPage->aData[] */ 1725 u8 hdr; /* Offset to beginning of page header */ 1726 u8 *data; /* Equal to pPage->aData */ 1727 BtShared *pBt; /* The main btree structure */ 1728 int usableSize; /* Amount of usable space on each page */ 1729 u16 cellOffset; /* Offset from start of page to first cell pointer */ 1730 int nFree; /* Number of unused bytes on the page */ 1731 int top; /* First byte of the cell content area */ 1732 int iCellFirst; /* First allowable cell or freeblock offset */ 1733 int iCellLast; /* Last possible cell or freeblock offset */ 1734 1735 pBt = pPage->pBt; 1736 1737 hdr = pPage->hdrOffset; 1738 data = pPage->aData; 1739 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating 1740 ** the b-tree page type. */ 1741 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; 1742 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 1743 pPage->maskPage = (u16)(pBt->pageSize - 1); 1744 pPage->nOverflow = 0; 1745 usableSize = pBt->usableSize; 1746 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize; 1747 pPage->aDataEnd = &data[usableSize]; 1748 pPage->aCellIdx = &data[cellOffset]; 1749 pPage->aDataOfst = &data[pPage->childPtrSize]; 1750 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates 1751 ** the start of the cell content area. A zero value for this integer is 1752 ** interpreted as 65536. */ 1753 top = get2byteNotZero(&data[hdr+5]); 1754 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 1755 ** number of cells on the page. */ 1756 pPage->nCell = get2byte(&data[hdr+3]); 1757 if( pPage->nCell>MX_CELL(pBt) ){ 1758 /* To many cells for a single page. The page must be corrupt */ 1759 return SQLITE_CORRUPT_BKPT; 1760 } 1761 testcase( pPage->nCell==MX_CELL(pBt) ); 1762 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only 1763 ** possible for a root page of a table that contains no rows) then the 1764 ** offset to the cell content area will equal the page size minus the 1765 ** bytes of reserved space. */ 1766 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB ); 1767 1768 /* A malformed database page might cause us to read past the end 1769 ** of page when parsing a cell. 1770 ** 1771 ** The following block of code checks early to see if a cell extends 1772 ** past the end of a page boundary and causes SQLITE_CORRUPT to be 1773 ** returned if it does. 1774 */ 1775 iCellFirst = cellOffset + 2*pPage->nCell; 1776 iCellLast = usableSize - 4; 1777 if( pBt->db->flags & SQLITE_CellSizeCk ){ 1778 int i; /* Index into the cell pointer array */ 1779 int sz; /* Size of a cell */ 1780 1781 if( !pPage->leaf ) iCellLast--; 1782 for(i=0; i<pPage->nCell; i++){ 1783 pc = get2byteAligned(&data[cellOffset+i*2]); 1784 testcase( pc==iCellFirst ); 1785 testcase( pc==iCellLast ); 1786 if( pc<iCellFirst || pc>iCellLast ){ 1787 return SQLITE_CORRUPT_BKPT; 1788 } 1789 sz = pPage->xCellSize(pPage, &data[pc]); 1790 testcase( pc+sz==usableSize ); 1791 if( pc+sz>usableSize ){ 1792 return SQLITE_CORRUPT_BKPT; 1793 } 1794 } 1795 if( !pPage->leaf ) iCellLast++; 1796 } 1797 1798 /* Compute the total free space on the page 1799 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the 1800 ** start of the first freeblock on the page, or is zero if there are no 1801 ** freeblocks. */ 1802 pc = get2byte(&data[hdr+1]); 1803 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ 1804 while( pc>0 ){ 1805 u16 next, size; 1806 if( pc<iCellFirst || pc>iCellLast ){ 1807 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will 1808 ** always be at least one cell before the first freeblock. 1809 ** 1810 ** Or, the freeblock is off the end of the page 1811 */ 1812 return SQLITE_CORRUPT_BKPT; 1813 } 1814 next = get2byte(&data[pc]); 1815 size = get2byte(&data[pc+2]); 1816 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ 1817 /* Free blocks must be in ascending order. And the last byte of 1818 ** the free-block must lie on the database page. */ 1819 return SQLITE_CORRUPT_BKPT; 1820 } 1821 nFree = nFree + size; 1822 pc = next; 1823 } 1824 1825 /* At this point, nFree contains the sum of the offset to the start 1826 ** of the cell-content area plus the number of free bytes within 1827 ** the cell-content area. If this is greater than the usable-size 1828 ** of the page, then the page must be corrupted. This check also 1829 ** serves to verify that the offset to the start of the cell-content 1830 ** area, according to the page header, lies within the page. 1831 */ 1832 if( nFree>usableSize ){ 1833 return SQLITE_CORRUPT_BKPT; 1834 } 1835 pPage->nFree = (u16)(nFree - iCellFirst); 1836 pPage->isInit = 1; 1837 } 1838 return SQLITE_OK; 1839 } 1840 1841 /* 1842 ** Set up a raw page so that it looks like a database page holding 1843 ** no entries. 1844 */ 1845 static void zeroPage(MemPage *pPage, int flags){ 1846 unsigned char *data = pPage->aData; 1847 BtShared *pBt = pPage->pBt; 1848 u8 hdr = pPage->hdrOffset; 1849 u16 first; 1850 1851 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); 1852 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 1853 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); 1854 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1855 assert( sqlite3_mutex_held(pBt->mutex) ); 1856 if( pBt->btsFlags & BTS_SECURE_DELETE ){ 1857 memset(&data[hdr], 0, pBt->usableSize - hdr); 1858 } 1859 data[hdr] = (char)flags; 1860 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); 1861 memset(&data[hdr+1], 0, 4); 1862 data[hdr+7] = 0; 1863 put2byte(&data[hdr+5], pBt->usableSize); 1864 pPage->nFree = (u16)(pBt->usableSize - first); 1865 decodeFlags(pPage, flags); 1866 pPage->cellOffset = first; 1867 pPage->aDataEnd = &data[pBt->usableSize]; 1868 pPage->aCellIdx = &data[first]; 1869 pPage->aDataOfst = &data[pPage->childPtrSize]; 1870 pPage->nOverflow = 0; 1871 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 1872 pPage->maskPage = (u16)(pBt->pageSize - 1); 1873 pPage->nCell = 0; 1874 pPage->isInit = 1; 1875 } 1876 1877 1878 /* 1879 ** Convert a DbPage obtained from the pager into a MemPage used by 1880 ** the btree layer. 1881 */ 1882 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ 1883 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); 1884 pPage->aData = sqlite3PagerGetData(pDbPage); 1885 pPage->pDbPage = pDbPage; 1886 pPage->pBt = pBt; 1887 pPage->pgno = pgno; 1888 pPage->hdrOffset = pgno==1 ? 100 : 0; 1889 return pPage; 1890 } 1891 1892 /* 1893 ** Get a page from the pager. Initialize the MemPage.pBt and 1894 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). 1895 ** 1896 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care 1897 ** about the content of the page at this time. So do not go to the disk 1898 ** to fetch the content. Just fill in the content with zeros for now. 1899 ** If in the future we call sqlite3PagerWrite() on this page, that 1900 ** means we have started to be concerned about content and the disk 1901 ** read should occur at that point. 1902 */ 1903 static int btreeGetPage( 1904 BtShared *pBt, /* The btree */ 1905 Pgno pgno, /* Number of the page to fetch */ 1906 MemPage **ppPage, /* Return the page in this parameter */ 1907 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 1908 ){ 1909 int rc; 1910 DbPage *pDbPage; 1911 1912 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); 1913 assert( sqlite3_mutex_held(pBt->mutex) ); 1914 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); 1915 if( rc ) return rc; 1916 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); 1917 return SQLITE_OK; 1918 } 1919 1920 /* 1921 ** Retrieve a page from the pager cache. If the requested page is not 1922 ** already in the pager cache return NULL. Initialize the MemPage.pBt and 1923 ** MemPage.aData elements if needed. 1924 */ 1925 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ 1926 DbPage *pDbPage; 1927 assert( sqlite3_mutex_held(pBt->mutex) ); 1928 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); 1929 if( pDbPage ){ 1930 return btreePageFromDbPage(pDbPage, pgno, pBt); 1931 } 1932 return 0; 1933 } 1934 1935 /* 1936 ** Return the size of the database file in pages. If there is any kind of 1937 ** error, return ((unsigned int)-1). 1938 */ 1939 static Pgno btreePagecount(BtShared *pBt){ 1940 return pBt->nPage; 1941 } 1942 u32 sqlite3BtreeLastPage(Btree *p){ 1943 assert( sqlite3BtreeHoldsMutex(p) ); 1944 assert( ((p->pBt->nPage)&0x8000000)==0 ); 1945 return btreePagecount(p->pBt); 1946 } 1947 1948 /* 1949 ** Get a page from the pager and initialize it. 1950 ** 1951 ** If pCur!=0 then the page is being fetched as part of a moveToChild() 1952 ** call. Do additional sanity checking on the page in this case. 1953 ** And if the fetch fails, this routine must decrement pCur->iPage. 1954 ** 1955 ** The page is fetched as read-write unless pCur is not NULL and is 1956 ** a read-only cursor. 1957 ** 1958 ** If an error occurs, then *ppPage is undefined. It 1959 ** may remain unchanged, or it may be set to an invalid value. 1960 */ 1961 static int getAndInitPage( 1962 BtShared *pBt, /* The database file */ 1963 Pgno pgno, /* Number of the page to get */ 1964 MemPage **ppPage, /* Write the page pointer here */ 1965 BtCursor *pCur, /* Cursor to receive the page, or NULL */ 1966 int bReadOnly /* True for a read-only page */ 1967 ){ 1968 int rc; 1969 DbPage *pDbPage; 1970 assert( sqlite3_mutex_held(pBt->mutex) ); 1971 assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] ); 1972 assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); 1973 assert( pCur==0 || pCur->iPage>0 ); 1974 1975 if( pgno>btreePagecount(pBt) ){ 1976 rc = SQLITE_CORRUPT_BKPT; 1977 goto getAndInitPage_error; 1978 } 1979 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); 1980 if( rc ){ 1981 goto getAndInitPage_error; 1982 } 1983 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); 1984 if( (*ppPage)->isInit==0 ){ 1985 rc = btreeInitPage(*ppPage); 1986 if( rc!=SQLITE_OK ){ 1987 releasePage(*ppPage); 1988 goto getAndInitPage_error; 1989 } 1990 } 1991 1992 /* If obtaining a child page for a cursor, we must verify that the page is 1993 ** compatible with the root page. */ 1994 if( pCur 1995 && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) 1996 ){ 1997 rc = SQLITE_CORRUPT_BKPT; 1998 releasePage(*ppPage); 1999 goto getAndInitPage_error; 2000 } 2001 return SQLITE_OK; 2002 2003 getAndInitPage_error: 2004 if( pCur ) pCur->iPage--; 2005 testcase( pgno==0 ); 2006 assert( pgno!=0 || rc==SQLITE_CORRUPT ); 2007 return rc; 2008 } 2009 2010 /* 2011 ** Release a MemPage. This should be called once for each prior 2012 ** call to btreeGetPage. 2013 */ 2014 static void releasePageNotNull(MemPage *pPage){ 2015 assert( pPage->aData ); 2016 assert( pPage->pBt ); 2017 assert( pPage->pDbPage!=0 ); 2018 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2019 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); 2020 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2021 sqlite3PagerUnrefNotNull(pPage->pDbPage); 2022 } 2023 static void releasePage(MemPage *pPage){ 2024 if( pPage ) releasePageNotNull(pPage); 2025 } 2026 2027 /* 2028 ** Get an unused page. 2029 ** 2030 ** This works just like btreeGetPage() with the addition: 2031 ** 2032 ** * If the page is already in use for some other purpose, immediately 2033 ** release it and return an SQLITE_CURRUPT error. 2034 ** * Make sure the isInit flag is clear 2035 */ 2036 static int btreeGetUnusedPage( 2037 BtShared *pBt, /* The btree */ 2038 Pgno pgno, /* Number of the page to fetch */ 2039 MemPage **ppPage, /* Return the page in this parameter */ 2040 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 2041 ){ 2042 int rc = btreeGetPage(pBt, pgno, ppPage, flags); 2043 if( rc==SQLITE_OK ){ 2044 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ 2045 releasePage(*ppPage); 2046 *ppPage = 0; 2047 return SQLITE_CORRUPT_BKPT; 2048 } 2049 (*ppPage)->isInit = 0; 2050 }else{ 2051 *ppPage = 0; 2052 } 2053 return rc; 2054 } 2055 2056 2057 /* 2058 ** During a rollback, when the pager reloads information into the cache 2059 ** so that the cache is restored to its original state at the start of 2060 ** the transaction, for each page restored this routine is called. 2061 ** 2062 ** This routine needs to reset the extra data section at the end of the 2063 ** page to agree with the restored data. 2064 */ 2065 static void pageReinit(DbPage *pData){ 2066 MemPage *pPage; 2067 pPage = (MemPage *)sqlite3PagerGetExtra(pData); 2068 assert( sqlite3PagerPageRefcount(pData)>0 ); 2069 if( pPage->isInit ){ 2070 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2071 pPage->isInit = 0; 2072 if( sqlite3PagerPageRefcount(pData)>1 ){ 2073 /* pPage might not be a btree page; it might be an overflow page 2074 ** or ptrmap page or a free page. In those cases, the following 2075 ** call to btreeInitPage() will likely return SQLITE_CORRUPT. 2076 ** But no harm is done by this. And it is very important that 2077 ** btreeInitPage() be called on every btree page so we make 2078 ** the call for every page that comes in for re-initing. */ 2079 btreeInitPage(pPage); 2080 } 2081 } 2082 } 2083 2084 /* 2085 ** Invoke the busy handler for a btree. 2086 */ 2087 static int btreeInvokeBusyHandler(void *pArg){ 2088 BtShared *pBt = (BtShared*)pArg; 2089 assert( pBt->db ); 2090 assert( sqlite3_mutex_held(pBt->db->mutex) ); 2091 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); 2092 } 2093 2094 /* 2095 ** Open a database file. 2096 ** 2097 ** zFilename is the name of the database file. If zFilename is NULL 2098 ** then an ephemeral database is created. The ephemeral database might 2099 ** be exclusively in memory, or it might use a disk-based memory cache. 2100 ** Either way, the ephemeral database will be automatically deleted 2101 ** when sqlite3BtreeClose() is called. 2102 ** 2103 ** If zFilename is ":memory:" then an in-memory database is created 2104 ** that is automatically destroyed when it is closed. 2105 ** 2106 ** The "flags" parameter is a bitmask that might contain bits like 2107 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. 2108 ** 2109 ** If the database is already opened in the same database connection 2110 ** and we are in shared cache mode, then the open will fail with an 2111 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared 2112 ** objects in the same database connection since doing so will lead 2113 ** to problems with locking. 2114 */ 2115 int sqlite3BtreeOpen( 2116 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ 2117 const char *zFilename, /* Name of the file containing the BTree database */ 2118 sqlite3 *db, /* Associated database handle */ 2119 Btree **ppBtree, /* Pointer to new Btree object written here */ 2120 int flags, /* Options */ 2121 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ 2122 ){ 2123 BtShared *pBt = 0; /* Shared part of btree structure */ 2124 Btree *p; /* Handle to return */ 2125 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ 2126 int rc = SQLITE_OK; /* Result code from this function */ 2127 u8 nReserve; /* Byte of unused space on each page */ 2128 unsigned char zDbHeader[100]; /* Database header content */ 2129 2130 /* True if opening an ephemeral, temporary database */ 2131 const int isTempDb = zFilename==0 || zFilename[0]==0; 2132 2133 /* Set the variable isMemdb to true for an in-memory database, or 2134 ** false for a file-based database. 2135 */ 2136 #ifdef SQLITE_OMIT_MEMORYDB 2137 const int isMemdb = 0; 2138 #else 2139 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) 2140 || (isTempDb && sqlite3TempInMemory(db)) 2141 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; 2142 #endif 2143 2144 assert( db!=0 ); 2145 assert( pVfs!=0 ); 2146 assert( sqlite3_mutex_held(db->mutex) ); 2147 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ 2148 2149 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ 2150 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); 2151 2152 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ 2153 assert( (flags & BTREE_SINGLE)==0 || isTempDb ); 2154 2155 if( isMemdb ){ 2156 flags |= BTREE_MEMORY; 2157 } 2158 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ 2159 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; 2160 } 2161 p = sqlite3MallocZero(sizeof(Btree)); 2162 if( !p ){ 2163 return SQLITE_NOMEM; 2164 } 2165 p->inTrans = TRANS_NONE; 2166 p->db = db; 2167 #ifndef SQLITE_OMIT_SHARED_CACHE 2168 p->lock.pBtree = p; 2169 p->lock.iTable = 1; 2170 #endif 2171 2172 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2173 /* 2174 ** If this Btree is a candidate for shared cache, try to find an 2175 ** existing BtShared object that we can share with 2176 */ 2177 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ 2178 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ 2179 int nFilename = sqlite3Strlen30(zFilename)+1; 2180 int nFullPathname = pVfs->mxPathname+1; 2181 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); 2182 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2183 2184 p->sharable = 1; 2185 if( !zFullPathname ){ 2186 sqlite3_free(p); 2187 return SQLITE_NOMEM; 2188 } 2189 if( isMemdb ){ 2190 memcpy(zFullPathname, zFilename, nFilename); 2191 }else{ 2192 rc = sqlite3OsFullPathname(pVfs, zFilename, 2193 nFullPathname, zFullPathname); 2194 if( rc ){ 2195 sqlite3_free(zFullPathname); 2196 sqlite3_free(p); 2197 return rc; 2198 } 2199 } 2200 #if SQLITE_THREADSAFE 2201 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); 2202 sqlite3_mutex_enter(mutexOpen); 2203 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); 2204 sqlite3_mutex_enter(mutexShared); 2205 #endif 2206 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ 2207 assert( pBt->nRef>0 ); 2208 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) 2209 && sqlite3PagerVfs(pBt->pPager)==pVfs ){ 2210 int iDb; 2211 for(iDb=db->nDb-1; iDb>=0; iDb--){ 2212 Btree *pExisting = db->aDb[iDb].pBt; 2213 if( pExisting && pExisting->pBt==pBt ){ 2214 sqlite3_mutex_leave(mutexShared); 2215 sqlite3_mutex_leave(mutexOpen); 2216 sqlite3_free(zFullPathname); 2217 sqlite3_free(p); 2218 return SQLITE_CONSTRAINT; 2219 } 2220 } 2221 p->pBt = pBt; 2222 pBt->nRef++; 2223 break; 2224 } 2225 } 2226 sqlite3_mutex_leave(mutexShared); 2227 sqlite3_free(zFullPathname); 2228 } 2229 #ifdef SQLITE_DEBUG 2230 else{ 2231 /* In debug mode, we mark all persistent databases as sharable 2232 ** even when they are not. This exercises the locking code and 2233 ** gives more opportunity for asserts(sqlite3_mutex_held()) 2234 ** statements to find locking problems. 2235 */ 2236 p->sharable = 1; 2237 } 2238 #endif 2239 } 2240 #endif 2241 if( pBt==0 ){ 2242 /* 2243 ** The following asserts make sure that structures used by the btree are 2244 ** the right size. This is to guard against size changes that result 2245 ** when compiling on a different architecture. 2246 */ 2247 assert( sizeof(i64)==8 ); 2248 assert( sizeof(u64)==8 ); 2249 assert( sizeof(u32)==4 ); 2250 assert( sizeof(u16)==2 ); 2251 assert( sizeof(Pgno)==4 ); 2252 2253 pBt = sqlite3MallocZero( sizeof(*pBt) ); 2254 if( pBt==0 ){ 2255 rc = SQLITE_NOMEM; 2256 goto btree_open_out; 2257 } 2258 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, 2259 EXTRA_SIZE, flags, vfsFlags, pageReinit); 2260 if( rc==SQLITE_OK ){ 2261 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); 2262 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); 2263 } 2264 if( rc!=SQLITE_OK ){ 2265 goto btree_open_out; 2266 } 2267 pBt->openFlags = (u8)flags; 2268 pBt->db = db; 2269 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); 2270 p->pBt = pBt; 2271 2272 pBt->pCursor = 0; 2273 pBt->pPage1 = 0; 2274 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; 2275 #ifdef SQLITE_SECURE_DELETE 2276 pBt->btsFlags |= BTS_SECURE_DELETE; 2277 #endif 2278 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 2279 ** determined by the 2-byte integer located at an offset of 16 bytes from 2280 ** the beginning of the database file. */ 2281 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); 2282 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE 2283 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ 2284 pBt->pageSize = 0; 2285 #ifndef SQLITE_OMIT_AUTOVACUUM 2286 /* If the magic name ":memory:" will create an in-memory database, then 2287 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if 2288 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if 2289 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a 2290 ** regular file-name. In this case the auto-vacuum applies as per normal. 2291 */ 2292 if( zFilename && !isMemdb ){ 2293 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); 2294 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); 2295 } 2296 #endif 2297 nReserve = 0; 2298 }else{ 2299 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is 2300 ** determined by the one-byte unsigned integer found at an offset of 20 2301 ** into the database file header. */ 2302 nReserve = zDbHeader[20]; 2303 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2304 #ifndef SQLITE_OMIT_AUTOVACUUM 2305 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); 2306 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); 2307 #endif 2308 } 2309 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2310 if( rc ) goto btree_open_out; 2311 pBt->usableSize = pBt->pageSize - nReserve; 2312 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ 2313 2314 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2315 /* Add the new BtShared object to the linked list sharable BtShareds. 2316 */ 2317 if( p->sharable ){ 2318 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2319 pBt->nRef = 1; 2320 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) 2321 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ 2322 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); 2323 if( pBt->mutex==0 ){ 2324 rc = SQLITE_NOMEM; 2325 db->mallocFailed = 0; 2326 goto btree_open_out; 2327 } 2328 } 2329 sqlite3_mutex_enter(mutexShared); 2330 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); 2331 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; 2332 sqlite3_mutex_leave(mutexShared); 2333 } 2334 #endif 2335 } 2336 2337 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2338 /* If the new Btree uses a sharable pBtShared, then link the new 2339 ** Btree into the list of all sharable Btrees for the same connection. 2340 ** The list is kept in ascending order by pBt address. 2341 */ 2342 if( p->sharable ){ 2343 int i; 2344 Btree *pSib; 2345 for(i=0; i<db->nDb; i++){ 2346 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ 2347 while( pSib->pPrev ){ pSib = pSib->pPrev; } 2348 if( p->pBt<pSib->pBt ){ 2349 p->pNext = pSib; 2350 p->pPrev = 0; 2351 pSib->pPrev = p; 2352 }else{ 2353 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){ 2354 pSib = pSib->pNext; 2355 } 2356 p->pNext = pSib->pNext; 2357 p->pPrev = pSib; 2358 if( p->pNext ){ 2359 p->pNext->pPrev = p; 2360 } 2361 pSib->pNext = p; 2362 } 2363 break; 2364 } 2365 } 2366 } 2367 #endif 2368 *ppBtree = p; 2369 2370 btree_open_out: 2371 if( rc!=SQLITE_OK ){ 2372 if( pBt && pBt->pPager ){ 2373 sqlite3PagerClose(pBt->pPager); 2374 } 2375 sqlite3_free(pBt); 2376 sqlite3_free(p); 2377 *ppBtree = 0; 2378 }else{ 2379 /* If the B-Tree was successfully opened, set the pager-cache size to the 2380 ** default value. Except, when opening on an existing shared pager-cache, 2381 ** do not change the pager-cache size. 2382 */ 2383 if( sqlite3BtreeSchema(p, 0, 0)==0 ){ 2384 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); 2385 } 2386 } 2387 if( mutexOpen ){ 2388 assert( sqlite3_mutex_held(mutexOpen) ); 2389 sqlite3_mutex_leave(mutexOpen); 2390 } 2391 return rc; 2392 } 2393 2394 /* 2395 ** Decrement the BtShared.nRef counter. When it reaches zero, 2396 ** remove the BtShared structure from the sharing list. Return 2397 ** true if the BtShared.nRef counter reaches zero and return 2398 ** false if it is still positive. 2399 */ 2400 static int removeFromSharingList(BtShared *pBt){ 2401 #ifndef SQLITE_OMIT_SHARED_CACHE 2402 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) 2403 BtShared *pList; 2404 int removed = 0; 2405 2406 assert( sqlite3_mutex_notheld(pBt->mutex) ); 2407 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) 2408 sqlite3_mutex_enter(pMaster); 2409 pBt->nRef--; 2410 if( pBt->nRef<=0 ){ 2411 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ 2412 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; 2413 }else{ 2414 pList = GLOBAL(BtShared*,sqlite3SharedCacheList); 2415 while( ALWAYS(pList) && pList->pNext!=pBt ){ 2416 pList=pList->pNext; 2417 } 2418 if( ALWAYS(pList) ){ 2419 pList->pNext = pBt->pNext; 2420 } 2421 } 2422 if( SQLITE_THREADSAFE ){ 2423 sqlite3_mutex_free(pBt->mutex); 2424 } 2425 removed = 1; 2426 } 2427 sqlite3_mutex_leave(pMaster); 2428 return removed; 2429 #else 2430 return 1; 2431 #endif 2432 } 2433 2434 /* 2435 ** Make sure pBt->pTmpSpace points to an allocation of 2436 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child 2437 ** pointer. 2438 */ 2439 static void allocateTempSpace(BtShared *pBt){ 2440 if( !pBt->pTmpSpace ){ 2441 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); 2442 2443 /* One of the uses of pBt->pTmpSpace is to format cells before 2444 ** inserting them into a leaf page (function fillInCell()). If 2445 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes 2446 ** by the various routines that manipulate binary cells. Which 2447 ** can mean that fillInCell() only initializes the first 2 or 3 2448 ** bytes of pTmpSpace, but that the first 4 bytes are copied from 2449 ** it into a database page. This is not actually a problem, but it 2450 ** does cause a valgrind error when the 1 or 2 bytes of unitialized 2451 ** data is passed to system call write(). So to avoid this error, 2452 ** zero the first 4 bytes of temp space here. 2453 ** 2454 ** Also: Provide four bytes of initialized space before the 2455 ** beginning of pTmpSpace as an area available to prepend the 2456 ** left-child pointer to the beginning of a cell. 2457 */ 2458 if( pBt->pTmpSpace ){ 2459 memset(pBt->pTmpSpace, 0, 8); 2460 pBt->pTmpSpace += 4; 2461 } 2462 } 2463 } 2464 2465 /* 2466 ** Free the pBt->pTmpSpace allocation 2467 */ 2468 static void freeTempSpace(BtShared *pBt){ 2469 if( pBt->pTmpSpace ){ 2470 pBt->pTmpSpace -= 4; 2471 sqlite3PageFree(pBt->pTmpSpace); 2472 pBt->pTmpSpace = 0; 2473 } 2474 } 2475 2476 /* 2477 ** Close an open database and invalidate all cursors. 2478 */ 2479 int sqlite3BtreeClose(Btree *p){ 2480 BtShared *pBt = p->pBt; 2481 BtCursor *pCur; 2482 2483 /* Close all cursors opened via this handle. */ 2484 assert( sqlite3_mutex_held(p->db->mutex) ); 2485 sqlite3BtreeEnter(p); 2486 pCur = pBt->pCursor; 2487 while( pCur ){ 2488 BtCursor *pTmp = pCur; 2489 pCur = pCur->pNext; 2490 if( pTmp->pBtree==p ){ 2491 sqlite3BtreeCloseCursor(pTmp); 2492 } 2493 } 2494 2495 /* Rollback any active transaction and free the handle structure. 2496 ** The call to sqlite3BtreeRollback() drops any table-locks held by 2497 ** this handle. 2498 */ 2499 sqlite3BtreeRollback(p, SQLITE_OK, 0); 2500 sqlite3BtreeLeave(p); 2501 2502 /* If there are still other outstanding references to the shared-btree 2503 ** structure, return now. The remainder of this procedure cleans 2504 ** up the shared-btree. 2505 */ 2506 assert( p->wantToLock==0 && p->locked==0 ); 2507 if( !p->sharable || removeFromSharingList(pBt) ){ 2508 /* The pBt is no longer on the sharing list, so we can access 2509 ** it without having to hold the mutex. 2510 ** 2511 ** Clean out and delete the BtShared object. 2512 */ 2513 assert( !pBt->pCursor ); 2514 sqlite3PagerClose(pBt->pPager); 2515 if( pBt->xFreeSchema && pBt->pSchema ){ 2516 pBt->xFreeSchema(pBt->pSchema); 2517 } 2518 sqlite3DbFree(0, pBt->pSchema); 2519 freeTempSpace(pBt); 2520 sqlite3_free(pBt); 2521 } 2522 2523 #ifndef SQLITE_OMIT_SHARED_CACHE 2524 assert( p->wantToLock==0 ); 2525 assert( p->locked==0 ); 2526 if( p->pPrev ) p->pPrev->pNext = p->pNext; 2527 if( p->pNext ) p->pNext->pPrev = p->pPrev; 2528 #endif 2529 2530 sqlite3_free(p); 2531 return SQLITE_OK; 2532 } 2533 2534 /* 2535 ** Change the limit on the number of pages allowed in the cache. 2536 ** 2537 ** The maximum number of cache pages is set to the absolute 2538 ** value of mxPage. If mxPage is negative, the pager will 2539 ** operate asynchronously - it will not stop to do fsync()s 2540 ** to insure data is written to the disk surface before 2541 ** continuing. Transactions still work if synchronous is off, 2542 ** and the database cannot be corrupted if this program 2543 ** crashes. But if the operating system crashes or there is 2544 ** an abrupt power failure when synchronous is off, the database 2545 ** could be left in an inconsistent and unrecoverable state. 2546 ** Synchronous is on by default so database corruption is not 2547 ** normally a worry. 2548 */ 2549 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ 2550 BtShared *pBt = p->pBt; 2551 assert( sqlite3_mutex_held(p->db->mutex) ); 2552 sqlite3BtreeEnter(p); 2553 sqlite3PagerSetCachesize(pBt->pPager, mxPage); 2554 sqlite3BtreeLeave(p); 2555 return SQLITE_OK; 2556 } 2557 2558 #if SQLITE_MAX_MMAP_SIZE>0 2559 /* 2560 ** Change the limit on the amount of the database file that may be 2561 ** memory mapped. 2562 */ 2563 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ 2564 BtShared *pBt = p->pBt; 2565 assert( sqlite3_mutex_held(p->db->mutex) ); 2566 sqlite3BtreeEnter(p); 2567 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); 2568 sqlite3BtreeLeave(p); 2569 return SQLITE_OK; 2570 } 2571 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ 2572 2573 /* 2574 ** Change the way data is synced to disk in order to increase or decrease 2575 ** how well the database resists damage due to OS crashes and power 2576 ** failures. Level 1 is the same as asynchronous (no syncs() occur and 2577 ** there is a high probability of damage) Level 2 is the default. There 2578 ** is a very low but non-zero probability of damage. Level 3 reduces the 2579 ** probability of damage to near zero but with a write performance reduction. 2580 */ 2581 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 2582 int sqlite3BtreeSetPagerFlags( 2583 Btree *p, /* The btree to set the safety level on */ 2584 unsigned pgFlags /* Various PAGER_* flags */ 2585 ){ 2586 BtShared *pBt = p->pBt; 2587 assert( sqlite3_mutex_held(p->db->mutex) ); 2588 sqlite3BtreeEnter(p); 2589 sqlite3PagerSetFlags(pBt->pPager, pgFlags); 2590 sqlite3BtreeLeave(p); 2591 return SQLITE_OK; 2592 } 2593 #endif 2594 2595 /* 2596 ** Return TRUE if the given btree is set to safety level 1. In other 2597 ** words, return TRUE if no sync() occurs on the disk files. 2598 */ 2599 int sqlite3BtreeSyncDisabled(Btree *p){ 2600 BtShared *pBt = p->pBt; 2601 int rc; 2602 assert( sqlite3_mutex_held(p->db->mutex) ); 2603 sqlite3BtreeEnter(p); 2604 assert( pBt && pBt->pPager ); 2605 rc = sqlite3PagerNosync(pBt->pPager); 2606 sqlite3BtreeLeave(p); 2607 return rc; 2608 } 2609 2610 /* 2611 ** Change the default pages size and the number of reserved bytes per page. 2612 ** Or, if the page size has already been fixed, return SQLITE_READONLY 2613 ** without changing anything. 2614 ** 2615 ** The page size must be a power of 2 between 512 and 65536. If the page 2616 ** size supplied does not meet this constraint then the page size is not 2617 ** changed. 2618 ** 2619 ** Page sizes are constrained to be a power of two so that the region 2620 ** of the database file used for locking (beginning at PENDING_BYTE, 2621 ** the first byte past the 1GB boundary, 0x40000000) needs to occur 2622 ** at the beginning of a page. 2623 ** 2624 ** If parameter nReserve is less than zero, then the number of reserved 2625 ** bytes per page is left unchanged. 2626 ** 2627 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size 2628 ** and autovacuum mode can no longer be changed. 2629 */ 2630 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ 2631 int rc = SQLITE_OK; 2632 BtShared *pBt = p->pBt; 2633 assert( nReserve>=-1 && nReserve<=255 ); 2634 sqlite3BtreeEnter(p); 2635 #if SQLITE_HAS_CODEC 2636 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve; 2637 #endif 2638 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ 2639 sqlite3BtreeLeave(p); 2640 return SQLITE_READONLY; 2641 } 2642 if( nReserve<0 ){ 2643 nReserve = pBt->pageSize - pBt->usableSize; 2644 } 2645 assert( nReserve>=0 && nReserve<=255 ); 2646 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && 2647 ((pageSize-1)&pageSize)==0 ){ 2648 assert( (pageSize & 7)==0 ); 2649 assert( !pBt->pCursor ); 2650 pBt->pageSize = (u32)pageSize; 2651 freeTempSpace(pBt); 2652 } 2653 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2654 pBt->usableSize = pBt->pageSize - (u16)nReserve; 2655 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2656 sqlite3BtreeLeave(p); 2657 return rc; 2658 } 2659 2660 /* 2661 ** Return the currently defined page size 2662 */ 2663 int sqlite3BtreeGetPageSize(Btree *p){ 2664 return p->pBt->pageSize; 2665 } 2666 2667 /* 2668 ** This function is similar to sqlite3BtreeGetReserve(), except that it 2669 ** may only be called if it is guaranteed that the b-tree mutex is already 2670 ** held. 2671 ** 2672 ** This is useful in one special case in the backup API code where it is 2673 ** known that the shared b-tree mutex is held, but the mutex on the 2674 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() 2675 ** were to be called, it might collide with some other operation on the 2676 ** database handle that owns *p, causing undefined behavior. 2677 */ 2678 int sqlite3BtreeGetReserveNoMutex(Btree *p){ 2679 int n; 2680 assert( sqlite3_mutex_held(p->pBt->mutex) ); 2681 n = p->pBt->pageSize - p->pBt->usableSize; 2682 return n; 2683 } 2684 2685 /* 2686 ** Return the number of bytes of space at the end of every page that 2687 ** are intentually left unused. This is the "reserved" space that is 2688 ** sometimes used by extensions. 2689 ** 2690 ** If SQLITE_HAS_MUTEX is defined then the number returned is the 2691 ** greater of the current reserved space and the maximum requested 2692 ** reserve space. 2693 */ 2694 int sqlite3BtreeGetOptimalReserve(Btree *p){ 2695 int n; 2696 sqlite3BtreeEnter(p); 2697 n = sqlite3BtreeGetReserveNoMutex(p); 2698 #ifdef SQLITE_HAS_CODEC 2699 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve; 2700 #endif 2701 sqlite3BtreeLeave(p); 2702 return n; 2703 } 2704 2705 2706 /* 2707 ** Set the maximum page count for a database if mxPage is positive. 2708 ** No changes are made if mxPage is 0 or negative. 2709 ** Regardless of the value of mxPage, return the maximum page count. 2710 */ 2711 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ 2712 int n; 2713 sqlite3BtreeEnter(p); 2714 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); 2715 sqlite3BtreeLeave(p); 2716 return n; 2717 } 2718 2719 /* 2720 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, 2721 ** then make no changes. Always return the value of the BTS_SECURE_DELETE 2722 ** setting after the change. 2723 */ 2724 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ 2725 int b; 2726 if( p==0 ) return 0; 2727 sqlite3BtreeEnter(p); 2728 if( newFlag>=0 ){ 2729 p->pBt->btsFlags &= ~BTS_SECURE_DELETE; 2730 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; 2731 } 2732 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; 2733 sqlite3BtreeLeave(p); 2734 return b; 2735 } 2736 2737 /* 2738 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' 2739 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it 2740 ** is disabled. The default value for the auto-vacuum property is 2741 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. 2742 */ 2743 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ 2744 #ifdef SQLITE_OMIT_AUTOVACUUM 2745 return SQLITE_READONLY; 2746 #else 2747 BtShared *pBt = p->pBt; 2748 int rc = SQLITE_OK; 2749 u8 av = (u8)autoVacuum; 2750 2751 sqlite3BtreeEnter(p); 2752 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ 2753 rc = SQLITE_READONLY; 2754 }else{ 2755 pBt->autoVacuum = av ?1:0; 2756 pBt->incrVacuum = av==2 ?1:0; 2757 } 2758 sqlite3BtreeLeave(p); 2759 return rc; 2760 #endif 2761 } 2762 2763 /* 2764 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 2765 ** enabled 1 is returned. Otherwise 0. 2766 */ 2767 int sqlite3BtreeGetAutoVacuum(Btree *p){ 2768 #ifdef SQLITE_OMIT_AUTOVACUUM 2769 return BTREE_AUTOVACUUM_NONE; 2770 #else 2771 int rc; 2772 sqlite3BtreeEnter(p); 2773 rc = ( 2774 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: 2775 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: 2776 BTREE_AUTOVACUUM_INCR 2777 ); 2778 sqlite3BtreeLeave(p); 2779 return rc; 2780 #endif 2781 } 2782 2783 2784 /* 2785 ** Get a reference to pPage1 of the database file. This will 2786 ** also acquire a readlock on that file. 2787 ** 2788 ** SQLITE_OK is returned on success. If the file is not a 2789 ** well-formed database file, then SQLITE_CORRUPT is returned. 2790 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM 2791 ** is returned if we run out of memory. 2792 */ 2793 static int lockBtree(BtShared *pBt){ 2794 int rc; /* Result code from subfunctions */ 2795 MemPage *pPage1; /* Page 1 of the database file */ 2796 int nPage; /* Number of pages in the database */ 2797 int nPageFile = 0; /* Number of pages in the database file */ 2798 int nPageHeader; /* Number of pages in the database according to hdr */ 2799 2800 assert( sqlite3_mutex_held(pBt->mutex) ); 2801 assert( pBt->pPage1==0 ); 2802 rc = sqlite3PagerSharedLock(pBt->pPager); 2803 if( rc!=SQLITE_OK ) return rc; 2804 rc = btreeGetPage(pBt, 1, &pPage1, 0); 2805 if( rc!=SQLITE_OK ) return rc; 2806 2807 /* Do some checking to help insure the file we opened really is 2808 ** a valid database file. 2809 */ 2810 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); 2811 sqlite3PagerPagecount(pBt->pPager, &nPageFile); 2812 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ 2813 nPage = nPageFile; 2814 } 2815 if( nPage>0 ){ 2816 u32 pageSize; 2817 u32 usableSize; 2818 u8 *page1 = pPage1->aData; 2819 rc = SQLITE_NOTADB; 2820 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins 2821 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d 2822 ** 61 74 20 33 00. */ 2823 if( memcmp(page1, zMagicHeader, 16)!=0 ){ 2824 goto page1_init_failed; 2825 } 2826 2827 #ifdef SQLITE_OMIT_WAL 2828 if( page1[18]>1 ){ 2829 pBt->btsFlags |= BTS_READ_ONLY; 2830 } 2831 if( page1[19]>1 ){ 2832 goto page1_init_failed; 2833 } 2834 #else 2835 if( page1[18]>2 ){ 2836 pBt->btsFlags |= BTS_READ_ONLY; 2837 } 2838 if( page1[19]>2 ){ 2839 goto page1_init_failed; 2840 } 2841 2842 /* If the write version is set to 2, this database should be accessed 2843 ** in WAL mode. If the log is not already open, open it now. Then 2844 ** return SQLITE_OK and return without populating BtShared.pPage1. 2845 ** The caller detects this and calls this function again. This is 2846 ** required as the version of page 1 currently in the page1 buffer 2847 ** may not be the latest version - there may be a newer one in the log 2848 ** file. 2849 */ 2850 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ 2851 int isOpen = 0; 2852 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); 2853 if( rc!=SQLITE_OK ){ 2854 goto page1_init_failed; 2855 }else if( isOpen==0 ){ 2856 releasePage(pPage1); 2857 return SQLITE_OK; 2858 } 2859 rc = SQLITE_NOTADB; 2860 } 2861 #endif 2862 2863 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload 2864 ** fractions and the leaf payload fraction values must be 64, 32, and 32. 2865 ** 2866 ** The original design allowed these amounts to vary, but as of 2867 ** version 3.6.0, we require them to be fixed. 2868 */ 2869 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ 2870 goto page1_init_failed; 2871 } 2872 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 2873 ** determined by the 2-byte integer located at an offset of 16 bytes from 2874 ** the beginning of the database file. */ 2875 pageSize = (page1[16]<<8) | (page1[17]<<16); 2876 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two 2877 ** between 512 and 65536 inclusive. */ 2878 if( ((pageSize-1)&pageSize)!=0 2879 || pageSize>SQLITE_MAX_PAGE_SIZE 2880 || pageSize<=256 2881 ){ 2882 goto page1_init_failed; 2883 } 2884 assert( (pageSize & 7)==0 ); 2885 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte 2886 ** integer at offset 20 is the number of bytes of space at the end of 2887 ** each page to reserve for extensions. 2888 ** 2889 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is 2890 ** determined by the one-byte unsigned integer found at an offset of 20 2891 ** into the database file header. */ 2892 usableSize = pageSize - page1[20]; 2893 if( (u32)pageSize!=pBt->pageSize ){ 2894 /* After reading the first page of the database assuming a page size 2895 ** of BtShared.pageSize, we have discovered that the page-size is 2896 ** actually pageSize. Unlock the database, leave pBt->pPage1 at 2897 ** zero and return SQLITE_OK. The caller will call this function 2898 ** again with the correct page-size. 2899 */ 2900 releasePage(pPage1); 2901 pBt->usableSize = usableSize; 2902 pBt->pageSize = pageSize; 2903 freeTempSpace(pBt); 2904 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, 2905 pageSize-usableSize); 2906 return rc; 2907 } 2908 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ 2909 rc = SQLITE_CORRUPT_BKPT; 2910 goto page1_init_failed; 2911 } 2912 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to 2913 ** be less than 480. In other words, if the page size is 512, then the 2914 ** reserved space size cannot exceed 32. */ 2915 if( usableSize<480 ){ 2916 goto page1_init_failed; 2917 } 2918 pBt->pageSize = pageSize; 2919 pBt->usableSize = usableSize; 2920 #ifndef SQLITE_OMIT_AUTOVACUUM 2921 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); 2922 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); 2923 #endif 2924 } 2925 2926 /* maxLocal is the maximum amount of payload to store locally for 2927 ** a cell. Make sure it is small enough so that at least minFanout 2928 ** cells can will fit on one page. We assume a 10-byte page header. 2929 ** Besides the payload, the cell must store: 2930 ** 2-byte pointer to the cell 2931 ** 4-byte child pointer 2932 ** 9-byte nKey value 2933 ** 4-byte nData value 2934 ** 4-byte overflow page pointer 2935 ** So a cell consists of a 2-byte pointer, a header which is as much as 2936 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow 2937 ** page pointer. 2938 */ 2939 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); 2940 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); 2941 pBt->maxLeaf = (u16)(pBt->usableSize - 35); 2942 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); 2943 if( pBt->maxLocal>127 ){ 2944 pBt->max1bytePayload = 127; 2945 }else{ 2946 pBt->max1bytePayload = (u8)pBt->maxLocal; 2947 } 2948 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); 2949 pBt->pPage1 = pPage1; 2950 pBt->nPage = nPage; 2951 return SQLITE_OK; 2952 2953 page1_init_failed: 2954 releasePage(pPage1); 2955 pBt->pPage1 = 0; 2956 return rc; 2957 } 2958 2959 #ifndef NDEBUG 2960 /* 2961 ** Return the number of cursors open on pBt. This is for use 2962 ** in assert() expressions, so it is only compiled if NDEBUG is not 2963 ** defined. 2964 ** 2965 ** Only write cursors are counted if wrOnly is true. If wrOnly is 2966 ** false then all cursors are counted. 2967 ** 2968 ** For the purposes of this routine, a cursor is any cursor that 2969 ** is capable of reading or writing to the database. Cursors that 2970 ** have been tripped into the CURSOR_FAULT state are not counted. 2971 */ 2972 static int countValidCursors(BtShared *pBt, int wrOnly){ 2973 BtCursor *pCur; 2974 int r = 0; 2975 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ 2976 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) 2977 && pCur->eState!=CURSOR_FAULT ) r++; 2978 } 2979 return r; 2980 } 2981 #endif 2982 2983 /* 2984 ** If there are no outstanding cursors and we are not in the middle 2985 ** of a transaction but there is a read lock on the database, then 2986 ** this routine unrefs the first page of the database file which 2987 ** has the effect of releasing the read lock. 2988 ** 2989 ** If there is a transaction in progress, this routine is a no-op. 2990 */ 2991 static void unlockBtreeIfUnused(BtShared *pBt){ 2992 assert( sqlite3_mutex_held(pBt->mutex) ); 2993 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); 2994 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ 2995 MemPage *pPage1 = pBt->pPage1; 2996 assert( pPage1->aData ); 2997 assert( sqlite3PagerRefcount(pBt->pPager)==1 ); 2998 pBt->pPage1 = 0; 2999 releasePageNotNull(pPage1); 3000 } 3001 } 3002 3003 /* 3004 ** If pBt points to an empty file then convert that empty file 3005 ** into a new empty database by initializing the first page of 3006 ** the database. 3007 */ 3008 static int newDatabase(BtShared *pBt){ 3009 MemPage *pP1; 3010 unsigned char *data; 3011 int rc; 3012 3013 assert( sqlite3_mutex_held(pBt->mutex) ); 3014 if( pBt->nPage>0 ){ 3015 return SQLITE_OK; 3016 } 3017 pP1 = pBt->pPage1; 3018 assert( pP1!=0 ); 3019 data = pP1->aData; 3020 rc = sqlite3PagerWrite(pP1->pDbPage); 3021 if( rc ) return rc; 3022 memcpy(data, zMagicHeader, sizeof(zMagicHeader)); 3023 assert( sizeof(zMagicHeader)==16 ); 3024 data[16] = (u8)((pBt->pageSize>>8)&0xff); 3025 data[17] = (u8)((pBt->pageSize>>16)&0xff); 3026 data[18] = 1; 3027 data[19] = 1; 3028 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); 3029 data[20] = (u8)(pBt->pageSize - pBt->usableSize); 3030 data[21] = 64; 3031 data[22] = 32; 3032 data[23] = 32; 3033 memset(&data[24], 0, 100-24); 3034 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); 3035 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 3036 #ifndef SQLITE_OMIT_AUTOVACUUM 3037 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); 3038 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); 3039 put4byte(&data[36 + 4*4], pBt->autoVacuum); 3040 put4byte(&data[36 + 7*4], pBt->incrVacuum); 3041 #endif 3042 pBt->nPage = 1; 3043 data[31] = 1; 3044 return SQLITE_OK; 3045 } 3046 3047 /* 3048 ** Initialize the first page of the database file (creating a database 3049 ** consisting of a single page and no schema objects). Return SQLITE_OK 3050 ** if successful, or an SQLite error code otherwise. 3051 */ 3052 int sqlite3BtreeNewDb(Btree *p){ 3053 int rc; 3054 sqlite3BtreeEnter(p); 3055 p->pBt->nPage = 0; 3056 rc = newDatabase(p->pBt); 3057 sqlite3BtreeLeave(p); 3058 return rc; 3059 } 3060 3061 /* 3062 ** Attempt to start a new transaction. A write-transaction 3063 ** is started if the second argument is nonzero, otherwise a read- 3064 ** transaction. If the second argument is 2 or more and exclusive 3065 ** transaction is started, meaning that no other process is allowed 3066 ** to access the database. A preexisting transaction may not be 3067 ** upgraded to exclusive by calling this routine a second time - the 3068 ** exclusivity flag only works for a new transaction. 3069 ** 3070 ** A write-transaction must be started before attempting any 3071 ** changes to the database. None of the following routines 3072 ** will work unless a transaction is started first: 3073 ** 3074 ** sqlite3BtreeCreateTable() 3075 ** sqlite3BtreeCreateIndex() 3076 ** sqlite3BtreeClearTable() 3077 ** sqlite3BtreeDropTable() 3078 ** sqlite3BtreeInsert() 3079 ** sqlite3BtreeDelete() 3080 ** sqlite3BtreeUpdateMeta() 3081 ** 3082 ** If an initial attempt to acquire the lock fails because of lock contention 3083 ** and the database was previously unlocked, then invoke the busy handler 3084 ** if there is one. But if there was previously a read-lock, do not 3085 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is 3086 ** returned when there is already a read-lock in order to avoid a deadlock. 3087 ** 3088 ** Suppose there are two processes A and B. A has a read lock and B has 3089 ** a reserved lock. B tries to promote to exclusive but is blocked because 3090 ** of A's read lock. A tries to promote to reserved but is blocked by B. 3091 ** One or the other of the two processes must give way or there can be 3092 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback 3093 ** when A already has a read lock, we encourage A to give up and let B 3094 ** proceed. 3095 */ 3096 int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ 3097 sqlite3 *pBlock = 0; 3098 BtShared *pBt = p->pBt; 3099 int rc = SQLITE_OK; 3100 3101 sqlite3BtreeEnter(p); 3102 btreeIntegrity(p); 3103 3104 /* If the btree is already in a write-transaction, or it 3105 ** is already in a read-transaction and a read-transaction 3106 ** is requested, this is a no-op. 3107 */ 3108 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ 3109 goto trans_begun; 3110 } 3111 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); 3112 3113 /* Write transactions are not possible on a read-only database */ 3114 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ 3115 rc = SQLITE_READONLY; 3116 goto trans_begun; 3117 } 3118 3119 #ifndef SQLITE_OMIT_SHARED_CACHE 3120 /* If another database handle has already opened a write transaction 3121 ** on this shared-btree structure and a second write transaction is 3122 ** requested, return SQLITE_LOCKED. 3123 */ 3124 if( (wrflag && pBt->inTransaction==TRANS_WRITE) 3125 || (pBt->btsFlags & BTS_PENDING)!=0 3126 ){ 3127 pBlock = pBt->pWriter->db; 3128 }else if( wrflag>1 ){ 3129 BtLock *pIter; 3130 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 3131 if( pIter->pBtree!=p ){ 3132 pBlock = pIter->pBtree->db; 3133 break; 3134 } 3135 } 3136 } 3137 if( pBlock ){ 3138 sqlite3ConnectionBlocked(p->db, pBlock); 3139 rc = SQLITE_LOCKED_SHAREDCACHE; 3140 goto trans_begun; 3141 } 3142 #endif 3143 3144 /* Any read-only or read-write transaction implies a read-lock on 3145 ** page 1. So if some other shared-cache client already has a write-lock 3146 ** on page 1, the transaction cannot be opened. */ 3147 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); 3148 if( SQLITE_OK!=rc ) goto trans_begun; 3149 3150 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; 3151 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; 3152 do { 3153 /* Call lockBtree() until either pBt->pPage1 is populated or 3154 ** lockBtree() returns something other than SQLITE_OK. lockBtree() 3155 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after 3156 ** reading page 1 it discovers that the page-size of the database 3157 ** file is not pBt->pageSize. In this case lockBtree() will update 3158 ** pBt->pageSize to the page-size of the file on disk. 3159 */ 3160 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); 3161 3162 if( rc==SQLITE_OK && wrflag ){ 3163 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ 3164 rc = SQLITE_READONLY; 3165 }else{ 3166 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); 3167 if( rc==SQLITE_OK ){ 3168 rc = newDatabase(pBt); 3169 } 3170 } 3171 } 3172 3173 if( rc!=SQLITE_OK ){ 3174 unlockBtreeIfUnused(pBt); 3175 } 3176 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && 3177 btreeInvokeBusyHandler(pBt) ); 3178 3179 if( rc==SQLITE_OK ){ 3180 if( p->inTrans==TRANS_NONE ){ 3181 pBt->nTransaction++; 3182 #ifndef SQLITE_OMIT_SHARED_CACHE 3183 if( p->sharable ){ 3184 assert( p->lock.pBtree==p && p->lock.iTable==1 ); 3185 p->lock.eLock = READ_LOCK; 3186 p->lock.pNext = pBt->pLock; 3187 pBt->pLock = &p->lock; 3188 } 3189 #endif 3190 } 3191 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); 3192 if( p->inTrans>pBt->inTransaction ){ 3193 pBt->inTransaction = p->inTrans; 3194 } 3195 if( wrflag ){ 3196 MemPage *pPage1 = pBt->pPage1; 3197 #ifndef SQLITE_OMIT_SHARED_CACHE 3198 assert( !pBt->pWriter ); 3199 pBt->pWriter = p; 3200 pBt->btsFlags &= ~BTS_EXCLUSIVE; 3201 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; 3202 #endif 3203 3204 /* If the db-size header field is incorrect (as it may be if an old 3205 ** client has been writing the database file), update it now. Doing 3206 ** this sooner rather than later means the database size can safely 3207 ** re-read the database size from page 1 if a savepoint or transaction 3208 ** rollback occurs within the transaction. 3209 */ 3210 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ 3211 rc = sqlite3PagerWrite(pPage1->pDbPage); 3212 if( rc==SQLITE_OK ){ 3213 put4byte(&pPage1->aData[28], pBt->nPage); 3214 } 3215 } 3216 } 3217 } 3218 3219 3220 trans_begun: 3221 if( rc==SQLITE_OK && wrflag ){ 3222 /* This call makes sure that the pager has the correct number of 3223 ** open savepoints. If the second parameter is greater than 0 and 3224 ** the sub-journal is not already open, then it will be opened here. 3225 */ 3226 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); 3227 } 3228 3229 btreeIntegrity(p); 3230 sqlite3BtreeLeave(p); 3231 return rc; 3232 } 3233 3234 #ifndef SQLITE_OMIT_AUTOVACUUM 3235 3236 /* 3237 ** Set the pointer-map entries for all children of page pPage. Also, if 3238 ** pPage contains cells that point to overflow pages, set the pointer 3239 ** map entries for the overflow pages as well. 3240 */ 3241 static int setChildPtrmaps(MemPage *pPage){ 3242 int i; /* Counter variable */ 3243 int nCell; /* Number of cells in page pPage */ 3244 int rc; /* Return code */ 3245 BtShared *pBt = pPage->pBt; 3246 u8 isInitOrig = pPage->isInit; 3247 Pgno pgno = pPage->pgno; 3248 3249 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3250 rc = btreeInitPage(pPage); 3251 if( rc!=SQLITE_OK ){ 3252 goto set_child_ptrmaps_out; 3253 } 3254 nCell = pPage->nCell; 3255 3256 for(i=0; i<nCell; i++){ 3257 u8 *pCell = findCell(pPage, i); 3258 3259 ptrmapPutOvflPtr(pPage, pCell, &rc); 3260 3261 if( !pPage->leaf ){ 3262 Pgno childPgno = get4byte(pCell); 3263 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3264 } 3265 } 3266 3267 if( !pPage->leaf ){ 3268 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 3269 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3270 } 3271 3272 set_child_ptrmaps_out: 3273 pPage->isInit = isInitOrig; 3274 return rc; 3275 } 3276 3277 /* 3278 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so 3279 ** that it points to iTo. Parameter eType describes the type of pointer to 3280 ** be modified, as follows: 3281 ** 3282 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child 3283 ** page of pPage. 3284 ** 3285 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow 3286 ** page pointed to by one of the cells on pPage. 3287 ** 3288 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next 3289 ** overflow page in the list. 3290 */ 3291 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ 3292 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3293 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 3294 if( eType==PTRMAP_OVERFLOW2 ){ 3295 /* The pointer is always the first 4 bytes of the page in this case. */ 3296 if( get4byte(pPage->aData)!=iFrom ){ 3297 return SQLITE_CORRUPT_BKPT; 3298 } 3299 put4byte(pPage->aData, iTo); 3300 }else{ 3301 u8 isInitOrig = pPage->isInit; 3302 int i; 3303 int nCell; 3304 int rc; 3305 3306 rc = btreeInitPage(pPage); 3307 if( rc ) return rc; 3308 nCell = pPage->nCell; 3309 3310 for(i=0; i<nCell; i++){ 3311 u8 *pCell = findCell(pPage, i); 3312 if( eType==PTRMAP_OVERFLOW1 ){ 3313 CellInfo info; 3314 pPage->xParseCell(pPage, pCell, &info); 3315 if( info.iOverflow 3316 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage 3317 && iFrom==get4byte(&pCell[info.iOverflow]) 3318 ){ 3319 put4byte(&pCell[info.iOverflow], iTo); 3320 break; 3321 } 3322 }else{ 3323 if( get4byte(pCell)==iFrom ){ 3324 put4byte(pCell, iTo); 3325 break; 3326 } 3327 } 3328 } 3329 3330 if( i==nCell ){ 3331 if( eType!=PTRMAP_BTREE || 3332 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ 3333 return SQLITE_CORRUPT_BKPT; 3334 } 3335 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); 3336 } 3337 3338 pPage->isInit = isInitOrig; 3339 } 3340 return SQLITE_OK; 3341 } 3342 3343 3344 /* 3345 ** Move the open database page pDbPage to location iFreePage in the 3346 ** database. The pDbPage reference remains valid. 3347 ** 3348 ** The isCommit flag indicates that there is no need to remember that 3349 ** the journal needs to be sync()ed before database page pDbPage->pgno 3350 ** can be written to. The caller has already promised not to write to that 3351 ** page. 3352 */ 3353 static int relocatePage( 3354 BtShared *pBt, /* Btree */ 3355 MemPage *pDbPage, /* Open page to move */ 3356 u8 eType, /* Pointer map 'type' entry for pDbPage */ 3357 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ 3358 Pgno iFreePage, /* The location to move pDbPage to */ 3359 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ 3360 ){ 3361 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ 3362 Pgno iDbPage = pDbPage->pgno; 3363 Pager *pPager = pBt->pPager; 3364 int rc; 3365 3366 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 3367 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); 3368 assert( sqlite3_mutex_held(pBt->mutex) ); 3369 assert( pDbPage->pBt==pBt ); 3370 3371 /* Move page iDbPage from its current location to page number iFreePage */ 3372 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 3373 iDbPage, iFreePage, iPtrPage, eType)); 3374 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); 3375 if( rc!=SQLITE_OK ){ 3376 return rc; 3377 } 3378 pDbPage->pgno = iFreePage; 3379 3380 /* If pDbPage was a btree-page, then it may have child pages and/or cells 3381 ** that point to overflow pages. The pointer map entries for all these 3382 ** pages need to be changed. 3383 ** 3384 ** If pDbPage is an overflow page, then the first 4 bytes may store a 3385 ** pointer to a subsequent overflow page. If this is the case, then 3386 ** the pointer map needs to be updated for the subsequent overflow page. 3387 */ 3388 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ 3389 rc = setChildPtrmaps(pDbPage); 3390 if( rc!=SQLITE_OK ){ 3391 return rc; 3392 } 3393 }else{ 3394 Pgno nextOvfl = get4byte(pDbPage->aData); 3395 if( nextOvfl!=0 ){ 3396 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); 3397 if( rc!=SQLITE_OK ){ 3398 return rc; 3399 } 3400 } 3401 } 3402 3403 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so 3404 ** that it points at iFreePage. Also fix the pointer map entry for 3405 ** iPtrPage. 3406 */ 3407 if( eType!=PTRMAP_ROOTPAGE ){ 3408 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); 3409 if( rc!=SQLITE_OK ){ 3410 return rc; 3411 } 3412 rc = sqlite3PagerWrite(pPtrPage->pDbPage); 3413 if( rc!=SQLITE_OK ){ 3414 releasePage(pPtrPage); 3415 return rc; 3416 } 3417 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); 3418 releasePage(pPtrPage); 3419 if( rc==SQLITE_OK ){ 3420 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); 3421 } 3422 } 3423 return rc; 3424 } 3425 3426 /* Forward declaration required by incrVacuumStep(). */ 3427 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); 3428 3429 /* 3430 ** Perform a single step of an incremental-vacuum. If successful, return 3431 ** SQLITE_OK. If there is no work to do (and therefore no point in 3432 ** calling this function again), return SQLITE_DONE. Or, if an error 3433 ** occurs, return some other error code. 3434 ** 3435 ** More specifically, this function attempts to re-organize the database so 3436 ** that the last page of the file currently in use is no longer in use. 3437 ** 3438 ** Parameter nFin is the number of pages that this database would contain 3439 ** were this function called until it returns SQLITE_DONE. 3440 ** 3441 ** If the bCommit parameter is non-zero, this function assumes that the 3442 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 3443 ** or an error. bCommit is passed true for an auto-vacuum-on-commit 3444 ** operation, or false for an incremental vacuum. 3445 */ 3446 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ 3447 Pgno nFreeList; /* Number of pages still on the free-list */ 3448 int rc; 3449 3450 assert( sqlite3_mutex_held(pBt->mutex) ); 3451 assert( iLastPg>nFin ); 3452 3453 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ 3454 u8 eType; 3455 Pgno iPtrPage; 3456 3457 nFreeList = get4byte(&pBt->pPage1->aData[36]); 3458 if( nFreeList==0 ){ 3459 return SQLITE_DONE; 3460 } 3461 3462 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); 3463 if( rc!=SQLITE_OK ){ 3464 return rc; 3465 } 3466 if( eType==PTRMAP_ROOTPAGE ){ 3467 return SQLITE_CORRUPT_BKPT; 3468 } 3469 3470 if( eType==PTRMAP_FREEPAGE ){ 3471 if( bCommit==0 ){ 3472 /* Remove the page from the files free-list. This is not required 3473 ** if bCommit is non-zero. In that case, the free-list will be 3474 ** truncated to zero after this function returns, so it doesn't 3475 ** matter if it still contains some garbage entries. 3476 */ 3477 Pgno iFreePg; 3478 MemPage *pFreePg; 3479 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); 3480 if( rc!=SQLITE_OK ){ 3481 return rc; 3482 } 3483 assert( iFreePg==iLastPg ); 3484 releasePage(pFreePg); 3485 } 3486 } else { 3487 Pgno iFreePg; /* Index of free page to move pLastPg to */ 3488 MemPage *pLastPg; 3489 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ 3490 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ 3491 3492 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); 3493 if( rc!=SQLITE_OK ){ 3494 return rc; 3495 } 3496 3497 /* If bCommit is zero, this loop runs exactly once and page pLastPg 3498 ** is swapped with the first free page pulled off the free list. 3499 ** 3500 ** On the other hand, if bCommit is greater than zero, then keep 3501 ** looping until a free-page located within the first nFin pages 3502 ** of the file is found. 3503 */ 3504 if( bCommit==0 ){ 3505 eMode = BTALLOC_LE; 3506 iNear = nFin; 3507 } 3508 do { 3509 MemPage *pFreePg; 3510 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); 3511 if( rc!=SQLITE_OK ){ 3512 releasePage(pLastPg); 3513 return rc; 3514 } 3515 releasePage(pFreePg); 3516 }while( bCommit && iFreePg>nFin ); 3517 assert( iFreePg<iLastPg ); 3518 3519 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); 3520 releasePage(pLastPg); 3521 if( rc!=SQLITE_OK ){ 3522 return rc; 3523 } 3524 } 3525 } 3526 3527 if( bCommit==0 ){ 3528 do { 3529 iLastPg--; 3530 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) ); 3531 pBt->bDoTruncate = 1; 3532 pBt->nPage = iLastPg; 3533 } 3534 return SQLITE_OK; 3535 } 3536 3537 /* 3538 ** The database opened by the first argument is an auto-vacuum database 3539 ** nOrig pages in size containing nFree free pages. Return the expected 3540 ** size of the database in pages following an auto-vacuum operation. 3541 */ 3542 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ 3543 int nEntry; /* Number of entries on one ptrmap page */ 3544 Pgno nPtrmap; /* Number of PtrMap pages to be freed */ 3545 Pgno nFin; /* Return value */ 3546 3547 nEntry = pBt->usableSize/5; 3548 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; 3549 nFin = nOrig - nFree - nPtrmap; 3550 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ 3551 nFin--; 3552 } 3553 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ 3554 nFin--; 3555 } 3556 3557 return nFin; 3558 } 3559 3560 /* 3561 ** A write-transaction must be opened before calling this function. 3562 ** It performs a single unit of work towards an incremental vacuum. 3563 ** 3564 ** If the incremental vacuum is finished after this function has run, 3565 ** SQLITE_DONE is returned. If it is not finished, but no error occurred, 3566 ** SQLITE_OK is returned. Otherwise an SQLite error code. 3567 */ 3568 int sqlite3BtreeIncrVacuum(Btree *p){ 3569 int rc; 3570 BtShared *pBt = p->pBt; 3571 3572 sqlite3BtreeEnter(p); 3573 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); 3574 if( !pBt->autoVacuum ){ 3575 rc = SQLITE_DONE; 3576 }else{ 3577 Pgno nOrig = btreePagecount(pBt); 3578 Pgno nFree = get4byte(&pBt->pPage1->aData[36]); 3579 Pgno nFin = finalDbSize(pBt, nOrig, nFree); 3580 3581 if( nOrig<nFin ){ 3582 rc = SQLITE_CORRUPT_BKPT; 3583 }else if( nFree>0 ){ 3584 rc = saveAllCursors(pBt, 0, 0); 3585 if( rc==SQLITE_OK ){ 3586 invalidateAllOverflowCache(pBt); 3587 rc = incrVacuumStep(pBt, nFin, nOrig, 0); 3588 } 3589 if( rc==SQLITE_OK ){ 3590 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3591 put4byte(&pBt->pPage1->aData[28], pBt->nPage); 3592 } 3593 }else{ 3594 rc = SQLITE_DONE; 3595 } 3596 } 3597 sqlite3BtreeLeave(p); 3598 return rc; 3599 } 3600 3601 /* 3602 ** This routine is called prior to sqlite3PagerCommit when a transaction 3603 ** is committed for an auto-vacuum database. 3604 ** 3605 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages 3606 ** the database file should be truncated to during the commit process. 3607 ** i.e. the database has been reorganized so that only the first *pnTrunc 3608 ** pages are in use. 3609 */ 3610 static int autoVacuumCommit(BtShared *pBt){ 3611 int rc = SQLITE_OK; 3612 Pager *pPager = pBt->pPager; 3613 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) 3614 3615 assert( sqlite3_mutex_held(pBt->mutex) ); 3616 invalidateAllOverflowCache(pBt); 3617 assert(pBt->autoVacuum); 3618 if( !pBt->incrVacuum ){ 3619 Pgno nFin; /* Number of pages in database after autovacuuming */ 3620 Pgno nFree; /* Number of pages on the freelist initially */ 3621 Pgno iFree; /* The next page to be freed */ 3622 Pgno nOrig; /* Database size before freeing */ 3623 3624 nOrig = btreePagecount(pBt); 3625 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ 3626 /* It is not possible to create a database for which the final page 3627 ** is either a pointer-map page or the pending-byte page. If one 3628 ** is encountered, this indicates corruption. 3629 */ 3630 return SQLITE_CORRUPT_BKPT; 3631 } 3632 3633 nFree = get4byte(&pBt->pPage1->aData[36]); 3634 nFin = finalDbSize(pBt, nOrig, nFree); 3635 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; 3636 if( nFin<nOrig ){ 3637 rc = saveAllCursors(pBt, 0, 0); 3638 } 3639 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ 3640 rc = incrVacuumStep(pBt, nFin, iFree, 1); 3641 } 3642 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ 3643 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3644 put4byte(&pBt->pPage1->aData[32], 0); 3645 put4byte(&pBt->pPage1->aData[36], 0); 3646 put4byte(&pBt->pPage1->aData[28], nFin); 3647 pBt->bDoTruncate = 1; 3648 pBt->nPage = nFin; 3649 } 3650 if( rc!=SQLITE_OK ){ 3651 sqlite3PagerRollback(pPager); 3652 } 3653 } 3654 3655 assert( nRef>=sqlite3PagerRefcount(pPager) ); 3656 return rc; 3657 } 3658 3659 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ 3660 # define setChildPtrmaps(x) SQLITE_OK 3661 #endif 3662 3663 /* 3664 ** This routine does the first phase of a two-phase commit. This routine 3665 ** causes a rollback journal to be created (if it does not already exist) 3666 ** and populated with enough information so that if a power loss occurs 3667 ** the database can be restored to its original state by playing back 3668 ** the journal. Then the contents of the journal are flushed out to 3669 ** the disk. After the journal is safely on oxide, the changes to the 3670 ** database are written into the database file and flushed to oxide. 3671 ** At the end of this call, the rollback journal still exists on the 3672 ** disk and we are still holding all locks, so the transaction has not 3673 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the 3674 ** commit process. 3675 ** 3676 ** This call is a no-op if no write-transaction is currently active on pBt. 3677 ** 3678 ** Otherwise, sync the database file for the btree pBt. zMaster points to 3679 ** the name of a master journal file that should be written into the 3680 ** individual journal file, or is NULL, indicating no master journal file 3681 ** (single database transaction). 3682 ** 3683 ** When this is called, the master journal should already have been 3684 ** created, populated with this journal pointer and synced to disk. 3685 ** 3686 ** Once this is routine has returned, the only thing required to commit 3687 ** the write-transaction for this database file is to delete the journal. 3688 */ 3689 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ 3690 int rc = SQLITE_OK; 3691 if( p->inTrans==TRANS_WRITE ){ 3692 BtShared *pBt = p->pBt; 3693 sqlite3BtreeEnter(p); 3694 #ifndef SQLITE_OMIT_AUTOVACUUM 3695 if( pBt->autoVacuum ){ 3696 rc = autoVacuumCommit(pBt); 3697 if( rc!=SQLITE_OK ){ 3698 sqlite3BtreeLeave(p); 3699 return rc; 3700 } 3701 } 3702 if( pBt->bDoTruncate ){ 3703 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); 3704 } 3705 #endif 3706 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); 3707 sqlite3BtreeLeave(p); 3708 } 3709 return rc; 3710 } 3711 3712 /* 3713 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() 3714 ** at the conclusion of a transaction. 3715 */ 3716 static void btreeEndTransaction(Btree *p){ 3717 BtShared *pBt = p->pBt; 3718 sqlite3 *db = p->db; 3719 assert( sqlite3BtreeHoldsMutex(p) ); 3720 3721 #ifndef SQLITE_OMIT_AUTOVACUUM 3722 pBt->bDoTruncate = 0; 3723 #endif 3724 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ 3725 /* If there are other active statements that belong to this database 3726 ** handle, downgrade to a read-only transaction. The other statements 3727 ** may still be reading from the database. */ 3728 downgradeAllSharedCacheTableLocks(p); 3729 p->inTrans = TRANS_READ; 3730 }else{ 3731 /* If the handle had any kind of transaction open, decrement the 3732 ** transaction count of the shared btree. If the transaction count 3733 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() 3734 ** call below will unlock the pager. */ 3735 if( p->inTrans!=TRANS_NONE ){ 3736 clearAllSharedCacheTableLocks(p); 3737 pBt->nTransaction--; 3738 if( 0==pBt->nTransaction ){ 3739 pBt->inTransaction = TRANS_NONE; 3740 } 3741 } 3742 3743 /* Set the current transaction state to TRANS_NONE and unlock the 3744 ** pager if this call closed the only read or write transaction. */ 3745 p->inTrans = TRANS_NONE; 3746 unlockBtreeIfUnused(pBt); 3747 } 3748 3749 btreeIntegrity(p); 3750 } 3751 3752 /* 3753 ** Commit the transaction currently in progress. 3754 ** 3755 ** This routine implements the second phase of a 2-phase commit. The 3756 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should 3757 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() 3758 ** routine did all the work of writing information out to disk and flushing the 3759 ** contents so that they are written onto the disk platter. All this 3760 ** routine has to do is delete or truncate or zero the header in the 3761 ** the rollback journal (which causes the transaction to commit) and 3762 ** drop locks. 3763 ** 3764 ** Normally, if an error occurs while the pager layer is attempting to 3765 ** finalize the underlying journal file, this function returns an error and 3766 ** the upper layer will attempt a rollback. However, if the second argument 3767 ** is non-zero then this b-tree transaction is part of a multi-file 3768 ** transaction. In this case, the transaction has already been committed 3769 ** (by deleting a master journal file) and the caller will ignore this 3770 ** functions return code. So, even if an error occurs in the pager layer, 3771 ** reset the b-tree objects internal state to indicate that the write 3772 ** transaction has been closed. This is quite safe, as the pager will have 3773 ** transitioned to the error state. 3774 ** 3775 ** This will release the write lock on the database file. If there 3776 ** are no active cursors, it also releases the read lock. 3777 */ 3778 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ 3779 3780 if( p->inTrans==TRANS_NONE ) return SQLITE_OK; 3781 sqlite3BtreeEnter(p); 3782 btreeIntegrity(p); 3783 3784 /* If the handle has a write-transaction open, commit the shared-btrees 3785 ** transaction and set the shared state to TRANS_READ. 3786 */ 3787 if( p->inTrans==TRANS_WRITE ){ 3788 int rc; 3789 BtShared *pBt = p->pBt; 3790 assert( pBt->inTransaction==TRANS_WRITE ); 3791 assert( pBt->nTransaction>0 ); 3792 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); 3793 if( rc!=SQLITE_OK && bCleanup==0 ){ 3794 sqlite3BtreeLeave(p); 3795 return rc; 3796 } 3797 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ 3798 pBt->inTransaction = TRANS_READ; 3799 btreeClearHasContent(pBt); 3800 } 3801 3802 btreeEndTransaction(p); 3803 sqlite3BtreeLeave(p); 3804 return SQLITE_OK; 3805 } 3806 3807 /* 3808 ** Do both phases of a commit. 3809 */ 3810 int sqlite3BtreeCommit(Btree *p){ 3811 int rc; 3812 sqlite3BtreeEnter(p); 3813 rc = sqlite3BtreeCommitPhaseOne(p, 0); 3814 if( rc==SQLITE_OK ){ 3815 rc = sqlite3BtreeCommitPhaseTwo(p, 0); 3816 } 3817 sqlite3BtreeLeave(p); 3818 return rc; 3819 } 3820 3821 /* 3822 ** This routine sets the state to CURSOR_FAULT and the error 3823 ** code to errCode for every cursor on any BtShared that pBtree 3824 ** references. Or if the writeOnly flag is set to 1, then only 3825 ** trip write cursors and leave read cursors unchanged. 3826 ** 3827 ** Every cursor is a candidate to be tripped, including cursors 3828 ** that belong to other database connections that happen to be 3829 ** sharing the cache with pBtree. 3830 ** 3831 ** This routine gets called when a rollback occurs. If the writeOnly 3832 ** flag is true, then only write-cursors need be tripped - read-only 3833 ** cursors save their current positions so that they may continue 3834 ** following the rollback. Or, if writeOnly is false, all cursors are 3835 ** tripped. In general, writeOnly is false if the transaction being 3836 ** rolled back modified the database schema. In this case b-tree root 3837 ** pages may be moved or deleted from the database altogether, making 3838 ** it unsafe for read cursors to continue. 3839 ** 3840 ** If the writeOnly flag is true and an error is encountered while 3841 ** saving the current position of a read-only cursor, all cursors, 3842 ** including all read-cursors are tripped. 3843 ** 3844 ** SQLITE_OK is returned if successful, or if an error occurs while 3845 ** saving a cursor position, an SQLite error code. 3846 */ 3847 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ 3848 BtCursor *p; 3849 int rc = SQLITE_OK; 3850 3851 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); 3852 if( pBtree ){ 3853 sqlite3BtreeEnter(pBtree); 3854 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 3855 int i; 3856 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ 3857 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 3858 rc = saveCursorPosition(p); 3859 if( rc!=SQLITE_OK ){ 3860 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); 3861 break; 3862 } 3863 } 3864 }else{ 3865 sqlite3BtreeClearCursor(p); 3866 p->eState = CURSOR_FAULT; 3867 p->skipNext = errCode; 3868 } 3869 for(i=0; i<=p->iPage; i++){ 3870 releasePage(p->apPage[i]); 3871 p->apPage[i] = 0; 3872 } 3873 } 3874 sqlite3BtreeLeave(pBtree); 3875 } 3876 return rc; 3877 } 3878 3879 /* 3880 ** Rollback the transaction in progress. 3881 ** 3882 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). 3883 ** Only write cursors are tripped if writeOnly is true but all cursors are 3884 ** tripped if writeOnly is false. Any attempt to use 3885 ** a tripped cursor will result in an error. 3886 ** 3887 ** This will release the write lock on the database file. If there 3888 ** are no active cursors, it also releases the read lock. 3889 */ 3890 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ 3891 int rc; 3892 BtShared *pBt = p->pBt; 3893 MemPage *pPage1; 3894 3895 assert( writeOnly==1 || writeOnly==0 ); 3896 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); 3897 sqlite3BtreeEnter(p); 3898 if( tripCode==SQLITE_OK ){ 3899 rc = tripCode = saveAllCursors(pBt, 0, 0); 3900 if( rc ) writeOnly = 0; 3901 }else{ 3902 rc = SQLITE_OK; 3903 } 3904 if( tripCode ){ 3905 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); 3906 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); 3907 if( rc2!=SQLITE_OK ) rc = rc2; 3908 } 3909 btreeIntegrity(p); 3910 3911 if( p->inTrans==TRANS_WRITE ){ 3912 int rc2; 3913 3914 assert( TRANS_WRITE==pBt->inTransaction ); 3915 rc2 = sqlite3PagerRollback(pBt->pPager); 3916 if( rc2!=SQLITE_OK ){ 3917 rc = rc2; 3918 } 3919 3920 /* The rollback may have destroyed the pPage1->aData value. So 3921 ** call btreeGetPage() on page 1 again to make 3922 ** sure pPage1->aData is set correctly. */ 3923 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ 3924 int nPage = get4byte(28+(u8*)pPage1->aData); 3925 testcase( nPage==0 ); 3926 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); 3927 testcase( pBt->nPage!=nPage ); 3928 pBt->nPage = nPage; 3929 releasePage(pPage1); 3930 } 3931 assert( countValidCursors(pBt, 1)==0 ); 3932 pBt->inTransaction = TRANS_READ; 3933 btreeClearHasContent(pBt); 3934 } 3935 3936 btreeEndTransaction(p); 3937 sqlite3BtreeLeave(p); 3938 return rc; 3939 } 3940 3941 /* 3942 ** Start a statement subtransaction. The subtransaction can be rolled 3943 ** back independently of the main transaction. You must start a transaction 3944 ** before starting a subtransaction. The subtransaction is ended automatically 3945 ** if the main transaction commits or rolls back. 3946 ** 3947 ** Statement subtransactions are used around individual SQL statements 3948 ** that are contained within a BEGIN...COMMIT block. If a constraint 3949 ** error occurs within the statement, the effect of that one statement 3950 ** can be rolled back without having to rollback the entire transaction. 3951 ** 3952 ** A statement sub-transaction is implemented as an anonymous savepoint. The 3953 ** value passed as the second parameter is the total number of savepoints, 3954 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there 3955 ** are no active savepoints and no other statement-transactions open, 3956 ** iStatement is 1. This anonymous savepoint can be released or rolled back 3957 ** using the sqlite3BtreeSavepoint() function. 3958 */ 3959 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ 3960 int rc; 3961 BtShared *pBt = p->pBt; 3962 sqlite3BtreeEnter(p); 3963 assert( p->inTrans==TRANS_WRITE ); 3964 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 3965 assert( iStatement>0 ); 3966 assert( iStatement>p->db->nSavepoint ); 3967 assert( pBt->inTransaction==TRANS_WRITE ); 3968 /* At the pager level, a statement transaction is a savepoint with 3969 ** an index greater than all savepoints created explicitly using 3970 ** SQL statements. It is illegal to open, release or rollback any 3971 ** such savepoints while the statement transaction savepoint is active. 3972 */ 3973 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); 3974 sqlite3BtreeLeave(p); 3975 return rc; 3976 } 3977 3978 /* 3979 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK 3980 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the 3981 ** savepoint identified by parameter iSavepoint, depending on the value 3982 ** of op. 3983 ** 3984 ** Normally, iSavepoint is greater than or equal to zero. However, if op is 3985 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 3986 ** contents of the entire transaction are rolled back. This is different 3987 ** from a normal transaction rollback, as no locks are released and the 3988 ** transaction remains open. 3989 */ 3990 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ 3991 int rc = SQLITE_OK; 3992 if( p && p->inTrans==TRANS_WRITE ){ 3993 BtShared *pBt = p->pBt; 3994 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); 3995 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); 3996 sqlite3BtreeEnter(p); 3997 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); 3998 if( rc==SQLITE_OK ){ 3999 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ 4000 pBt->nPage = 0; 4001 } 4002 rc = newDatabase(pBt); 4003 pBt->nPage = get4byte(28 + pBt->pPage1->aData); 4004 4005 /* The database size was written into the offset 28 of the header 4006 ** when the transaction started, so we know that the value at offset 4007 ** 28 is nonzero. */ 4008 assert( pBt->nPage>0 ); 4009 } 4010 sqlite3BtreeLeave(p); 4011 } 4012 return rc; 4013 } 4014 4015 /* 4016 ** Create a new cursor for the BTree whose root is on the page 4017 ** iTable. If a read-only cursor is requested, it is assumed that 4018 ** the caller already has at least a read-only transaction open 4019 ** on the database already. If a write-cursor is requested, then 4020 ** the caller is assumed to have an open write transaction. 4021 ** 4022 ** If wrFlag==0, then the cursor can only be used for reading. 4023 ** If wrFlag==1, then the cursor can be used for reading or for 4024 ** writing if other conditions for writing are also met. These 4025 ** are the conditions that must be met in order for writing to 4026 ** be allowed: 4027 ** 4028 ** 1: The cursor must have been opened with wrFlag==1 4029 ** 4030 ** 2: Other database connections that share the same pager cache 4031 ** but which are not in the READ_UNCOMMITTED state may not have 4032 ** cursors open with wrFlag==0 on the same table. Otherwise 4033 ** the changes made by this write cursor would be visible to 4034 ** the read cursors in the other database connection. 4035 ** 4036 ** 3: The database must be writable (not on read-only media) 4037 ** 4038 ** 4: There must be an active transaction. 4039 ** 4040 ** No checking is done to make sure that page iTable really is the 4041 ** root page of a b-tree. If it is not, then the cursor acquired 4042 ** will not work correctly. 4043 ** 4044 ** It is assumed that the sqlite3BtreeCursorZero() has been called 4045 ** on pCur to initialize the memory space prior to invoking this routine. 4046 */ 4047 static int btreeCursor( 4048 Btree *p, /* The btree */ 4049 int iTable, /* Root page of table to open */ 4050 int wrFlag, /* 1 to write. 0 read-only */ 4051 struct KeyInfo *pKeyInfo, /* First arg to comparison function */ 4052 BtCursor *pCur /* Space for new cursor */ 4053 ){ 4054 BtShared *pBt = p->pBt; /* Shared b-tree handle */ 4055 BtCursor *pX; /* Looping over other all cursors */ 4056 4057 assert( sqlite3BtreeHoldsMutex(p) ); 4058 assert( wrFlag==0 || wrFlag==1 ); 4059 4060 /* The following assert statements verify that if this is a sharable 4061 ** b-tree database, the connection is holding the required table locks, 4062 ** and that no other connection has any open cursor that conflicts with 4063 ** this lock. */ 4064 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) ); 4065 assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); 4066 4067 /* Assert that the caller has opened the required transaction. */ 4068 assert( p->inTrans>TRANS_NONE ); 4069 assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); 4070 assert( pBt->pPage1 && pBt->pPage1->aData ); 4071 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); 4072 4073 if( wrFlag ){ 4074 allocateTempSpace(pBt); 4075 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM; 4076 } 4077 if( iTable==1 && btreePagecount(pBt)==0 ){ 4078 assert( wrFlag==0 ); 4079 iTable = 0; 4080 } 4081 4082 /* Now that no other errors can occur, finish filling in the BtCursor 4083 ** variables and link the cursor into the BtShared list. */ 4084 pCur->pgnoRoot = (Pgno)iTable; 4085 pCur->iPage = -1; 4086 pCur->pKeyInfo = pKeyInfo; 4087 pCur->pBtree = p; 4088 pCur->pBt = pBt; 4089 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag ); 4090 pCur->curFlags = wrFlag; 4091 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; 4092 /* If there are two or more cursors on the same btree, then all such 4093 ** cursors *must* have the BTCF_Multiple flag set. */ 4094 for(pX=pBt->pCursor; pX; pX=pX->pNext){ 4095 if( pX->pgnoRoot==(Pgno)iTable ){ 4096 pX->curFlags |= BTCF_Multiple; 4097 pCur->curFlags |= BTCF_Multiple; 4098 } 4099 } 4100 pCur->pNext = pBt->pCursor; 4101 pBt->pCursor = pCur; 4102 pCur->eState = CURSOR_INVALID; 4103 return SQLITE_OK; 4104 } 4105 int sqlite3BtreeCursor( 4106 Btree *p, /* The btree */ 4107 int iTable, /* Root page of table to open */ 4108 int wrFlag, /* 1 to write. 0 read-only */ 4109 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ 4110 BtCursor *pCur /* Write new cursor here */ 4111 ){ 4112 int rc; 4113 if( iTable<1 ){ 4114 rc = SQLITE_CORRUPT_BKPT; 4115 }else{ 4116 sqlite3BtreeEnter(p); 4117 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); 4118 sqlite3BtreeLeave(p); 4119 } 4120 return rc; 4121 } 4122 4123 /* 4124 ** Return the size of a BtCursor object in bytes. 4125 ** 4126 ** This interfaces is needed so that users of cursors can preallocate 4127 ** sufficient storage to hold a cursor. The BtCursor object is opaque 4128 ** to users so they cannot do the sizeof() themselves - they must call 4129 ** this routine. 4130 */ 4131 int sqlite3BtreeCursorSize(void){ 4132 return ROUND8(sizeof(BtCursor)); 4133 } 4134 4135 /* 4136 ** Initialize memory that will be converted into a BtCursor object. 4137 ** 4138 ** The simple approach here would be to memset() the entire object 4139 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays 4140 ** do not need to be zeroed and they are large, so we can save a lot 4141 ** of run-time by skipping the initialization of those elements. 4142 */ 4143 void sqlite3BtreeCursorZero(BtCursor *p){ 4144 memset(p, 0, offsetof(BtCursor, iPage)); 4145 } 4146 4147 /* 4148 ** Close a cursor. The read lock on the database file is released 4149 ** when the last cursor is closed. 4150 */ 4151 int sqlite3BtreeCloseCursor(BtCursor *pCur){ 4152 Btree *pBtree = pCur->pBtree; 4153 if( pBtree ){ 4154 int i; 4155 BtShared *pBt = pCur->pBt; 4156 sqlite3BtreeEnter(pBtree); 4157 sqlite3BtreeClearCursor(pCur); 4158 assert( pBt->pCursor!=0 ); 4159 if( pBt->pCursor==pCur ){ 4160 pBt->pCursor = pCur->pNext; 4161 }else{ 4162 BtCursor *pPrev = pBt->pCursor; 4163 do{ 4164 if( pPrev->pNext==pCur ){ 4165 pPrev->pNext = pCur->pNext; 4166 break; 4167 } 4168 pPrev = pPrev->pNext; 4169 }while( ALWAYS(pPrev) ); 4170 } 4171 for(i=0; i<=pCur->iPage; i++){ 4172 releasePage(pCur->apPage[i]); 4173 } 4174 unlockBtreeIfUnused(pBt); 4175 sqlite3_free(pCur->aOverflow); 4176 /* sqlite3_free(pCur); */ 4177 sqlite3BtreeLeave(pBtree); 4178 } 4179 return SQLITE_OK; 4180 } 4181 4182 /* 4183 ** Make sure the BtCursor* given in the argument has a valid 4184 ** BtCursor.info structure. If it is not already valid, call 4185 ** btreeParseCell() to fill it in. 4186 ** 4187 ** BtCursor.info is a cache of the information in the current cell. 4188 ** Using this cache reduces the number of calls to btreeParseCell(). 4189 */ 4190 #ifndef NDEBUG 4191 static void assertCellInfo(BtCursor *pCur){ 4192 CellInfo info; 4193 int iPage = pCur->iPage; 4194 memset(&info, 0, sizeof(info)); 4195 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); 4196 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); 4197 } 4198 #else 4199 #define assertCellInfo(x) 4200 #endif 4201 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ 4202 if( pCur->info.nSize==0 ){ 4203 int iPage = pCur->iPage; 4204 pCur->curFlags |= BTCF_ValidNKey; 4205 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); 4206 }else{ 4207 assertCellInfo(pCur); 4208 } 4209 } 4210 4211 #ifndef NDEBUG /* The next routine used only within assert() statements */ 4212 /* 4213 ** Return true if the given BtCursor is valid. A valid cursor is one 4214 ** that is currently pointing to a row in a (non-empty) table. 4215 ** This is a verification routine is used only within assert() statements. 4216 */ 4217 int sqlite3BtreeCursorIsValid(BtCursor *pCur){ 4218 return pCur && pCur->eState==CURSOR_VALID; 4219 } 4220 #endif /* NDEBUG */ 4221 4222 /* 4223 ** Set *pSize to the size of the buffer needed to hold the value of 4224 ** the key for the current entry. If the cursor is not pointing 4225 ** to a valid entry, *pSize is set to 0. 4226 ** 4227 ** For a table with the INTKEY flag set, this routine returns the key 4228 ** itself, not the number of bytes in the key. 4229 ** 4230 ** The caller must position the cursor prior to invoking this routine. 4231 ** 4232 ** This routine cannot fail. It always returns SQLITE_OK. 4233 */ 4234 int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ 4235 assert( cursorHoldsMutex(pCur) ); 4236 assert( pCur->eState==CURSOR_VALID ); 4237 getCellInfo(pCur); 4238 *pSize = pCur->info.nKey; 4239 return SQLITE_OK; 4240 } 4241 4242 /* 4243 ** Set *pSize to the number of bytes of data in the entry the 4244 ** cursor currently points to. 4245 ** 4246 ** The caller must guarantee that the cursor is pointing to a non-NULL 4247 ** valid entry. In other words, the calling procedure must guarantee 4248 ** that the cursor has Cursor.eState==CURSOR_VALID. 4249 ** 4250 ** Failure is not possible. This function always returns SQLITE_OK. 4251 ** It might just as well be a procedure (returning void) but we continue 4252 ** to return an integer result code for historical reasons. 4253 */ 4254 int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ 4255 assert( cursorHoldsMutex(pCur) ); 4256 assert( pCur->eState==CURSOR_VALID ); 4257 assert( pCur->iPage>=0 ); 4258 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); 4259 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 ); 4260 getCellInfo(pCur); 4261 *pSize = pCur->info.nPayload; 4262 return SQLITE_OK; 4263 } 4264 4265 /* 4266 ** Given the page number of an overflow page in the database (parameter 4267 ** ovfl), this function finds the page number of the next page in the 4268 ** linked list of overflow pages. If possible, it uses the auto-vacuum 4269 ** pointer-map data instead of reading the content of page ovfl to do so. 4270 ** 4271 ** If an error occurs an SQLite error code is returned. Otherwise: 4272 ** 4273 ** The page number of the next overflow page in the linked list is 4274 ** written to *pPgnoNext. If page ovfl is the last page in its linked 4275 ** list, *pPgnoNext is set to zero. 4276 ** 4277 ** If ppPage is not NULL, and a reference to the MemPage object corresponding 4278 ** to page number pOvfl was obtained, then *ppPage is set to point to that 4279 ** reference. It is the responsibility of the caller to call releasePage() 4280 ** on *ppPage to free the reference. In no reference was obtained (because 4281 ** the pointer-map was used to obtain the value for *pPgnoNext), then 4282 ** *ppPage is set to zero. 4283 */ 4284 static int getOverflowPage( 4285 BtShared *pBt, /* The database file */ 4286 Pgno ovfl, /* Current overflow page number */ 4287 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ 4288 Pgno *pPgnoNext /* OUT: Next overflow page number */ 4289 ){ 4290 Pgno next = 0; 4291 MemPage *pPage = 0; 4292 int rc = SQLITE_OK; 4293 4294 assert( sqlite3_mutex_held(pBt->mutex) ); 4295 assert(pPgnoNext); 4296 4297 #ifndef SQLITE_OMIT_AUTOVACUUM 4298 /* Try to find the next page in the overflow list using the 4299 ** autovacuum pointer-map pages. Guess that the next page in 4300 ** the overflow list is page number (ovfl+1). If that guess turns 4301 ** out to be wrong, fall back to loading the data of page 4302 ** number ovfl to determine the next page number. 4303 */ 4304 if( pBt->autoVacuum ){ 4305 Pgno pgno; 4306 Pgno iGuess = ovfl+1; 4307 u8 eType; 4308 4309 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ 4310 iGuess++; 4311 } 4312 4313 if( iGuess<=btreePagecount(pBt) ){ 4314 rc = ptrmapGet(pBt, iGuess, &eType, &pgno); 4315 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ 4316 next = iGuess; 4317 rc = SQLITE_DONE; 4318 } 4319 } 4320 } 4321 #endif 4322 4323 assert( next==0 || rc==SQLITE_DONE ); 4324 if( rc==SQLITE_OK ){ 4325 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); 4326 assert( rc==SQLITE_OK || pPage==0 ); 4327 if( rc==SQLITE_OK ){ 4328 next = get4byte(pPage->aData); 4329 } 4330 } 4331 4332 *pPgnoNext = next; 4333 if( ppPage ){ 4334 *ppPage = pPage; 4335 }else{ 4336 releasePage(pPage); 4337 } 4338 return (rc==SQLITE_DONE ? SQLITE_OK : rc); 4339 } 4340 4341 /* 4342 ** Copy data from a buffer to a page, or from a page to a buffer. 4343 ** 4344 ** pPayload is a pointer to data stored on database page pDbPage. 4345 ** If argument eOp is false, then nByte bytes of data are copied 4346 ** from pPayload to the buffer pointed at by pBuf. If eOp is true, 4347 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes 4348 ** of data are copied from the buffer pBuf to pPayload. 4349 ** 4350 ** SQLITE_OK is returned on success, otherwise an error code. 4351 */ 4352 static int copyPayload( 4353 void *pPayload, /* Pointer to page data */ 4354 void *pBuf, /* Pointer to buffer */ 4355 int nByte, /* Number of bytes to copy */ 4356 int eOp, /* 0 -> copy from page, 1 -> copy to page */ 4357 DbPage *pDbPage /* Page containing pPayload */ 4358 ){ 4359 if( eOp ){ 4360 /* Copy data from buffer to page (a write operation) */ 4361 int rc = sqlite3PagerWrite(pDbPage); 4362 if( rc!=SQLITE_OK ){ 4363 return rc; 4364 } 4365 memcpy(pPayload, pBuf, nByte); 4366 }else{ 4367 /* Copy data from page to buffer (a read operation) */ 4368 memcpy(pBuf, pPayload, nByte); 4369 } 4370 return SQLITE_OK; 4371 } 4372 4373 /* 4374 ** This function is used to read or overwrite payload information 4375 ** for the entry that the pCur cursor is pointing to. The eOp 4376 ** argument is interpreted as follows: 4377 ** 4378 ** 0: The operation is a read. Populate the overflow cache. 4379 ** 1: The operation is a write. Populate the overflow cache. 4380 ** 2: The operation is a read. Do not populate the overflow cache. 4381 ** 4382 ** A total of "amt" bytes are read or written beginning at "offset". 4383 ** Data is read to or from the buffer pBuf. 4384 ** 4385 ** The content being read or written might appear on the main page 4386 ** or be scattered out on multiple overflow pages. 4387 ** 4388 ** If the current cursor entry uses one or more overflow pages and the 4389 ** eOp argument is not 2, this function may allocate space for and lazily 4390 ** populates the overflow page-list cache array (BtCursor.aOverflow). 4391 ** Subsequent calls use this cache to make seeking to the supplied offset 4392 ** more efficient. 4393 ** 4394 ** Once an overflow page-list cache has been allocated, it may be 4395 ** invalidated if some other cursor writes to the same table, or if 4396 ** the cursor is moved to a different row. Additionally, in auto-vacuum 4397 ** mode, the following events may invalidate an overflow page-list cache. 4398 ** 4399 ** * An incremental vacuum, 4400 ** * A commit in auto_vacuum="full" mode, 4401 ** * Creating a table (may require moving an overflow page). 4402 */ 4403 static int accessPayload( 4404 BtCursor *pCur, /* Cursor pointing to entry to read from */ 4405 u32 offset, /* Begin reading this far into payload */ 4406 u32 amt, /* Read this many bytes */ 4407 unsigned char *pBuf, /* Write the bytes into this buffer */ 4408 int eOp /* zero to read. non-zero to write. */ 4409 ){ 4410 unsigned char *aPayload; 4411 int rc = SQLITE_OK; 4412 int iIdx = 0; 4413 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ 4414 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ 4415 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4416 unsigned char * const pBufStart = pBuf; 4417 int bEnd; /* True if reading to end of data */ 4418 #endif 4419 4420 assert( pPage ); 4421 assert( pCur->eState==CURSOR_VALID ); 4422 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); 4423 assert( cursorHoldsMutex(pCur) ); 4424 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */ 4425 4426 getCellInfo(pCur); 4427 aPayload = pCur->info.pPayload; 4428 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4429 bEnd = offset+amt==pCur->info.nPayload; 4430 #endif 4431 assert( offset+amt <= pCur->info.nPayload ); 4432 4433 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){ 4434 /* Trying to read or write past the end of the data is an error */ 4435 return SQLITE_CORRUPT_BKPT; 4436 } 4437 4438 /* Check if data must be read/written to/from the btree page itself. */ 4439 if( offset<pCur->info.nLocal ){ 4440 int a = amt; 4441 if( a+offset>pCur->info.nLocal ){ 4442 a = pCur->info.nLocal - offset; 4443 } 4444 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage); 4445 offset = 0; 4446 pBuf += a; 4447 amt -= a; 4448 }else{ 4449 offset -= pCur->info.nLocal; 4450 } 4451 4452 4453 if( rc==SQLITE_OK && amt>0 ){ 4454 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ 4455 Pgno nextPage; 4456 4457 nextPage = get4byte(&aPayload[pCur->info.nLocal]); 4458 4459 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. 4460 ** Except, do not allocate aOverflow[] for eOp==2. 4461 ** 4462 ** The aOverflow[] array is sized at one entry for each overflow page 4463 ** in the overflow chain. The page number of the first overflow page is 4464 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array 4465 ** means "not yet known" (the cache is lazily populated). 4466 */ 4467 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){ 4468 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; 4469 if( nOvfl>pCur->nOvflAlloc ){ 4470 Pgno *aNew = (Pgno*)sqlite3Realloc( 4471 pCur->aOverflow, nOvfl*2*sizeof(Pgno) 4472 ); 4473 if( aNew==0 ){ 4474 rc = SQLITE_NOMEM; 4475 }else{ 4476 pCur->nOvflAlloc = nOvfl*2; 4477 pCur->aOverflow = aNew; 4478 } 4479 } 4480 if( rc==SQLITE_OK ){ 4481 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); 4482 pCur->curFlags |= BTCF_ValidOvfl; 4483 } 4484 } 4485 4486 /* If the overflow page-list cache has been allocated and the 4487 ** entry for the first required overflow page is valid, skip 4488 ** directly to it. 4489 */ 4490 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 4491 && pCur->aOverflow[offset/ovflSize] 4492 ){ 4493 iIdx = (offset/ovflSize); 4494 nextPage = pCur->aOverflow[iIdx]; 4495 offset = (offset%ovflSize); 4496 } 4497 4498 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ 4499 4500 /* If required, populate the overflow page-list cache. */ 4501 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){ 4502 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); 4503 pCur->aOverflow[iIdx] = nextPage; 4504 } 4505 4506 if( offset>=ovflSize ){ 4507 /* The only reason to read this page is to obtain the page 4508 ** number for the next page in the overflow chain. The page 4509 ** data is not required. So first try to lookup the overflow 4510 ** page-list cache, if any, then fall back to the getOverflowPage() 4511 ** function. 4512 ** 4513 ** Note that the aOverflow[] array must be allocated because eOp!=2 4514 ** here. If eOp==2, then offset==0 and this branch is never taken. 4515 */ 4516 assert( eOp!=2 ); 4517 assert( pCur->curFlags & BTCF_ValidOvfl ); 4518 assert( pCur->pBtree->db==pBt->db ); 4519 if( pCur->aOverflow[iIdx+1] ){ 4520 nextPage = pCur->aOverflow[iIdx+1]; 4521 }else{ 4522 rc = getOverflowPage(pBt, nextPage, 0, &nextPage); 4523 } 4524 offset -= ovflSize; 4525 }else{ 4526 /* Need to read this page properly. It contains some of the 4527 ** range of data that is being read (eOp==0) or written (eOp!=0). 4528 */ 4529 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4530 sqlite3_file *fd; 4531 #endif 4532 int a = amt; 4533 if( a + offset > ovflSize ){ 4534 a = ovflSize - offset; 4535 } 4536 4537 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4538 /* If all the following are true: 4539 ** 4540 ** 1) this is a read operation, and 4541 ** 2) data is required from the start of this overflow page, and 4542 ** 3) the database is file-backed, and 4543 ** 4) there is no open write-transaction, and 4544 ** 5) the database is not a WAL database, 4545 ** 6) all data from the page is being read. 4546 ** 7) at least 4 bytes have already been read into the output buffer 4547 ** 4548 ** then data can be read directly from the database file into the 4549 ** output buffer, bypassing the page-cache altogether. This speeds 4550 ** up loading large records that span many overflow pages. 4551 */ 4552 if( (eOp&0x01)==0 /* (1) */ 4553 && offset==0 /* (2) */ 4554 && (bEnd || a==ovflSize) /* (6) */ 4555 && pBt->inTransaction==TRANS_READ /* (4) */ 4556 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ 4557 && pBt->pPage1->aData[19]==0x01 /* (5) */ 4558 && &pBuf[-4]>=pBufStart /* (7) */ 4559 ){ 4560 u8 aSave[4]; 4561 u8 *aWrite = &pBuf[-4]; 4562 assert( aWrite>=pBufStart ); /* hence (7) */ 4563 memcpy(aSave, aWrite, 4); 4564 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); 4565 nextPage = get4byte(aWrite); 4566 memcpy(aWrite, aSave, 4); 4567 }else 4568 #endif 4569 4570 { 4571 DbPage *pDbPage; 4572 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage, 4573 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0) 4574 ); 4575 if( rc==SQLITE_OK ){ 4576 aPayload = sqlite3PagerGetData(pDbPage); 4577 nextPage = get4byte(aPayload); 4578 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage); 4579 sqlite3PagerUnref(pDbPage); 4580 offset = 0; 4581 } 4582 } 4583 amt -= a; 4584 pBuf += a; 4585 } 4586 } 4587 } 4588 4589 if( rc==SQLITE_OK && amt>0 ){ 4590 return SQLITE_CORRUPT_BKPT; 4591 } 4592 return rc; 4593 } 4594 4595 /* 4596 ** Read part of the key associated with cursor pCur. Exactly 4597 ** "amt" bytes will be transferred into pBuf[]. The transfer 4598 ** begins at "offset". 4599 ** 4600 ** The caller must ensure that pCur is pointing to a valid row 4601 ** in the table. 4602 ** 4603 ** Return SQLITE_OK on success or an error code if anything goes 4604 ** wrong. An error is returned if "offset+amt" is larger than 4605 ** the available payload. 4606 */ 4607 int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 4608 assert( cursorHoldsMutex(pCur) ); 4609 assert( pCur->eState==CURSOR_VALID ); 4610 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); 4611 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); 4612 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); 4613 } 4614 4615 /* 4616 ** Read part of the data associated with cursor pCur. Exactly 4617 ** "amt" bytes will be transfered into pBuf[]. The transfer 4618 ** begins at "offset". 4619 ** 4620 ** Return SQLITE_OK on success or an error code if anything goes 4621 ** wrong. An error is returned if "offset+amt" is larger than 4622 ** the available payload. 4623 */ 4624 int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 4625 int rc; 4626 4627 #ifndef SQLITE_OMIT_INCRBLOB 4628 if ( pCur->eState==CURSOR_INVALID ){ 4629 return SQLITE_ABORT; 4630 } 4631 #endif 4632 4633 assert( cursorHoldsMutex(pCur) ); 4634 rc = restoreCursorPosition(pCur); 4635 if( rc==SQLITE_OK ){ 4636 assert( pCur->eState==CURSOR_VALID ); 4637 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); 4638 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); 4639 rc = accessPayload(pCur, offset, amt, pBuf, 0); 4640 } 4641 return rc; 4642 } 4643 4644 /* 4645 ** Return a pointer to payload information from the entry that the 4646 ** pCur cursor is pointing to. The pointer is to the beginning of 4647 ** the key if index btrees (pPage->intKey==0) and is the data for 4648 ** table btrees (pPage->intKey==1). The number of bytes of available 4649 ** key/data is written into *pAmt. If *pAmt==0, then the value 4650 ** returned will not be a valid pointer. 4651 ** 4652 ** This routine is an optimization. It is common for the entire key 4653 ** and data to fit on the local page and for there to be no overflow 4654 ** pages. When that is so, this routine can be used to access the 4655 ** key and data without making a copy. If the key and/or data spills 4656 ** onto overflow pages, then accessPayload() must be used to reassemble 4657 ** the key/data and copy it into a preallocated buffer. 4658 ** 4659 ** The pointer returned by this routine looks directly into the cached 4660 ** page of the database. The data might change or move the next time 4661 ** any btree routine is called. 4662 */ 4663 static const void *fetchPayload( 4664 BtCursor *pCur, /* Cursor pointing to entry to read from */ 4665 u32 *pAmt /* Write the number of available bytes here */ 4666 ){ 4667 u32 amt; 4668 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); 4669 assert( pCur->eState==CURSOR_VALID ); 4670 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 4671 assert( cursorHoldsMutex(pCur) ); 4672 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); 4673 assert( pCur->info.nSize>0 ); 4674 assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB ); 4675 assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB); 4676 amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload); 4677 if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal; 4678 *pAmt = amt; 4679 return (void*)pCur->info.pPayload; 4680 } 4681 4682 4683 /* 4684 ** For the entry that cursor pCur is point to, return as 4685 ** many bytes of the key or data as are available on the local 4686 ** b-tree page. Write the number of available bytes into *pAmt. 4687 ** 4688 ** The pointer returned is ephemeral. The key/data may move 4689 ** or be destroyed on the next call to any Btree routine, 4690 ** including calls from other threads against the same cache. 4691 ** Hence, a mutex on the BtShared should be held prior to calling 4692 ** this routine. 4693 ** 4694 ** These routines is used to get quick access to key and data 4695 ** in the common case where no overflow pages are used. 4696 */ 4697 const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){ 4698 return fetchPayload(pCur, pAmt); 4699 } 4700 const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){ 4701 return fetchPayload(pCur, pAmt); 4702 } 4703 4704 4705 /* 4706 ** Move the cursor down to a new child page. The newPgno argument is the 4707 ** page number of the child page to move to. 4708 ** 4709 ** This function returns SQLITE_CORRUPT if the page-header flags field of 4710 ** the new child page does not match the flags field of the parent (i.e. 4711 ** if an intkey page appears to be the parent of a non-intkey page, or 4712 ** vice-versa). 4713 */ 4714 static int moveToChild(BtCursor *pCur, u32 newPgno){ 4715 BtShared *pBt = pCur->pBt; 4716 4717 assert( cursorHoldsMutex(pCur) ); 4718 assert( pCur->eState==CURSOR_VALID ); 4719 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); 4720 assert( pCur->iPage>=0 ); 4721 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ 4722 return SQLITE_CORRUPT_BKPT; 4723 } 4724 pCur->info.nSize = 0; 4725 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 4726 pCur->iPage++; 4727 pCur->aiIdx[pCur->iPage] = 0; 4728 return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage], 4729 pCur, pCur->curPagerFlags); 4730 } 4731 4732 #if SQLITE_DEBUG 4733 /* 4734 ** Page pParent is an internal (non-leaf) tree page. This function 4735 ** asserts that page number iChild is the left-child if the iIdx'th 4736 ** cell in page pParent. Or, if iIdx is equal to the total number of 4737 ** cells in pParent, that page number iChild is the right-child of 4738 ** the page. 4739 */ 4740 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ 4741 if( CORRUPT_DB ) return; /* The conditions tested below might not be true 4742 ** in a corrupt database */ 4743 assert( iIdx<=pParent->nCell ); 4744 if( iIdx==pParent->nCell ){ 4745 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); 4746 }else{ 4747 assert( get4byte(findCell(pParent, iIdx))==iChild ); 4748 } 4749 } 4750 #else 4751 # define assertParentIndex(x,y,z) 4752 #endif 4753 4754 /* 4755 ** Move the cursor up to the parent page. 4756 ** 4757 ** pCur->idx is set to the cell index that contains the pointer 4758 ** to the page we are coming from. If we are coming from the 4759 ** right-most child page then pCur->idx is set to one more than 4760 ** the largest cell index. 4761 */ 4762 static void moveToParent(BtCursor *pCur){ 4763 assert( cursorHoldsMutex(pCur) ); 4764 assert( pCur->eState==CURSOR_VALID ); 4765 assert( pCur->iPage>0 ); 4766 assert( pCur->apPage[pCur->iPage] ); 4767 assertParentIndex( 4768 pCur->apPage[pCur->iPage-1], 4769 pCur->aiIdx[pCur->iPage-1], 4770 pCur->apPage[pCur->iPage]->pgno 4771 ); 4772 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); 4773 pCur->info.nSize = 0; 4774 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 4775 releasePageNotNull(pCur->apPage[pCur->iPage--]); 4776 } 4777 4778 /* 4779 ** Move the cursor to point to the root page of its b-tree structure. 4780 ** 4781 ** If the table has a virtual root page, then the cursor is moved to point 4782 ** to the virtual root page instead of the actual root page. A table has a 4783 ** virtual root page when the actual root page contains no cells and a 4784 ** single child page. This can only happen with the table rooted at page 1. 4785 ** 4786 ** If the b-tree structure is empty, the cursor state is set to 4787 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first 4788 ** cell located on the root (or virtual root) page and the cursor state 4789 ** is set to CURSOR_VALID. 4790 ** 4791 ** If this function returns successfully, it may be assumed that the 4792 ** page-header flags indicate that the [virtual] root-page is the expected 4793 ** kind of b-tree page (i.e. if when opening the cursor the caller did not 4794 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, 4795 ** indicating a table b-tree, or if the caller did specify a KeyInfo 4796 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index 4797 ** b-tree). 4798 */ 4799 static int moveToRoot(BtCursor *pCur){ 4800 MemPage *pRoot; 4801 int rc = SQLITE_OK; 4802 4803 assert( cursorHoldsMutex(pCur) ); 4804 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); 4805 assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); 4806 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); 4807 if( pCur->eState>=CURSOR_REQUIRESEEK ){ 4808 if( pCur->eState==CURSOR_FAULT ){ 4809 assert( pCur->skipNext!=SQLITE_OK ); 4810 return pCur->skipNext; 4811 } 4812 sqlite3BtreeClearCursor(pCur); 4813 } 4814 4815 if( pCur->iPage>=0 ){ 4816 while( pCur->iPage ){ 4817 assert( pCur->apPage[pCur->iPage]!=0 ); 4818 releasePageNotNull(pCur->apPage[pCur->iPage--]); 4819 } 4820 }else if( pCur->pgnoRoot==0 ){ 4821 pCur->eState = CURSOR_INVALID; 4822 return SQLITE_OK; 4823 }else{ 4824 assert( pCur->iPage==(-1) ); 4825 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0], 4826 0, pCur->curPagerFlags); 4827 if( rc!=SQLITE_OK ){ 4828 pCur->eState = CURSOR_INVALID; 4829 return rc; 4830 } 4831 pCur->iPage = 0; 4832 pCur->curIntKey = pCur->apPage[0]->intKey; 4833 } 4834 pRoot = pCur->apPage[0]; 4835 assert( pRoot->pgno==pCur->pgnoRoot ); 4836 4837 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor 4838 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is 4839 ** NULL, the caller expects a table b-tree. If this is not the case, 4840 ** return an SQLITE_CORRUPT error. 4841 ** 4842 ** Earlier versions of SQLite assumed that this test could not fail 4843 ** if the root page was already loaded when this function was called (i.e. 4844 ** if pCur->iPage>=0). But this is not so if the database is corrupted 4845 ** in such a way that page pRoot is linked into a second b-tree table 4846 ** (or the freelist). */ 4847 assert( pRoot->intKey==1 || pRoot->intKey==0 ); 4848 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ 4849 return SQLITE_CORRUPT_BKPT; 4850 } 4851 4852 pCur->aiIdx[0] = 0; 4853 pCur->info.nSize = 0; 4854 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); 4855 4856 if( pRoot->nCell>0 ){ 4857 pCur->eState = CURSOR_VALID; 4858 }else if( !pRoot->leaf ){ 4859 Pgno subpage; 4860 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; 4861 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); 4862 pCur->eState = CURSOR_VALID; 4863 rc = moveToChild(pCur, subpage); 4864 }else{ 4865 pCur->eState = CURSOR_INVALID; 4866 } 4867 return rc; 4868 } 4869 4870 /* 4871 ** Move the cursor down to the left-most leaf entry beneath the 4872 ** entry to which it is currently pointing. 4873 ** 4874 ** The left-most leaf is the one with the smallest key - the first 4875 ** in ascending order. 4876 */ 4877 static int moveToLeftmost(BtCursor *pCur){ 4878 Pgno pgno; 4879 int rc = SQLITE_OK; 4880 MemPage *pPage; 4881 4882 assert( cursorHoldsMutex(pCur) ); 4883 assert( pCur->eState==CURSOR_VALID ); 4884 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ 4885 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); 4886 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); 4887 rc = moveToChild(pCur, pgno); 4888 } 4889 return rc; 4890 } 4891 4892 /* 4893 ** Move the cursor down to the right-most leaf entry beneath the 4894 ** page to which it is currently pointing. Notice the difference 4895 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() 4896 ** finds the left-most entry beneath the *entry* whereas moveToRightmost() 4897 ** finds the right-most entry beneath the *page*. 4898 ** 4899 ** The right-most entry is the one with the largest key - the last 4900 ** key in ascending order. 4901 */ 4902 static int moveToRightmost(BtCursor *pCur){ 4903 Pgno pgno; 4904 int rc = SQLITE_OK; 4905 MemPage *pPage = 0; 4906 4907 assert( cursorHoldsMutex(pCur) ); 4908 assert( pCur->eState==CURSOR_VALID ); 4909 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){ 4910 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 4911 pCur->aiIdx[pCur->iPage] = pPage->nCell; 4912 rc = moveToChild(pCur, pgno); 4913 if( rc ) return rc; 4914 } 4915 pCur->aiIdx[pCur->iPage] = pPage->nCell-1; 4916 assert( pCur->info.nSize==0 ); 4917 assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); 4918 return SQLITE_OK; 4919 } 4920 4921 /* Move the cursor to the first entry in the table. Return SQLITE_OK 4922 ** on success. Set *pRes to 0 if the cursor actually points to something 4923 ** or set *pRes to 1 if the table is empty. 4924 */ 4925 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ 4926 int rc; 4927 4928 assert( cursorHoldsMutex(pCur) ); 4929 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 4930 rc = moveToRoot(pCur); 4931 if( rc==SQLITE_OK ){ 4932 if( pCur->eState==CURSOR_INVALID ){ 4933 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); 4934 *pRes = 1; 4935 }else{ 4936 assert( pCur->apPage[pCur->iPage]->nCell>0 ); 4937 *pRes = 0; 4938 rc = moveToLeftmost(pCur); 4939 } 4940 } 4941 return rc; 4942 } 4943 4944 /* Move the cursor to the last entry in the table. Return SQLITE_OK 4945 ** on success. Set *pRes to 0 if the cursor actually points to something 4946 ** or set *pRes to 1 if the table is empty. 4947 */ 4948 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ 4949 int rc; 4950 4951 assert( cursorHoldsMutex(pCur) ); 4952 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 4953 4954 /* If the cursor already points to the last entry, this is a no-op. */ 4955 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ 4956 #ifdef SQLITE_DEBUG 4957 /* This block serves to assert() that the cursor really does point 4958 ** to the last entry in the b-tree. */ 4959 int ii; 4960 for(ii=0; ii<pCur->iPage; ii++){ 4961 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); 4962 } 4963 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); 4964 assert( pCur->apPage[pCur->iPage]->leaf ); 4965 #endif 4966 return SQLITE_OK; 4967 } 4968 4969 rc = moveToRoot(pCur); 4970 if( rc==SQLITE_OK ){ 4971 if( CURSOR_INVALID==pCur->eState ){ 4972 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); 4973 *pRes = 1; 4974 }else{ 4975 assert( pCur->eState==CURSOR_VALID ); 4976 *pRes = 0; 4977 rc = moveToRightmost(pCur); 4978 if( rc==SQLITE_OK ){ 4979 pCur->curFlags |= BTCF_AtLast; 4980 }else{ 4981 pCur->curFlags &= ~BTCF_AtLast; 4982 } 4983 4984 } 4985 } 4986 return rc; 4987 } 4988 4989 /* Move the cursor so that it points to an entry near the key 4990 ** specified by pIdxKey or intKey. Return a success code. 4991 ** 4992 ** For INTKEY tables, the intKey parameter is used. pIdxKey 4993 ** must be NULL. For index tables, pIdxKey is used and intKey 4994 ** is ignored. 4995 ** 4996 ** If an exact match is not found, then the cursor is always 4997 ** left pointing at a leaf page which would hold the entry if it 4998 ** were present. The cursor might point to an entry that comes 4999 ** before or after the key. 5000 ** 5001 ** An integer is written into *pRes which is the result of 5002 ** comparing the key with the entry to which the cursor is 5003 ** pointing. The meaning of the integer written into 5004 ** *pRes is as follows: 5005 ** 5006 ** *pRes<0 The cursor is left pointing at an entry that 5007 ** is smaller than intKey/pIdxKey or if the table is empty 5008 ** and the cursor is therefore left point to nothing. 5009 ** 5010 ** *pRes==0 The cursor is left pointing at an entry that 5011 ** exactly matches intKey/pIdxKey. 5012 ** 5013 ** *pRes>0 The cursor is left pointing at an entry that 5014 ** is larger than intKey/pIdxKey. 5015 ** 5016 */ 5017 int sqlite3BtreeMovetoUnpacked( 5018 BtCursor *pCur, /* The cursor to be moved */ 5019 UnpackedRecord *pIdxKey, /* Unpacked index key */ 5020 i64 intKey, /* The table key */ 5021 int biasRight, /* If true, bias the search to the high end */ 5022 int *pRes /* Write search results here */ 5023 ){ 5024 int rc; 5025 RecordCompare xRecordCompare; 5026 5027 assert( cursorHoldsMutex(pCur) ); 5028 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5029 assert( pRes ); 5030 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); 5031 5032 /* If the cursor is already positioned at the point we are trying 5033 ** to move to, then just return without doing any work */ 5034 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 5035 && pCur->curIntKey 5036 ){ 5037 if( pCur->info.nKey==intKey ){ 5038 *pRes = 0; 5039 return SQLITE_OK; 5040 } 5041 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){ 5042 *pRes = -1; 5043 return SQLITE_OK; 5044 } 5045 } 5046 5047 if( pIdxKey ){ 5048 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); 5049 pIdxKey->errCode = 0; 5050 assert( pIdxKey->default_rc==1 5051 || pIdxKey->default_rc==0 5052 || pIdxKey->default_rc==-1 5053 ); 5054 }else{ 5055 xRecordCompare = 0; /* All keys are integers */ 5056 } 5057 5058 rc = moveToRoot(pCur); 5059 if( rc ){ 5060 return rc; 5061 } 5062 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] ); 5063 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); 5064 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); 5065 if( pCur->eState==CURSOR_INVALID ){ 5066 *pRes = -1; 5067 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); 5068 return SQLITE_OK; 5069 } 5070 assert( pCur->apPage[0]->intKey==pCur->curIntKey ); 5071 assert( pCur->curIntKey || pIdxKey ); 5072 for(;;){ 5073 int lwr, upr, idx, c; 5074 Pgno chldPg; 5075 MemPage *pPage = pCur->apPage[pCur->iPage]; 5076 u8 *pCell; /* Pointer to current cell in pPage */ 5077 5078 /* pPage->nCell must be greater than zero. If this is the root-page 5079 ** the cursor would have been INVALID above and this for(;;) loop 5080 ** not run. If this is not the root-page, then the moveToChild() routine 5081 ** would have already detected db corruption. Similarly, pPage must 5082 ** be the right kind (index or table) of b-tree page. Otherwise 5083 ** a moveToChild() or moveToRoot() call would have detected corruption. */ 5084 assert( pPage->nCell>0 ); 5085 assert( pPage->intKey==(pIdxKey==0) ); 5086 lwr = 0; 5087 upr = pPage->nCell-1; 5088 assert( biasRight==0 || biasRight==1 ); 5089 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ 5090 pCur->aiIdx[pCur->iPage] = (u16)idx; 5091 if( xRecordCompare==0 ){ 5092 for(;;){ 5093 i64 nCellKey; 5094 pCell = findCellPastPtr(pPage, idx); 5095 if( pPage->intKeyLeaf ){ 5096 while( 0x80 <= *(pCell++) ){ 5097 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; 5098 } 5099 } 5100 getVarint(pCell, (u64*)&nCellKey); 5101 if( nCellKey<intKey ){ 5102 lwr = idx+1; 5103 if( lwr>upr ){ c = -1; break; } 5104 }else if( nCellKey>intKey ){ 5105 upr = idx-1; 5106 if( lwr>upr ){ c = +1; break; } 5107 }else{ 5108 assert( nCellKey==intKey ); 5109 pCur->curFlags |= BTCF_ValidNKey; 5110 pCur->info.nKey = nCellKey; 5111 pCur->aiIdx[pCur->iPage] = (u16)idx; 5112 if( !pPage->leaf ){ 5113 lwr = idx; 5114 goto moveto_next_layer; 5115 }else{ 5116 *pRes = 0; 5117 rc = SQLITE_OK; 5118 goto moveto_finish; 5119 } 5120 } 5121 assert( lwr+upr>=0 ); 5122 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ 5123 } 5124 }else{ 5125 for(;;){ 5126 int nCell; /* Size of the pCell cell in bytes */ 5127 pCell = findCellPastPtr(pPage, idx); 5128 5129 /* The maximum supported page-size is 65536 bytes. This means that 5130 ** the maximum number of record bytes stored on an index B-Tree 5131 ** page is less than 16384 bytes and may be stored as a 2-byte 5132 ** varint. This information is used to attempt to avoid parsing 5133 ** the entire cell by checking for the cases where the record is 5134 ** stored entirely within the b-tree page by inspecting the first 5135 ** 2 bytes of the cell. 5136 */ 5137 nCell = pCell[0]; 5138 if( nCell<=pPage->max1bytePayload ){ 5139 /* This branch runs if the record-size field of the cell is a 5140 ** single byte varint and the record fits entirely on the main 5141 ** b-tree page. */ 5142 testcase( pCell+nCell+1==pPage->aDataEnd ); 5143 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); 5144 }else if( !(pCell[1] & 0x80) 5145 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal 5146 ){ 5147 /* The record-size field is a 2 byte varint and the record 5148 ** fits entirely on the main b-tree page. */ 5149 testcase( pCell+nCell+2==pPage->aDataEnd ); 5150 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); 5151 }else{ 5152 /* The record flows over onto one or more overflow pages. In 5153 ** this case the whole cell needs to be parsed, a buffer allocated 5154 ** and accessPayload() used to retrieve the record into the 5155 ** buffer before VdbeRecordCompare() can be called. 5156 ** 5157 ** If the record is corrupt, the xRecordCompare routine may read 5158 ** up to two varints past the end of the buffer. An extra 18 5159 ** bytes of padding is allocated at the end of the buffer in 5160 ** case this happens. */ 5161 void *pCellKey; 5162 u8 * const pCellBody = pCell - pPage->childPtrSize; 5163 pPage->xParseCell(pPage, pCellBody, &pCur->info); 5164 nCell = (int)pCur->info.nKey; 5165 testcase( nCell<0 ); /* True if key size is 2^32 or more */ 5166 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ 5167 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ 5168 testcase( nCell==2 ); /* Minimum legal index key size */ 5169 if( nCell<2 ){ 5170 rc = SQLITE_CORRUPT_BKPT; 5171 goto moveto_finish; 5172 } 5173 pCellKey = sqlite3Malloc( nCell+18 ); 5174 if( pCellKey==0 ){ 5175 rc = SQLITE_NOMEM; 5176 goto moveto_finish; 5177 } 5178 pCur->aiIdx[pCur->iPage] = (u16)idx; 5179 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2); 5180 if( rc ){ 5181 sqlite3_free(pCellKey); 5182 goto moveto_finish; 5183 } 5184 c = xRecordCompare(nCell, pCellKey, pIdxKey); 5185 sqlite3_free(pCellKey); 5186 } 5187 assert( 5188 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) 5189 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) 5190 ); 5191 if( c<0 ){ 5192 lwr = idx+1; 5193 }else if( c>0 ){ 5194 upr = idx-1; 5195 }else{ 5196 assert( c==0 ); 5197 *pRes = 0; 5198 rc = SQLITE_OK; 5199 pCur->aiIdx[pCur->iPage] = (u16)idx; 5200 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT; 5201 goto moveto_finish; 5202 } 5203 if( lwr>upr ) break; 5204 assert( lwr+upr>=0 ); 5205 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ 5206 } 5207 } 5208 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); 5209 assert( pPage->isInit ); 5210 if( pPage->leaf ){ 5211 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); 5212 pCur->aiIdx[pCur->iPage] = (u16)idx; 5213 *pRes = c; 5214 rc = SQLITE_OK; 5215 goto moveto_finish; 5216 } 5217 moveto_next_layer: 5218 if( lwr>=pPage->nCell ){ 5219 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5220 }else{ 5221 chldPg = get4byte(findCell(pPage, lwr)); 5222 } 5223 pCur->aiIdx[pCur->iPage] = (u16)lwr; 5224 rc = moveToChild(pCur, chldPg); 5225 if( rc ) break; 5226 } 5227 moveto_finish: 5228 pCur->info.nSize = 0; 5229 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5230 return rc; 5231 } 5232 5233 5234 /* 5235 ** Return TRUE if the cursor is not pointing at an entry of the table. 5236 ** 5237 ** TRUE will be returned after a call to sqlite3BtreeNext() moves 5238 ** past the last entry in the table or sqlite3BtreePrev() moves past 5239 ** the first entry. TRUE is also returned if the table is empty. 5240 */ 5241 int sqlite3BtreeEof(BtCursor *pCur){ 5242 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries 5243 ** have been deleted? This API will need to change to return an error code 5244 ** as well as the boolean result value. 5245 */ 5246 return (CURSOR_VALID!=pCur->eState); 5247 } 5248 5249 /* 5250 ** Advance the cursor to the next entry in the database. If 5251 ** successful then set *pRes=0. If the cursor 5252 ** was already pointing to the last entry in the database before 5253 ** this routine was called, then set *pRes=1. 5254 ** 5255 ** The main entry point is sqlite3BtreeNext(). That routine is optimized 5256 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx 5257 ** to the next cell on the current page. The (slower) btreeNext() helper 5258 ** routine is called when it is necessary to move to a different page or 5259 ** to restore the cursor. 5260 ** 5261 ** The calling function will set *pRes to 0 or 1. The initial *pRes value 5262 ** will be 1 if the cursor being stepped corresponds to an SQL index and 5263 ** if this routine could have been skipped if that SQL index had been 5264 ** a unique index. Otherwise the caller will have set *pRes to zero. 5265 ** Zero is the common case. The btree implementation is free to use the 5266 ** initial *pRes value as a hint to improve performance, but the current 5267 ** SQLite btree implementation does not. (Note that the comdb2 btree 5268 ** implementation does use this hint, however.) 5269 */ 5270 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ 5271 int rc; 5272 int idx; 5273 MemPage *pPage; 5274 5275 assert( cursorHoldsMutex(pCur) ); 5276 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); 5277 assert( *pRes==0 ); 5278 if( pCur->eState!=CURSOR_VALID ){ 5279 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5280 rc = restoreCursorPosition(pCur); 5281 if( rc!=SQLITE_OK ){ 5282 return rc; 5283 } 5284 if( CURSOR_INVALID==pCur->eState ){ 5285 *pRes = 1; 5286 return SQLITE_OK; 5287 } 5288 if( pCur->skipNext ){ 5289 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); 5290 pCur->eState = CURSOR_VALID; 5291 if( pCur->skipNext>0 ){ 5292 pCur->skipNext = 0; 5293 return SQLITE_OK; 5294 } 5295 pCur->skipNext = 0; 5296 } 5297 } 5298 5299 pPage = pCur->apPage[pCur->iPage]; 5300 idx = ++pCur->aiIdx[pCur->iPage]; 5301 assert( pPage->isInit ); 5302 5303 /* If the database file is corrupt, it is possible for the value of idx 5304 ** to be invalid here. This can only occur if a second cursor modifies 5305 ** the page while cursor pCur is holding a reference to it. Which can 5306 ** only happen if the database is corrupt in such a way as to link the 5307 ** page into more than one b-tree structure. */ 5308 testcase( idx>pPage->nCell ); 5309 5310 if( idx>=pPage->nCell ){ 5311 if( !pPage->leaf ){ 5312 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 5313 if( rc ) return rc; 5314 return moveToLeftmost(pCur); 5315 } 5316 do{ 5317 if( pCur->iPage==0 ){ 5318 *pRes = 1; 5319 pCur->eState = CURSOR_INVALID; 5320 return SQLITE_OK; 5321 } 5322 moveToParent(pCur); 5323 pPage = pCur->apPage[pCur->iPage]; 5324 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); 5325 if( pPage->intKey ){ 5326 return sqlite3BtreeNext(pCur, pRes); 5327 }else{ 5328 return SQLITE_OK; 5329 } 5330 } 5331 if( pPage->leaf ){ 5332 return SQLITE_OK; 5333 }else{ 5334 return moveToLeftmost(pCur); 5335 } 5336 } 5337 int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ 5338 MemPage *pPage; 5339 assert( cursorHoldsMutex(pCur) ); 5340 assert( pRes!=0 ); 5341 assert( *pRes==0 || *pRes==1 ); 5342 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); 5343 pCur->info.nSize = 0; 5344 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5345 *pRes = 0; 5346 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes); 5347 pPage = pCur->apPage[pCur->iPage]; 5348 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){ 5349 pCur->aiIdx[pCur->iPage]--; 5350 return btreeNext(pCur, pRes); 5351 } 5352 if( pPage->leaf ){ 5353 return SQLITE_OK; 5354 }else{ 5355 return moveToLeftmost(pCur); 5356 } 5357 } 5358 5359 /* 5360 ** Step the cursor to the back to the previous entry in the database. If 5361 ** successful then set *pRes=0. If the cursor 5362 ** was already pointing to the first entry in the database before 5363 ** this routine was called, then set *pRes=1. 5364 ** 5365 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized 5366 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx 5367 ** to the previous cell on the current page. The (slower) btreePrevious() 5368 ** helper routine is called when it is necessary to move to a different page 5369 ** or to restore the cursor. 5370 ** 5371 ** The calling function will set *pRes to 0 or 1. The initial *pRes value 5372 ** will be 1 if the cursor being stepped corresponds to an SQL index and 5373 ** if this routine could have been skipped if that SQL index had been 5374 ** a unique index. Otherwise the caller will have set *pRes to zero. 5375 ** Zero is the common case. The btree implementation is free to use the 5376 ** initial *pRes value as a hint to improve performance, but the current 5377 ** SQLite btree implementation does not. (Note that the comdb2 btree 5378 ** implementation does use this hint, however.) 5379 */ 5380 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ 5381 int rc; 5382 MemPage *pPage; 5383 5384 assert( cursorHoldsMutex(pCur) ); 5385 assert( pRes!=0 ); 5386 assert( *pRes==0 ); 5387 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); 5388 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); 5389 assert( pCur->info.nSize==0 ); 5390 if( pCur->eState!=CURSOR_VALID ){ 5391 rc = restoreCursorPosition(pCur); 5392 if( rc!=SQLITE_OK ){ 5393 return rc; 5394 } 5395 if( CURSOR_INVALID==pCur->eState ){ 5396 *pRes = 1; 5397 return SQLITE_OK; 5398 } 5399 if( pCur->skipNext ){ 5400 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); 5401 pCur->eState = CURSOR_VALID; 5402 if( pCur->skipNext<0 ){ 5403 pCur->skipNext = 0; 5404 return SQLITE_OK; 5405 } 5406 pCur->skipNext = 0; 5407 } 5408 } 5409 5410 pPage = pCur->apPage[pCur->iPage]; 5411 assert( pPage->isInit ); 5412 if( !pPage->leaf ){ 5413 int idx = pCur->aiIdx[pCur->iPage]; 5414 rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); 5415 if( rc ) return rc; 5416 rc = moveToRightmost(pCur); 5417 }else{ 5418 while( pCur->aiIdx[pCur->iPage]==0 ){ 5419 if( pCur->iPage==0 ){ 5420 pCur->eState = CURSOR_INVALID; 5421 *pRes = 1; 5422 return SQLITE_OK; 5423 } 5424 moveToParent(pCur); 5425 } 5426 assert( pCur->info.nSize==0 ); 5427 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 ); 5428 5429 pCur->aiIdx[pCur->iPage]--; 5430 pPage = pCur->apPage[pCur->iPage]; 5431 if( pPage->intKey && !pPage->leaf ){ 5432 rc = sqlite3BtreePrevious(pCur, pRes); 5433 }else{ 5434 rc = SQLITE_OK; 5435 } 5436 } 5437 return rc; 5438 } 5439 int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ 5440 assert( cursorHoldsMutex(pCur) ); 5441 assert( pRes!=0 ); 5442 assert( *pRes==0 || *pRes==1 ); 5443 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); 5444 *pRes = 0; 5445 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); 5446 pCur->info.nSize = 0; 5447 if( pCur->eState!=CURSOR_VALID 5448 || pCur->aiIdx[pCur->iPage]==0 5449 || pCur->apPage[pCur->iPage]->leaf==0 5450 ){ 5451 return btreePrevious(pCur, pRes); 5452 } 5453 pCur->aiIdx[pCur->iPage]--; 5454 return SQLITE_OK; 5455 } 5456 5457 /* 5458 ** Allocate a new page from the database file. 5459 ** 5460 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() 5461 ** has already been called on the new page.) The new page has also 5462 ** been referenced and the calling routine is responsible for calling 5463 ** sqlite3PagerUnref() on the new page when it is done. 5464 ** 5465 ** SQLITE_OK is returned on success. Any other return value indicates 5466 ** an error. *ppPage is set to NULL in the event of an error. 5467 ** 5468 ** If the "nearby" parameter is not 0, then an effort is made to 5469 ** locate a page close to the page number "nearby". This can be used in an 5470 ** attempt to keep related pages close to each other in the database file, 5471 ** which in turn can make database access faster. 5472 ** 5473 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists 5474 ** anywhere on the free-list, then it is guaranteed to be returned. If 5475 ** eMode is BTALLOC_LT then the page returned will be less than or equal 5476 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there 5477 ** are no restrictions on which page is returned. 5478 */ 5479 static int allocateBtreePage( 5480 BtShared *pBt, /* The btree */ 5481 MemPage **ppPage, /* Store pointer to the allocated page here */ 5482 Pgno *pPgno, /* Store the page number here */ 5483 Pgno nearby, /* Search for a page near this one */ 5484 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ 5485 ){ 5486 MemPage *pPage1; 5487 int rc; 5488 u32 n; /* Number of pages on the freelist */ 5489 u32 k; /* Number of leaves on the trunk of the freelist */ 5490 MemPage *pTrunk = 0; 5491 MemPage *pPrevTrunk = 0; 5492 Pgno mxPage; /* Total size of the database file */ 5493 5494 assert( sqlite3_mutex_held(pBt->mutex) ); 5495 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); 5496 pPage1 = pBt->pPage1; 5497 mxPage = btreePagecount(pBt); 5498 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 5499 ** stores stores the total number of pages on the freelist. */ 5500 n = get4byte(&pPage1->aData[36]); 5501 testcase( n==mxPage-1 ); 5502 if( n>=mxPage ){ 5503 return SQLITE_CORRUPT_BKPT; 5504 } 5505 if( n>0 ){ 5506 /* There are pages on the freelist. Reuse one of those pages. */ 5507 Pgno iTrunk; 5508 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ 5509 u32 nSearch = 0; /* Count of the number of search attempts */ 5510 5511 /* If eMode==BTALLOC_EXACT and a query of the pointer-map 5512 ** shows that the page 'nearby' is somewhere on the free-list, then 5513 ** the entire-list will be searched for that page. 5514 */ 5515 #ifndef SQLITE_OMIT_AUTOVACUUM 5516 if( eMode==BTALLOC_EXACT ){ 5517 if( nearby<=mxPage ){ 5518 u8 eType; 5519 assert( nearby>0 ); 5520 assert( pBt->autoVacuum ); 5521 rc = ptrmapGet(pBt, nearby, &eType, 0); 5522 if( rc ) return rc; 5523 if( eType==PTRMAP_FREEPAGE ){ 5524 searchList = 1; 5525 } 5526 } 5527 }else if( eMode==BTALLOC_LE ){ 5528 searchList = 1; 5529 } 5530 #endif 5531 5532 /* Decrement the free-list count by 1. Set iTrunk to the index of the 5533 ** first free-list trunk page. iPrevTrunk is initially 1. 5534 */ 5535 rc = sqlite3PagerWrite(pPage1->pDbPage); 5536 if( rc ) return rc; 5537 put4byte(&pPage1->aData[36], n-1); 5538 5539 /* The code within this loop is run only once if the 'searchList' variable 5540 ** is not true. Otherwise, it runs once for each trunk-page on the 5541 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) 5542 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) 5543 */ 5544 do { 5545 pPrevTrunk = pTrunk; 5546 if( pPrevTrunk ){ 5547 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page 5548 ** is the page number of the next freelist trunk page in the list or 5549 ** zero if this is the last freelist trunk page. */ 5550 iTrunk = get4byte(&pPrevTrunk->aData[0]); 5551 }else{ 5552 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 5553 ** stores the page number of the first page of the freelist, or zero if 5554 ** the freelist is empty. */ 5555 iTrunk = get4byte(&pPage1->aData[32]); 5556 } 5557 testcase( iTrunk==mxPage ); 5558 if( iTrunk>mxPage || nSearch++ > n ){ 5559 rc = SQLITE_CORRUPT_BKPT; 5560 }else{ 5561 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); 5562 } 5563 if( rc ){ 5564 pTrunk = 0; 5565 goto end_allocate_page; 5566 } 5567 assert( pTrunk!=0 ); 5568 assert( pTrunk->aData!=0 ); 5569 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page 5570 ** is the number of leaf page pointers to follow. */ 5571 k = get4byte(&pTrunk->aData[4]); 5572 if( k==0 && !searchList ){ 5573 /* The trunk has no leaves and the list is not being searched. 5574 ** So extract the trunk page itself and use it as the newly 5575 ** allocated page */ 5576 assert( pPrevTrunk==0 ); 5577 rc = sqlite3PagerWrite(pTrunk->pDbPage); 5578 if( rc ){ 5579 goto end_allocate_page; 5580 } 5581 *pPgno = iTrunk; 5582 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 5583 *ppPage = pTrunk; 5584 pTrunk = 0; 5585 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 5586 }else if( k>(u32)(pBt->usableSize/4 - 2) ){ 5587 /* Value of k is out of range. Database corruption */ 5588 rc = SQLITE_CORRUPT_BKPT; 5589 goto end_allocate_page; 5590 #ifndef SQLITE_OMIT_AUTOVACUUM 5591 }else if( searchList 5592 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 5593 ){ 5594 /* The list is being searched and this trunk page is the page 5595 ** to allocate, regardless of whether it has leaves. 5596 */ 5597 *pPgno = iTrunk; 5598 *ppPage = pTrunk; 5599 searchList = 0; 5600 rc = sqlite3PagerWrite(pTrunk->pDbPage); 5601 if( rc ){ 5602 goto end_allocate_page; 5603 } 5604 if( k==0 ){ 5605 if( !pPrevTrunk ){ 5606 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 5607 }else{ 5608 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 5609 if( rc!=SQLITE_OK ){ 5610 goto end_allocate_page; 5611 } 5612 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); 5613 } 5614 }else{ 5615 /* The trunk page is required by the caller but it contains 5616 ** pointers to free-list leaves. The first leaf becomes a trunk 5617 ** page in this case. 5618 */ 5619 MemPage *pNewTrunk; 5620 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); 5621 if( iNewTrunk>mxPage ){ 5622 rc = SQLITE_CORRUPT_BKPT; 5623 goto end_allocate_page; 5624 } 5625 testcase( iNewTrunk==mxPage ); 5626 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); 5627 if( rc!=SQLITE_OK ){ 5628 goto end_allocate_page; 5629 } 5630 rc = sqlite3PagerWrite(pNewTrunk->pDbPage); 5631 if( rc!=SQLITE_OK ){ 5632 releasePage(pNewTrunk); 5633 goto end_allocate_page; 5634 } 5635 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); 5636 put4byte(&pNewTrunk->aData[4], k-1); 5637 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); 5638 releasePage(pNewTrunk); 5639 if( !pPrevTrunk ){ 5640 assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); 5641 put4byte(&pPage1->aData[32], iNewTrunk); 5642 }else{ 5643 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 5644 if( rc ){ 5645 goto end_allocate_page; 5646 } 5647 put4byte(&pPrevTrunk->aData[0], iNewTrunk); 5648 } 5649 } 5650 pTrunk = 0; 5651 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 5652 #endif 5653 }else if( k>0 ){ 5654 /* Extract a leaf from the trunk */ 5655 u32 closest; 5656 Pgno iPage; 5657 unsigned char *aData = pTrunk->aData; 5658 if( nearby>0 ){ 5659 u32 i; 5660 closest = 0; 5661 if( eMode==BTALLOC_LE ){ 5662 for(i=0; i<k; i++){ 5663 iPage = get4byte(&aData[8+i*4]); 5664 if( iPage<=nearby ){ 5665 closest = i; 5666 break; 5667 } 5668 } 5669 }else{ 5670 int dist; 5671 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); 5672 for(i=1; i<k; i++){ 5673 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); 5674 if( d2<dist ){ 5675 closest = i; 5676 dist = d2; 5677 } 5678 } 5679 } 5680 }else{ 5681 closest = 0; 5682 } 5683 5684 iPage = get4byte(&aData[8+closest*4]); 5685 testcase( iPage==mxPage ); 5686 if( iPage>mxPage ){ 5687 rc = SQLITE_CORRUPT_BKPT; 5688 goto end_allocate_page; 5689 } 5690 testcase( iPage==mxPage ); 5691 if( !searchList 5692 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 5693 ){ 5694 int noContent; 5695 *pPgno = iPage; 5696 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" 5697 ": %d more free pages\n", 5698 *pPgno, closest+1, k, pTrunk->pgno, n-1)); 5699 rc = sqlite3PagerWrite(pTrunk->pDbPage); 5700 if( rc ) goto end_allocate_page; 5701 if( closest<k-1 ){ 5702 memcpy(&aData[8+closest*4], &aData[4+k*4], 4); 5703 } 5704 put4byte(&aData[4], k-1); 5705 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; 5706 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); 5707 if( rc==SQLITE_OK ){ 5708 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 5709 if( rc!=SQLITE_OK ){ 5710 releasePage(*ppPage); 5711 *ppPage = 0; 5712 } 5713 } 5714 searchList = 0; 5715 } 5716 } 5717 releasePage(pPrevTrunk); 5718 pPrevTrunk = 0; 5719 }while( searchList ); 5720 }else{ 5721 /* There are no pages on the freelist, so append a new page to the 5722 ** database image. 5723 ** 5724 ** Normally, new pages allocated by this block can be requested from the 5725 ** pager layer with the 'no-content' flag set. This prevents the pager 5726 ** from trying to read the pages content from disk. However, if the 5727 ** current transaction has already run one or more incremental-vacuum 5728 ** steps, then the page we are about to allocate may contain content 5729 ** that is required in the event of a rollback. In this case, do 5730 ** not set the no-content flag. This causes the pager to load and journal 5731 ** the current page content before overwriting it. 5732 ** 5733 ** Note that the pager will not actually attempt to load or journal 5734 ** content for any page that really does lie past the end of the database 5735 ** file on disk. So the effects of disabling the no-content optimization 5736 ** here are confined to those pages that lie between the end of the 5737 ** database image and the end of the database file. 5738 */ 5739 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; 5740 5741 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 5742 if( rc ) return rc; 5743 pBt->nPage++; 5744 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; 5745 5746 #ifndef SQLITE_OMIT_AUTOVACUUM 5747 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ 5748 /* If *pPgno refers to a pointer-map page, allocate two new pages 5749 ** at the end of the file instead of one. The first allocated page 5750 ** becomes a new pointer-map page, the second is used by the caller. 5751 */ 5752 MemPage *pPg = 0; 5753 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); 5754 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); 5755 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); 5756 if( rc==SQLITE_OK ){ 5757 rc = sqlite3PagerWrite(pPg->pDbPage); 5758 releasePage(pPg); 5759 } 5760 if( rc ) return rc; 5761 pBt->nPage++; 5762 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } 5763 } 5764 #endif 5765 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); 5766 *pPgno = pBt->nPage; 5767 5768 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); 5769 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); 5770 if( rc ) return rc; 5771 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 5772 if( rc!=SQLITE_OK ){ 5773 releasePage(*ppPage); 5774 *ppPage = 0; 5775 } 5776 TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); 5777 } 5778 5779 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); 5780 5781 end_allocate_page: 5782 releasePage(pTrunk); 5783 releasePage(pPrevTrunk); 5784 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); 5785 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); 5786 return rc; 5787 } 5788 5789 /* 5790 ** This function is used to add page iPage to the database file free-list. 5791 ** It is assumed that the page is not already a part of the free-list. 5792 ** 5793 ** The value passed as the second argument to this function is optional. 5794 ** If the caller happens to have a pointer to the MemPage object 5795 ** corresponding to page iPage handy, it may pass it as the second value. 5796 ** Otherwise, it may pass NULL. 5797 ** 5798 ** If a pointer to a MemPage object is passed as the second argument, 5799 ** its reference count is not altered by this function. 5800 */ 5801 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ 5802 MemPage *pTrunk = 0; /* Free-list trunk page */ 5803 Pgno iTrunk = 0; /* Page number of free-list trunk page */ 5804 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ 5805 MemPage *pPage; /* Page being freed. May be NULL. */ 5806 int rc; /* Return Code */ 5807 int nFree; /* Initial number of pages on free-list */ 5808 5809 assert( sqlite3_mutex_held(pBt->mutex) ); 5810 assert( CORRUPT_DB || iPage>1 ); 5811 assert( !pMemPage || pMemPage->pgno==iPage ); 5812 5813 if( iPage<2 ) return SQLITE_CORRUPT_BKPT; 5814 if( pMemPage ){ 5815 pPage = pMemPage; 5816 sqlite3PagerRef(pPage->pDbPage); 5817 }else{ 5818 pPage = btreePageLookup(pBt, iPage); 5819 } 5820 5821 /* Increment the free page count on pPage1 */ 5822 rc = sqlite3PagerWrite(pPage1->pDbPage); 5823 if( rc ) goto freepage_out; 5824 nFree = get4byte(&pPage1->aData[36]); 5825 put4byte(&pPage1->aData[36], nFree+1); 5826 5827 if( pBt->btsFlags & BTS_SECURE_DELETE ){ 5828 /* If the secure_delete option is enabled, then 5829 ** always fully overwrite deleted information with zeros. 5830 */ 5831 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) 5832 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) 5833 ){ 5834 goto freepage_out; 5835 } 5836 memset(pPage->aData, 0, pPage->pBt->pageSize); 5837 } 5838 5839 /* If the database supports auto-vacuum, write an entry in the pointer-map 5840 ** to indicate that the page is free. 5841 */ 5842 if( ISAUTOVACUUM ){ 5843 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); 5844 if( rc ) goto freepage_out; 5845 } 5846 5847 /* Now manipulate the actual database free-list structure. There are two 5848 ** possibilities. If the free-list is currently empty, or if the first 5849 ** trunk page in the free-list is full, then this page will become a 5850 ** new free-list trunk page. Otherwise, it will become a leaf of the 5851 ** first trunk page in the current free-list. This block tests if it 5852 ** is possible to add the page as a new free-list leaf. 5853 */ 5854 if( nFree!=0 ){ 5855 u32 nLeaf; /* Initial number of leaf cells on trunk page */ 5856 5857 iTrunk = get4byte(&pPage1->aData[32]); 5858 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); 5859 if( rc!=SQLITE_OK ){ 5860 goto freepage_out; 5861 } 5862 5863 nLeaf = get4byte(&pTrunk->aData[4]); 5864 assert( pBt->usableSize>32 ); 5865 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ 5866 rc = SQLITE_CORRUPT_BKPT; 5867 goto freepage_out; 5868 } 5869 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ 5870 /* In this case there is room on the trunk page to insert the page 5871 ** being freed as a new leaf. 5872 ** 5873 ** Note that the trunk page is not really full until it contains 5874 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have 5875 ** coded. But due to a coding error in versions of SQLite prior to 5876 ** 3.6.0, databases with freelist trunk pages holding more than 5877 ** usableSize/4 - 8 entries will be reported as corrupt. In order 5878 ** to maintain backwards compatibility with older versions of SQLite, 5879 ** we will continue to restrict the number of entries to usableSize/4 - 8 5880 ** for now. At some point in the future (once everyone has upgraded 5881 ** to 3.6.0 or later) we should consider fixing the conditional above 5882 ** to read "usableSize/4-2" instead of "usableSize/4-8". 5883 ** 5884 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still 5885 ** avoid using the last six entries in the freelist trunk page array in 5886 ** order that database files created by newer versions of SQLite can be 5887 ** read by older versions of SQLite. 5888 */ 5889 rc = sqlite3PagerWrite(pTrunk->pDbPage); 5890 if( rc==SQLITE_OK ){ 5891 put4byte(&pTrunk->aData[4], nLeaf+1); 5892 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); 5893 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ 5894 sqlite3PagerDontWrite(pPage->pDbPage); 5895 } 5896 rc = btreeSetHasContent(pBt, iPage); 5897 } 5898 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); 5899 goto freepage_out; 5900 } 5901 } 5902 5903 /* If control flows to this point, then it was not possible to add the 5904 ** the page being freed as a leaf page of the first trunk in the free-list. 5905 ** Possibly because the free-list is empty, or possibly because the 5906 ** first trunk in the free-list is full. Either way, the page being freed 5907 ** will become the new first trunk page in the free-list. 5908 */ 5909 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ 5910 goto freepage_out; 5911 } 5912 rc = sqlite3PagerWrite(pPage->pDbPage); 5913 if( rc!=SQLITE_OK ){ 5914 goto freepage_out; 5915 } 5916 put4byte(pPage->aData, iTrunk); 5917 put4byte(&pPage->aData[4], 0); 5918 put4byte(&pPage1->aData[32], iPage); 5919 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); 5920 5921 freepage_out: 5922 if( pPage ){ 5923 pPage->isInit = 0; 5924 } 5925 releasePage(pPage); 5926 releasePage(pTrunk); 5927 return rc; 5928 } 5929 static void freePage(MemPage *pPage, int *pRC){ 5930 if( (*pRC)==SQLITE_OK ){ 5931 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); 5932 } 5933 } 5934 5935 /* 5936 ** Free any overflow pages associated with the given Cell. Write the 5937 ** local Cell size (the number of bytes on the original page, omitting 5938 ** overflow) into *pnSize. 5939 */ 5940 static int clearCell( 5941 MemPage *pPage, /* The page that contains the Cell */ 5942 unsigned char *pCell, /* First byte of the Cell */ 5943 u16 *pnSize /* Write the size of the Cell here */ 5944 ){ 5945 BtShared *pBt = pPage->pBt; 5946 CellInfo info; 5947 Pgno ovflPgno; 5948 int rc; 5949 int nOvfl; 5950 u32 ovflPageSize; 5951 5952 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 5953 pPage->xParseCell(pPage, pCell, &info); 5954 *pnSize = info.nSize; 5955 if( info.iOverflow==0 ){ 5956 return SQLITE_OK; /* No overflow pages. Return without doing anything */ 5957 } 5958 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){ 5959 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ 5960 } 5961 ovflPgno = get4byte(&pCell[info.iOverflow]); 5962 assert( pBt->usableSize > 4 ); 5963 ovflPageSize = pBt->usableSize - 4; 5964 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; 5965 assert( nOvfl>0 || 5966 (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize) 5967 ); 5968 while( nOvfl-- ){ 5969 Pgno iNext = 0; 5970 MemPage *pOvfl = 0; 5971 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ 5972 /* 0 is not a legal page number and page 1 cannot be an 5973 ** overflow page. Therefore if ovflPgno<2 or past the end of the 5974 ** file the database must be corrupt. */ 5975 return SQLITE_CORRUPT_BKPT; 5976 } 5977 if( nOvfl ){ 5978 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); 5979 if( rc ) return rc; 5980 } 5981 5982 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) 5983 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 5984 ){ 5985 /* There is no reason any cursor should have an outstanding reference 5986 ** to an overflow page belonging to a cell that is being deleted/updated. 5987 ** So if there exists more than one reference to this page, then it 5988 ** must not really be an overflow page and the database must be corrupt. 5989 ** It is helpful to detect this before calling freePage2(), as 5990 ** freePage2() may zero the page contents if secure-delete mode is 5991 ** enabled. If this 'overflow' page happens to be a page that the 5992 ** caller is iterating through or using in some other way, this 5993 ** can be problematic. 5994 */ 5995 rc = SQLITE_CORRUPT_BKPT; 5996 }else{ 5997 rc = freePage2(pBt, pOvfl, ovflPgno); 5998 } 5999 6000 if( pOvfl ){ 6001 sqlite3PagerUnref(pOvfl->pDbPage); 6002 } 6003 if( rc ) return rc; 6004 ovflPgno = iNext; 6005 } 6006 return SQLITE_OK; 6007 } 6008 6009 /* 6010 ** Create the byte sequence used to represent a cell on page pPage 6011 ** and write that byte sequence into pCell[]. Overflow pages are 6012 ** allocated and filled in as necessary. The calling procedure 6013 ** is responsible for making sure sufficient space has been allocated 6014 ** for pCell[]. 6015 ** 6016 ** Note that pCell does not necessary need to point to the pPage->aData 6017 ** area. pCell might point to some temporary storage. The cell will 6018 ** be constructed in this temporary area then copied into pPage->aData 6019 ** later. 6020 */ 6021 static int fillInCell( 6022 MemPage *pPage, /* The page that contains the cell */ 6023 unsigned char *pCell, /* Complete text of the cell */ 6024 const void *pKey, i64 nKey, /* The key */ 6025 const void *pData,int nData, /* The data */ 6026 int nZero, /* Extra zero bytes to append to pData */ 6027 int *pnSize /* Write cell size here */ 6028 ){ 6029 int nPayload; 6030 const u8 *pSrc; 6031 int nSrc, n, rc; 6032 int spaceLeft; 6033 MemPage *pOvfl = 0; 6034 MemPage *pToRelease = 0; 6035 unsigned char *pPrior; 6036 unsigned char *pPayload; 6037 BtShared *pBt = pPage->pBt; 6038 Pgno pgnoOvfl = 0; 6039 int nHeader; 6040 6041 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6042 6043 /* pPage is not necessarily writeable since pCell might be auxiliary 6044 ** buffer space that is separate from the pPage buffer area */ 6045 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize] 6046 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6047 6048 /* Fill in the header. */ 6049 nHeader = pPage->childPtrSize; 6050 nPayload = nData + nZero; 6051 if( pPage->intKeyLeaf ){ 6052 nHeader += putVarint32(&pCell[nHeader], nPayload); 6053 }else{ 6054 assert( nData==0 ); 6055 assert( nZero==0 ); 6056 } 6057 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); 6058 6059 /* Fill in the payload size */ 6060 if( pPage->intKey ){ 6061 pSrc = pData; 6062 nSrc = nData; 6063 nData = 0; 6064 }else{ 6065 assert( nKey<=0x7fffffff && pKey!=0 ); 6066 nPayload = (int)nKey; 6067 pSrc = pKey; 6068 nSrc = (int)nKey; 6069 } 6070 if( nPayload<=pPage->maxLocal ){ 6071 n = nHeader + nPayload; 6072 testcase( n==3 ); 6073 testcase( n==4 ); 6074 if( n<4 ) n = 4; 6075 *pnSize = n; 6076 spaceLeft = nPayload; 6077 pPrior = pCell; 6078 }else{ 6079 int mn = pPage->minLocal; 6080 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); 6081 testcase( n==pPage->maxLocal ); 6082 testcase( n==pPage->maxLocal+1 ); 6083 if( n > pPage->maxLocal ) n = mn; 6084 spaceLeft = n; 6085 *pnSize = n + nHeader + 4; 6086 pPrior = &pCell[nHeader+n]; 6087 } 6088 pPayload = &pCell[nHeader]; 6089 6090 /* At this point variables should be set as follows: 6091 ** 6092 ** nPayload Total payload size in bytes 6093 ** pPayload Begin writing payload here 6094 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, 6095 ** that means content must spill into overflow pages. 6096 ** *pnSize Size of the local cell (not counting overflow pages) 6097 ** pPrior Where to write the pgno of the first overflow page 6098 ** 6099 ** Use a call to btreeParseCellPtr() to verify that the values above 6100 ** were computed correctly. 6101 */ 6102 #if SQLITE_DEBUG 6103 { 6104 CellInfo info; 6105 pPage->xParseCell(pPage, pCell, &info); 6106 assert( nHeader=(int)(info.pPayload - pCell) ); 6107 assert( info.nKey==nKey ); 6108 assert( *pnSize == info.nSize ); 6109 assert( spaceLeft == info.nLocal ); 6110 assert( pPrior == &pCell[info.iOverflow] ); 6111 } 6112 #endif 6113 6114 /* Write the payload into the local Cell and any extra into overflow pages */ 6115 while( nPayload>0 ){ 6116 if( spaceLeft==0 ){ 6117 #ifndef SQLITE_OMIT_AUTOVACUUM 6118 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ 6119 if( pBt->autoVacuum ){ 6120 do{ 6121 pgnoOvfl++; 6122 } while( 6123 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 6124 ); 6125 } 6126 #endif 6127 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); 6128 #ifndef SQLITE_OMIT_AUTOVACUUM 6129 /* If the database supports auto-vacuum, and the second or subsequent 6130 ** overflow page is being allocated, add an entry to the pointer-map 6131 ** for that page now. 6132 ** 6133 ** If this is the first overflow page, then write a partial entry 6134 ** to the pointer-map. If we write nothing to this pointer-map slot, 6135 ** then the optimistic overflow chain processing in clearCell() 6136 ** may misinterpret the uninitialized values and delete the 6137 ** wrong pages from the database. 6138 */ 6139 if( pBt->autoVacuum && rc==SQLITE_OK ){ 6140 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); 6141 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); 6142 if( rc ){ 6143 releasePage(pOvfl); 6144 } 6145 } 6146 #endif 6147 if( rc ){ 6148 releasePage(pToRelease); 6149 return rc; 6150 } 6151 6152 /* If pToRelease is not zero than pPrior points into the data area 6153 ** of pToRelease. Make sure pToRelease is still writeable. */ 6154 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6155 6156 /* If pPrior is part of the data area of pPage, then make sure pPage 6157 ** is still writeable */ 6158 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize] 6159 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6160 6161 put4byte(pPrior, pgnoOvfl); 6162 releasePage(pToRelease); 6163 pToRelease = pOvfl; 6164 pPrior = pOvfl->aData; 6165 put4byte(pPrior, 0); 6166 pPayload = &pOvfl->aData[4]; 6167 spaceLeft = pBt->usableSize - 4; 6168 } 6169 n = nPayload; 6170 if( n>spaceLeft ) n = spaceLeft; 6171 6172 /* If pToRelease is not zero than pPayload points into the data area 6173 ** of pToRelease. Make sure pToRelease is still writeable. */ 6174 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6175 6176 /* If pPayload is part of the data area of pPage, then make sure pPage 6177 ** is still writeable */ 6178 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] 6179 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6180 6181 if( nSrc>0 ){ 6182 if( n>nSrc ) n = nSrc; 6183 assert( pSrc ); 6184 memcpy(pPayload, pSrc, n); 6185 }else{ 6186 memset(pPayload, 0, n); 6187 } 6188 nPayload -= n; 6189 pPayload += n; 6190 pSrc += n; 6191 nSrc -= n; 6192 spaceLeft -= n; 6193 if( nSrc==0 ){ 6194 nSrc = nData; 6195 pSrc = pData; 6196 } 6197 } 6198 releasePage(pToRelease); 6199 return SQLITE_OK; 6200 } 6201 6202 /* 6203 ** Remove the i-th cell from pPage. This routine effects pPage only. 6204 ** The cell content is not freed or deallocated. It is assumed that 6205 ** the cell content has been copied someplace else. This routine just 6206 ** removes the reference to the cell from pPage. 6207 ** 6208 ** "sz" must be the number of bytes in the cell. 6209 */ 6210 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ 6211 u32 pc; /* Offset to cell content of cell being deleted */ 6212 u8 *data; /* pPage->aData */ 6213 u8 *ptr; /* Used to move bytes around within data[] */ 6214 int rc; /* The return code */ 6215 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ 6216 6217 if( *pRC ) return; 6218 6219 assert( idx>=0 && idx<pPage->nCell ); 6220 assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); 6221 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6222 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6223 data = pPage->aData; 6224 ptr = &pPage->aCellIdx[2*idx]; 6225 pc = get2byte(ptr); 6226 hdr = pPage->hdrOffset; 6227 testcase( pc==get2byte(&data[hdr+5]) ); 6228 testcase( pc+sz==pPage->pBt->usableSize ); 6229 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ 6230 *pRC = SQLITE_CORRUPT_BKPT; 6231 return; 6232 } 6233 rc = freeSpace(pPage, pc, sz); 6234 if( rc ){ 6235 *pRC = rc; 6236 return; 6237 } 6238 pPage->nCell--; 6239 if( pPage->nCell==0 ){ 6240 memset(&data[hdr+1], 0, 4); 6241 data[hdr+7] = 0; 6242 put2byte(&data[hdr+5], pPage->pBt->usableSize); 6243 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset 6244 - pPage->childPtrSize - 8; 6245 }else{ 6246 memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); 6247 put2byte(&data[hdr+3], pPage->nCell); 6248 pPage->nFree += 2; 6249 } 6250 } 6251 6252 /* 6253 ** Insert a new cell on pPage at cell index "i". pCell points to the 6254 ** content of the cell. 6255 ** 6256 ** If the cell content will fit on the page, then put it there. If it 6257 ** will not fit, then make a copy of the cell content into pTemp if 6258 ** pTemp is not null. Regardless of pTemp, allocate a new entry 6259 ** in pPage->apOvfl[] and make it point to the cell content (either 6260 ** in pTemp or the original pCell) and also record its index. 6261 ** Allocating a new entry in pPage->aCell[] implies that 6262 ** pPage->nOverflow is incremented. 6263 */ 6264 static void insertCell( 6265 MemPage *pPage, /* Page into which we are copying */ 6266 int i, /* New cell becomes the i-th cell of the page */ 6267 u8 *pCell, /* Content of the new cell */ 6268 int sz, /* Bytes of content in pCell */ 6269 u8 *pTemp, /* Temp storage space for pCell, if needed */ 6270 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ 6271 int *pRC /* Read and write return code from here */ 6272 ){ 6273 int idx = 0; /* Where to write new cell content in data[] */ 6274 int j; /* Loop counter */ 6275 u8 *data; /* The content of the whole page */ 6276 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ 6277 6278 if( *pRC ) return; 6279 6280 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); 6281 assert( MX_CELL(pPage->pBt)<=10921 ); 6282 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); 6283 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); 6284 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); 6285 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6286 /* The cell should normally be sized correctly. However, when moving a 6287 ** malformed cell from a leaf page to an interior page, if the cell size 6288 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size 6289 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence 6290 ** the term after the || in the following assert(). */ 6291 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) ); 6292 if( pPage->nOverflow || sz+2>pPage->nFree ){ 6293 if( pTemp ){ 6294 memcpy(pTemp, pCell, sz); 6295 pCell = pTemp; 6296 } 6297 if( iChild ){ 6298 put4byte(pCell, iChild); 6299 } 6300 j = pPage->nOverflow++; 6301 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); 6302 pPage->apOvfl[j] = pCell; 6303 pPage->aiOvfl[j] = (u16)i; 6304 6305 /* When multiple overflows occur, they are always sequential and in 6306 ** sorted order. This invariants arise because multiple overflows can 6307 ** only occur when inserting divider cells into the parent page during 6308 ** balancing, and the dividers are adjacent and sorted. 6309 */ 6310 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ 6311 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ 6312 }else{ 6313 int rc = sqlite3PagerWrite(pPage->pDbPage); 6314 if( rc!=SQLITE_OK ){ 6315 *pRC = rc; 6316 return; 6317 } 6318 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6319 data = pPage->aData; 6320 assert( &data[pPage->cellOffset]==pPage->aCellIdx ); 6321 rc = allocateSpace(pPage, sz, &idx); 6322 if( rc ){ *pRC = rc; return; } 6323 /* The allocateSpace() routine guarantees the following properties 6324 ** if it returns successfully */ 6325 assert( idx >= 0 ); 6326 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); 6327 assert( idx+sz <= (int)pPage->pBt->usableSize ); 6328 pPage->nFree -= (u16)(2 + sz); 6329 memcpy(&data[idx], pCell, sz); 6330 if( iChild ){ 6331 put4byte(&data[idx], iChild); 6332 } 6333 pIns = pPage->aCellIdx + i*2; 6334 memmove(pIns+2, pIns, 2*(pPage->nCell - i)); 6335 put2byte(pIns, idx); 6336 pPage->nCell++; 6337 /* increment the cell count */ 6338 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; 6339 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell ); 6340 #ifndef SQLITE_OMIT_AUTOVACUUM 6341 if( pPage->pBt->autoVacuum ){ 6342 /* The cell may contain a pointer to an overflow page. If so, write 6343 ** the entry for the overflow page into the pointer map. 6344 */ 6345 ptrmapPutOvflPtr(pPage, pCell, pRC); 6346 } 6347 #endif 6348 } 6349 } 6350 6351 /* 6352 ** A CellArray object contains a cache of pointers and sizes for a 6353 ** consecutive sequence of cells that might be held multiple pages. 6354 */ 6355 typedef struct CellArray CellArray; 6356 struct CellArray { 6357 int nCell; /* Number of cells in apCell[] */ 6358 MemPage *pRef; /* Reference page */ 6359 u8 **apCell; /* All cells begin balanced */ 6360 u16 *szCell; /* Local size of all cells in apCell[] */ 6361 }; 6362 6363 /* 6364 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been 6365 ** computed. 6366 */ 6367 static void populateCellCache(CellArray *p, int idx, int N){ 6368 assert( idx>=0 && idx+N<=p->nCell ); 6369 while( N>0 ){ 6370 assert( p->apCell[idx]!=0 ); 6371 if( p->szCell[idx]==0 ){ 6372 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); 6373 }else{ 6374 assert( CORRUPT_DB || 6375 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); 6376 } 6377 idx++; 6378 N--; 6379 } 6380 } 6381 6382 /* 6383 ** Return the size of the Nth element of the cell array 6384 */ 6385 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ 6386 assert( N>=0 && N<p->nCell ); 6387 assert( p->szCell[N]==0 ); 6388 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); 6389 return p->szCell[N]; 6390 } 6391 static u16 cachedCellSize(CellArray *p, int N){ 6392 assert( N>=0 && N<p->nCell ); 6393 if( p->szCell[N] ) return p->szCell[N]; 6394 return computeCellSize(p, N); 6395 } 6396 6397 /* 6398 ** Array apCell[] contains pointers to nCell b-tree page cells. The 6399 ** szCell[] array contains the size in bytes of each cell. This function 6400 ** replaces the current contents of page pPg with the contents of the cell 6401 ** array. 6402 ** 6403 ** Some of the cells in apCell[] may currently be stored in pPg. This 6404 ** function works around problems caused by this by making a copy of any 6405 ** such cells before overwriting the page data. 6406 ** 6407 ** The MemPage.nFree field is invalidated by this function. It is the 6408 ** responsibility of the caller to set it correctly. 6409 */ 6410 static int rebuildPage( 6411 MemPage *pPg, /* Edit this page */ 6412 int nCell, /* Final number of cells on page */ 6413 u8 **apCell, /* Array of cells */ 6414 u16 *szCell /* Array of cell sizes */ 6415 ){ 6416 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ 6417 u8 * const aData = pPg->aData; /* Pointer to data for pPg */ 6418 const int usableSize = pPg->pBt->usableSize; 6419 u8 * const pEnd = &aData[usableSize]; 6420 int i; 6421 u8 *pCellptr = pPg->aCellIdx; 6422 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 6423 u8 *pData; 6424 6425 i = get2byte(&aData[hdr+5]); 6426 memcpy(&pTmp[i], &aData[i], usableSize - i); 6427 6428 pData = pEnd; 6429 for(i=0; i<nCell; i++){ 6430 u8 *pCell = apCell[i]; 6431 if( pCell>aData && pCell<pEnd ){ 6432 pCell = &pTmp[pCell - aData]; 6433 } 6434 pData -= szCell[i]; 6435 put2byte(pCellptr, (pData - aData)); 6436 pCellptr += 2; 6437 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; 6438 memcpy(pData, pCell, szCell[i]); 6439 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); 6440 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); 6441 } 6442 6443 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ 6444 pPg->nCell = nCell; 6445 pPg->nOverflow = 0; 6446 6447 put2byte(&aData[hdr+1], 0); 6448 put2byte(&aData[hdr+3], pPg->nCell); 6449 put2byte(&aData[hdr+5], pData - aData); 6450 aData[hdr+7] = 0x00; 6451 return SQLITE_OK; 6452 } 6453 6454 /* 6455 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 6456 ** contains the size in bytes of each such cell. This function attempts to 6457 ** add the cells stored in the array to page pPg. If it cannot (because 6458 ** the page needs to be defragmented before the cells will fit), non-zero 6459 ** is returned. Otherwise, if the cells are added successfully, zero is 6460 ** returned. 6461 ** 6462 ** Argument pCellptr points to the first entry in the cell-pointer array 6463 ** (part of page pPg) to populate. After cell apCell[0] is written to the 6464 ** page body, a 16-bit offset is written to pCellptr. And so on, for each 6465 ** cell in the array. It is the responsibility of the caller to ensure 6466 ** that it is safe to overwrite this part of the cell-pointer array. 6467 ** 6468 ** When this function is called, *ppData points to the start of the 6469 ** content area on page pPg. If the size of the content area is extended, 6470 ** *ppData is updated to point to the new start of the content area 6471 ** before returning. 6472 ** 6473 ** Finally, argument pBegin points to the byte immediately following the 6474 ** end of the space required by this page for the cell-pointer area (for 6475 ** all cells - not just those inserted by the current call). If the content 6476 ** area must be extended to before this point in order to accomodate all 6477 ** cells in apCell[], then the cells do not fit and non-zero is returned. 6478 */ 6479 static int pageInsertArray( 6480 MemPage *pPg, /* Page to add cells to */ 6481 u8 *pBegin, /* End of cell-pointer array */ 6482 u8 **ppData, /* IN/OUT: Page content -area pointer */ 6483 u8 *pCellptr, /* Pointer to cell-pointer area */ 6484 int iFirst, /* Index of first cell to add */ 6485 int nCell, /* Number of cells to add to pPg */ 6486 CellArray *pCArray /* Array of cells */ 6487 ){ 6488 int i; 6489 u8 *aData = pPg->aData; 6490 u8 *pData = *ppData; 6491 int iEnd = iFirst + nCell; 6492 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ 6493 for(i=iFirst; i<iEnd; i++){ 6494 int sz, rc; 6495 u8 *pSlot; 6496 sz = cachedCellSize(pCArray, i); 6497 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ 6498 pData -= sz; 6499 if( pData<pBegin ) return 1; 6500 pSlot = pData; 6501 } 6502 memcpy(pSlot, pCArray->apCell[i], sz); 6503 put2byte(pCellptr, (pSlot - aData)); 6504 pCellptr += 2; 6505 } 6506 *ppData = pData; 6507 return 0; 6508 } 6509 6510 /* 6511 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 6512 ** contains the size in bytes of each such cell. This function adds the 6513 ** space associated with each cell in the array that is currently stored 6514 ** within the body of pPg to the pPg free-list. The cell-pointers and other 6515 ** fields of the page are not updated. 6516 ** 6517 ** This function returns the total number of cells added to the free-list. 6518 */ 6519 static int pageFreeArray( 6520 MemPage *pPg, /* Page to edit */ 6521 int iFirst, /* First cell to delete */ 6522 int nCell, /* Cells to delete */ 6523 CellArray *pCArray /* Array of cells */ 6524 ){ 6525 u8 * const aData = pPg->aData; 6526 u8 * const pEnd = &aData[pPg->pBt->usableSize]; 6527 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; 6528 int nRet = 0; 6529 int i; 6530 int iEnd = iFirst + nCell; 6531 u8 *pFree = 0; 6532 int szFree = 0; 6533 6534 for(i=iFirst; i<iEnd; i++){ 6535 u8 *pCell = pCArray->apCell[i]; 6536 if( pCell>=pStart && pCell<pEnd ){ 6537 int sz; 6538 /* No need to use cachedCellSize() here. The sizes of all cells that 6539 ** are to be freed have already been computing while deciding which 6540 ** cells need freeing */ 6541 sz = pCArray->szCell[i]; assert( sz>0 ); 6542 if( pFree!=(pCell + sz) ){ 6543 if( pFree ){ 6544 assert( pFree>aData && (pFree - aData)<65536 ); 6545 freeSpace(pPg, (u16)(pFree - aData), szFree); 6546 } 6547 pFree = pCell; 6548 szFree = sz; 6549 if( pFree+sz>pEnd ) return 0; 6550 }else{ 6551 pFree = pCell; 6552 szFree += sz; 6553 } 6554 nRet++; 6555 } 6556 } 6557 if( pFree ){ 6558 assert( pFree>aData && (pFree - aData)<65536 ); 6559 freeSpace(pPg, (u16)(pFree - aData), szFree); 6560 } 6561 return nRet; 6562 } 6563 6564 /* 6565 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the 6566 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting 6567 ** with apCell[iOld]. After balancing, this page should hold nNew cells 6568 ** starting at apCell[iNew]. 6569 ** 6570 ** This routine makes the necessary adjustments to pPg so that it contains 6571 ** the correct cells after being balanced. 6572 ** 6573 ** The pPg->nFree field is invalid when this function returns. It is the 6574 ** responsibility of the caller to set it correctly. 6575 */ 6576 static int editPage( 6577 MemPage *pPg, /* Edit this page */ 6578 int iOld, /* Index of first cell currently on page */ 6579 int iNew, /* Index of new first cell on page */ 6580 int nNew, /* Final number of cells on page */ 6581 CellArray *pCArray /* Array of cells and sizes */ 6582 ){ 6583 u8 * const aData = pPg->aData; 6584 const int hdr = pPg->hdrOffset; 6585 u8 *pBegin = &pPg->aCellIdx[nNew * 2]; 6586 int nCell = pPg->nCell; /* Cells stored on pPg */ 6587 u8 *pData; 6588 u8 *pCellptr; 6589 int i; 6590 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; 6591 int iNewEnd = iNew + nNew; 6592 6593 #ifdef SQLITE_DEBUG 6594 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 6595 memcpy(pTmp, aData, pPg->pBt->usableSize); 6596 #endif 6597 6598 /* Remove cells from the start and end of the page */ 6599 if( iOld<iNew ){ 6600 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); 6601 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); 6602 nCell -= nShift; 6603 } 6604 if( iNewEnd < iOldEnd ){ 6605 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); 6606 } 6607 6608 pData = &aData[get2byteNotZero(&aData[hdr+5])]; 6609 if( pData<pBegin ) goto editpage_fail; 6610 6611 /* Add cells to the start of the page */ 6612 if( iNew<iOld ){ 6613 int nAdd = MIN(nNew,iOld-iNew); 6614 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB ); 6615 pCellptr = pPg->aCellIdx; 6616 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); 6617 if( pageInsertArray( 6618 pPg, pBegin, &pData, pCellptr, 6619 iNew, nAdd, pCArray 6620 ) ) goto editpage_fail; 6621 nCell += nAdd; 6622 } 6623 6624 /* Add any overflow cells */ 6625 for(i=0; i<pPg->nOverflow; i++){ 6626 int iCell = (iOld + pPg->aiOvfl[i]) - iNew; 6627 if( iCell>=0 && iCell<nNew ){ 6628 pCellptr = &pPg->aCellIdx[iCell * 2]; 6629 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); 6630 nCell++; 6631 if( pageInsertArray( 6632 pPg, pBegin, &pData, pCellptr, 6633 iCell+iNew, 1, pCArray 6634 ) ) goto editpage_fail; 6635 } 6636 } 6637 6638 /* Append cells to the end of the page */ 6639 pCellptr = &pPg->aCellIdx[nCell*2]; 6640 if( pageInsertArray( 6641 pPg, pBegin, &pData, pCellptr, 6642 iNew+nCell, nNew-nCell, pCArray 6643 ) ) goto editpage_fail; 6644 6645 pPg->nCell = nNew; 6646 pPg->nOverflow = 0; 6647 6648 put2byte(&aData[hdr+3], pPg->nCell); 6649 put2byte(&aData[hdr+5], pData - aData); 6650 6651 #ifdef SQLITE_DEBUG 6652 for(i=0; i<nNew && !CORRUPT_DB; i++){ 6653 u8 *pCell = pCArray->apCell[i+iNew]; 6654 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); 6655 if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){ 6656 pCell = &pTmp[pCell - aData]; 6657 } 6658 assert( 0==memcmp(pCell, &aData[iOff], 6659 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); 6660 } 6661 #endif 6662 6663 return SQLITE_OK; 6664 editpage_fail: 6665 /* Unable to edit this page. Rebuild it from scratch instead. */ 6666 populateCellCache(pCArray, iNew, nNew); 6667 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]); 6668 } 6669 6670 /* 6671 ** The following parameters determine how many adjacent pages get involved 6672 ** in a balancing operation. NN is the number of neighbors on either side 6673 ** of the page that participate in the balancing operation. NB is the 6674 ** total number of pages that participate, including the target page and 6675 ** NN neighbors on either side. 6676 ** 6677 ** The minimum value of NN is 1 (of course). Increasing NN above 1 6678 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance 6679 ** in exchange for a larger degradation in INSERT and UPDATE performance. 6680 ** The value of NN appears to give the best results overall. 6681 */ 6682 #define NN 1 /* Number of neighbors on either side of pPage */ 6683 #define NB (NN*2+1) /* Total pages involved in the balance */ 6684 6685 6686 #ifndef SQLITE_OMIT_QUICKBALANCE 6687 /* 6688 ** This version of balance() handles the common special case where 6689 ** a new entry is being inserted on the extreme right-end of the 6690 ** tree, in other words, when the new entry will become the largest 6691 ** entry in the tree. 6692 ** 6693 ** Instead of trying to balance the 3 right-most leaf pages, just add 6694 ** a new page to the right-hand side and put the one new entry in 6695 ** that page. This leaves the right side of the tree somewhat 6696 ** unbalanced. But odds are that we will be inserting new entries 6697 ** at the end soon afterwards so the nearly empty page will quickly 6698 ** fill up. On average. 6699 ** 6700 ** pPage is the leaf page which is the right-most page in the tree. 6701 ** pParent is its parent. pPage must have a single overflow entry 6702 ** which is also the right-most entry on the page. 6703 ** 6704 ** The pSpace buffer is used to store a temporary copy of the divider 6705 ** cell that will be inserted into pParent. Such a cell consists of a 4 6706 ** byte page number followed by a variable length integer. In other 6707 ** words, at most 13 bytes. Hence the pSpace buffer must be at 6708 ** least 13 bytes in size. 6709 */ 6710 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ 6711 BtShared *const pBt = pPage->pBt; /* B-Tree Database */ 6712 MemPage *pNew; /* Newly allocated page */ 6713 int rc; /* Return Code */ 6714 Pgno pgnoNew; /* Page number of pNew */ 6715 6716 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6717 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 6718 assert( pPage->nOverflow==1 ); 6719 6720 /* This error condition is now caught prior to reaching this function */ 6721 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT; 6722 6723 /* Allocate a new page. This page will become the right-sibling of 6724 ** pPage. Make the parent page writable, so that the new divider cell 6725 ** may be inserted. If both these operations are successful, proceed. 6726 */ 6727 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); 6728 6729 if( rc==SQLITE_OK ){ 6730 6731 u8 *pOut = &pSpace[4]; 6732 u8 *pCell = pPage->apOvfl[0]; 6733 u16 szCell = pPage->xCellSize(pPage, pCell); 6734 u8 *pStop; 6735 6736 assert( sqlite3PagerIswriteable(pNew->pDbPage) ); 6737 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); 6738 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); 6739 rc = rebuildPage(pNew, 1, &pCell, &szCell); 6740 if( NEVER(rc) ) return rc; 6741 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; 6742 6743 /* If this is an auto-vacuum database, update the pointer map 6744 ** with entries for the new page, and any pointer from the 6745 ** cell on the page to an overflow page. If either of these 6746 ** operations fails, the return code is set, but the contents 6747 ** of the parent page are still manipulated by thh code below. 6748 ** That is Ok, at this point the parent page is guaranteed to 6749 ** be marked as dirty. Returning an error code will cause a 6750 ** rollback, undoing any changes made to the parent page. 6751 */ 6752 if( ISAUTOVACUUM ){ 6753 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); 6754 if( szCell>pNew->minLocal ){ 6755 ptrmapPutOvflPtr(pNew, pCell, &rc); 6756 } 6757 } 6758 6759 /* Create a divider cell to insert into pParent. The divider cell 6760 ** consists of a 4-byte page number (the page number of pPage) and 6761 ** a variable length key value (which must be the same value as the 6762 ** largest key on pPage). 6763 ** 6764 ** To find the largest key value on pPage, first find the right-most 6765 ** cell on pPage. The first two fields of this cell are the 6766 ** record-length (a variable length integer at most 32-bits in size) 6767 ** and the key value (a variable length integer, may have any value). 6768 ** The first of the while(...) loops below skips over the record-length 6769 ** field. The second while(...) loop copies the key value from the 6770 ** cell on pPage into the pSpace buffer. 6771 */ 6772 pCell = findCell(pPage, pPage->nCell-1); 6773 pStop = &pCell[9]; 6774 while( (*(pCell++)&0x80) && pCell<pStop ); 6775 pStop = &pCell[9]; 6776 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop ); 6777 6778 /* Insert the new divider cell into pParent. */ 6779 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace), 6780 0, pPage->pgno, &rc); 6781 6782 /* Set the right-child pointer of pParent to point to the new page. */ 6783 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); 6784 6785 /* Release the reference to the new page. */ 6786 releasePage(pNew); 6787 } 6788 6789 return rc; 6790 } 6791 #endif /* SQLITE_OMIT_QUICKBALANCE */ 6792 6793 #if 0 6794 /* 6795 ** This function does not contribute anything to the operation of SQLite. 6796 ** it is sometimes activated temporarily while debugging code responsible 6797 ** for setting pointer-map entries. 6798 */ 6799 static int ptrmapCheckPages(MemPage **apPage, int nPage){ 6800 int i, j; 6801 for(i=0; i<nPage; i++){ 6802 Pgno n; 6803 u8 e; 6804 MemPage *pPage = apPage[i]; 6805 BtShared *pBt = pPage->pBt; 6806 assert( pPage->isInit ); 6807 6808 for(j=0; j<pPage->nCell; j++){ 6809 CellInfo info; 6810 u8 *z; 6811 6812 z = findCell(pPage, j); 6813 pPage->xParseCell(pPage, z, &info); 6814 if( info.iOverflow ){ 6815 Pgno ovfl = get4byte(&z[info.iOverflow]); 6816 ptrmapGet(pBt, ovfl, &e, &n); 6817 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); 6818 } 6819 if( !pPage->leaf ){ 6820 Pgno child = get4byte(z); 6821 ptrmapGet(pBt, child, &e, &n); 6822 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 6823 } 6824 } 6825 if( !pPage->leaf ){ 6826 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); 6827 ptrmapGet(pBt, child, &e, &n); 6828 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 6829 } 6830 } 6831 return 1; 6832 } 6833 #endif 6834 6835 /* 6836 ** This function is used to copy the contents of the b-tree node stored 6837 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then 6838 ** the pointer-map entries for each child page are updated so that the 6839 ** parent page stored in the pointer map is page pTo. If pFrom contained 6840 ** any cells with overflow page pointers, then the corresponding pointer 6841 ** map entries are also updated so that the parent page is page pTo. 6842 ** 6843 ** If pFrom is currently carrying any overflow cells (entries in the 6844 ** MemPage.apOvfl[] array), they are not copied to pTo. 6845 ** 6846 ** Before returning, page pTo is reinitialized using btreeInitPage(). 6847 ** 6848 ** The performance of this function is not critical. It is only used by 6849 ** the balance_shallower() and balance_deeper() procedures, neither of 6850 ** which are called often under normal circumstances. 6851 */ 6852 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ 6853 if( (*pRC)==SQLITE_OK ){ 6854 BtShared * const pBt = pFrom->pBt; 6855 u8 * const aFrom = pFrom->aData; 6856 u8 * const aTo = pTo->aData; 6857 int const iFromHdr = pFrom->hdrOffset; 6858 int const iToHdr = ((pTo->pgno==1) ? 100 : 0); 6859 int rc; 6860 int iData; 6861 6862 6863 assert( pFrom->isInit ); 6864 assert( pFrom->nFree>=iToHdr ); 6865 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); 6866 6867 /* Copy the b-tree node content from page pFrom to page pTo. */ 6868 iData = get2byte(&aFrom[iFromHdr+5]); 6869 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); 6870 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); 6871 6872 /* Reinitialize page pTo so that the contents of the MemPage structure 6873 ** match the new data. The initialization of pTo can actually fail under 6874 ** fairly obscure circumstances, even though it is a copy of initialized 6875 ** page pFrom. 6876 */ 6877 pTo->isInit = 0; 6878 rc = btreeInitPage(pTo); 6879 if( rc!=SQLITE_OK ){ 6880 *pRC = rc; 6881 return; 6882 } 6883 6884 /* If this is an auto-vacuum database, update the pointer-map entries 6885 ** for any b-tree or overflow pages that pTo now contains the pointers to. 6886 */ 6887 if( ISAUTOVACUUM ){ 6888 *pRC = setChildPtrmaps(pTo); 6889 } 6890 } 6891 } 6892 6893 /* 6894 ** This routine redistributes cells on the iParentIdx'th child of pParent 6895 ** (hereafter "the page") and up to 2 siblings so that all pages have about the 6896 ** same amount of free space. Usually a single sibling on either side of the 6897 ** page are used in the balancing, though both siblings might come from one 6898 ** side if the page is the first or last child of its parent. If the page 6899 ** has fewer than 2 siblings (something which can only happen if the page 6900 ** is a root page or a child of a root page) then all available siblings 6901 ** participate in the balancing. 6902 ** 6903 ** The number of siblings of the page might be increased or decreased by 6904 ** one or two in an effort to keep pages nearly full but not over full. 6905 ** 6906 ** Note that when this routine is called, some of the cells on the page 6907 ** might not actually be stored in MemPage.aData[]. This can happen 6908 ** if the page is overfull. This routine ensures that all cells allocated 6909 ** to the page and its siblings fit into MemPage.aData[] before returning. 6910 ** 6911 ** In the course of balancing the page and its siblings, cells may be 6912 ** inserted into or removed from the parent page (pParent). Doing so 6913 ** may cause the parent page to become overfull or underfull. If this 6914 ** happens, it is the responsibility of the caller to invoke the correct 6915 ** balancing routine to fix this problem (see the balance() routine). 6916 ** 6917 ** If this routine fails for any reason, it might leave the database 6918 ** in a corrupted state. So if this routine fails, the database should 6919 ** be rolled back. 6920 ** 6921 ** The third argument to this function, aOvflSpace, is a pointer to a 6922 ** buffer big enough to hold one page. If while inserting cells into the parent 6923 ** page (pParent) the parent page becomes overfull, this buffer is 6924 ** used to store the parent's overflow cells. Because this function inserts 6925 ** a maximum of four divider cells into the parent page, and the maximum 6926 ** size of a cell stored within an internal node is always less than 1/4 6927 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large 6928 ** enough for all overflow cells. 6929 ** 6930 ** If aOvflSpace is set to a null pointer, this function returns 6931 ** SQLITE_NOMEM. 6932 */ 6933 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) 6934 #pragma optimize("", off) 6935 #endif 6936 static int balance_nonroot( 6937 MemPage *pParent, /* Parent page of siblings being balanced */ 6938 int iParentIdx, /* Index of "the page" in pParent */ 6939 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ 6940 int isRoot, /* True if pParent is a root-page */ 6941 int bBulk /* True if this call is part of a bulk load */ 6942 ){ 6943 BtShared *pBt; /* The whole database */ 6944 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ 6945 int nNew = 0; /* Number of pages in apNew[] */ 6946 int nOld; /* Number of pages in apOld[] */ 6947 int i, j, k; /* Loop counters */ 6948 int nxDiv; /* Next divider slot in pParent->aCell[] */ 6949 int rc = SQLITE_OK; /* The return code */ 6950 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ 6951 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ 6952 int usableSpace; /* Bytes in pPage beyond the header */ 6953 int pageFlags; /* Value of pPage->aData[0] */ 6954 int iSpace1 = 0; /* First unused byte of aSpace1[] */ 6955 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ 6956 int szScratch; /* Size of scratch memory requested */ 6957 MemPage *apOld[NB]; /* pPage and up to two siblings */ 6958 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ 6959 u8 *pRight; /* Location in parent of right-sibling pointer */ 6960 u8 *apDiv[NB-1]; /* Divider cells in pParent */ 6961 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ 6962 int cntOld[NB+2]; /* Old index in b.apCell[] */ 6963 int szNew[NB+2]; /* Combined size of cells placed on i-th page */ 6964 u8 *aSpace1; /* Space for copies of dividers cells */ 6965 Pgno pgno; /* Temp var to store a page number in */ 6966 u8 abDone[NB+2]; /* True after i'th new page is populated */ 6967 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ 6968 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ 6969 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ 6970 CellArray b; /* Parsed information on cells being balanced */ 6971 6972 memset(abDone, 0, sizeof(abDone)); 6973 b.nCell = 0; 6974 b.apCell = 0; 6975 pBt = pParent->pBt; 6976 assert( sqlite3_mutex_held(pBt->mutex) ); 6977 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 6978 6979 #if 0 6980 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); 6981 #endif 6982 6983 /* At this point pParent may have at most one overflow cell. And if 6984 ** this overflow cell is present, it must be the cell with 6985 ** index iParentIdx. This scenario comes about when this function 6986 ** is called (indirectly) from sqlite3BtreeDelete(). 6987 */ 6988 assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); 6989 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); 6990 6991 if( !aOvflSpace ){ 6992 return SQLITE_NOMEM; 6993 } 6994 6995 /* Find the sibling pages to balance. Also locate the cells in pParent 6996 ** that divide the siblings. An attempt is made to find NN siblings on 6997 ** either side of pPage. More siblings are taken from one side, however, 6998 ** if there are fewer than NN siblings on the other side. If pParent 6999 ** has NB or fewer children then all children of pParent are taken. 7000 ** 7001 ** This loop also drops the divider cells from the parent page. This 7002 ** way, the remainder of the function does not have to deal with any 7003 ** overflow cells in the parent page, since if any existed they will 7004 ** have already been removed. 7005 */ 7006 i = pParent->nOverflow + pParent->nCell; 7007 if( i<2 ){ 7008 nxDiv = 0; 7009 }else{ 7010 assert( bBulk==0 || bBulk==1 ); 7011 if( iParentIdx==0 ){ 7012 nxDiv = 0; 7013 }else if( iParentIdx==i ){ 7014 nxDiv = i-2+bBulk; 7015 }else{ 7016 nxDiv = iParentIdx-1; 7017 } 7018 i = 2-bBulk; 7019 } 7020 nOld = i+1; 7021 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ 7022 pRight = &pParent->aData[pParent->hdrOffset+8]; 7023 }else{ 7024 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); 7025 } 7026 pgno = get4byte(pRight); 7027 while( 1 ){ 7028 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); 7029 if( rc ){ 7030 memset(apOld, 0, (i+1)*sizeof(MemPage*)); 7031 goto balance_cleanup; 7032 } 7033 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; 7034 if( (i--)==0 ) break; 7035 7036 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ 7037 apDiv[i] = pParent->apOvfl[0]; 7038 pgno = get4byte(apDiv[i]); 7039 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7040 pParent->nOverflow = 0; 7041 }else{ 7042 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); 7043 pgno = get4byte(apDiv[i]); 7044 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7045 7046 /* Drop the cell from the parent page. apDiv[i] still points to 7047 ** the cell within the parent, even though it has been dropped. 7048 ** This is safe because dropping a cell only overwrites the first 7049 ** four bytes of it, and this function does not need the first 7050 ** four bytes of the divider cell. So the pointer is safe to use 7051 ** later on. 7052 ** 7053 ** But not if we are in secure-delete mode. In secure-delete mode, 7054 ** the dropCell() routine will overwrite the entire cell with zeroes. 7055 ** In this case, temporarily copy the cell into the aOvflSpace[] 7056 ** buffer. It will be copied out again as soon as the aSpace[] buffer 7057 ** is allocated. */ 7058 if( pBt->btsFlags & BTS_SECURE_DELETE ){ 7059 int iOff; 7060 7061 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); 7062 if( (iOff+szNew[i])>(int)pBt->usableSize ){ 7063 rc = SQLITE_CORRUPT_BKPT; 7064 memset(apOld, 0, (i+1)*sizeof(MemPage*)); 7065 goto balance_cleanup; 7066 }else{ 7067 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); 7068 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; 7069 } 7070 } 7071 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); 7072 } 7073 } 7074 7075 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte 7076 ** alignment */ 7077 nMaxCells = (nMaxCells + 3)&~3; 7078 7079 /* 7080 ** Allocate space for memory structures 7081 */ 7082 szScratch = 7083 nMaxCells*sizeof(u8*) /* b.apCell */ 7084 + nMaxCells*sizeof(u16) /* b.szCell */ 7085 + pBt->pageSize; /* aSpace1 */ 7086 7087 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer 7088 ** that is more than 6 times the database page size. */ 7089 assert( szScratch<=6*(int)pBt->pageSize ); 7090 b.apCell = sqlite3ScratchMalloc( szScratch ); 7091 if( b.apCell==0 ){ 7092 rc = SQLITE_NOMEM; 7093 goto balance_cleanup; 7094 } 7095 b.szCell = (u16*)&b.apCell[nMaxCells]; 7096 aSpace1 = (u8*)&b.szCell[nMaxCells]; 7097 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); 7098 7099 /* 7100 ** Load pointers to all cells on sibling pages and the divider cells 7101 ** into the local b.apCell[] array. Make copies of the divider cells 7102 ** into space obtained from aSpace1[]. The divider cells have already 7103 ** been removed from pParent. 7104 ** 7105 ** If the siblings are on leaf pages, then the child pointers of the 7106 ** divider cells are stripped from the cells before they are copied 7107 ** into aSpace1[]. In this way, all cells in b.apCell[] are without 7108 ** child pointers. If siblings are not leaves, then all cell in 7109 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] 7110 ** are alike. 7111 ** 7112 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. 7113 ** leafData: 1 if pPage holds key+data and pParent holds only keys. 7114 */ 7115 b.pRef = apOld[0]; 7116 leafCorrection = b.pRef->leaf*4; 7117 leafData = b.pRef->intKeyLeaf; 7118 for(i=0; i<nOld; i++){ 7119 MemPage *pOld = apOld[i]; 7120 int limit = pOld->nCell; 7121 u8 *aData = pOld->aData; 7122 u16 maskPage = pOld->maskPage; 7123 u8 *piCell = aData + pOld->cellOffset; 7124 u8 *piEnd; 7125 7126 /* Verify that all sibling pages are of the same "type" (table-leaf, 7127 ** table-interior, index-leaf, or index-interior). 7128 */ 7129 if( pOld->aData[0]!=apOld[0]->aData[0] ){ 7130 rc = SQLITE_CORRUPT_BKPT; 7131 goto balance_cleanup; 7132 } 7133 7134 /* Load b.apCell[] with pointers to all cells in pOld. If pOld 7135 ** constains overflow cells, include them in the b.apCell[] array 7136 ** in the correct spot. 7137 ** 7138 ** Note that when there are multiple overflow cells, it is always the 7139 ** case that they are sequential and adjacent. This invariant arises 7140 ** because multiple overflows can only occurs when inserting divider 7141 ** cells into a parent on a prior balance, and divider cells are always 7142 ** adjacent and are inserted in order. There is an assert() tagged 7143 ** with "NOTE 1" in the overflow cell insertion loop to prove this 7144 ** invariant. 7145 ** 7146 ** This must be done in advance. Once the balance starts, the cell 7147 ** offset section of the btree page will be overwritten and we will no 7148 ** long be able to find the cells if a pointer to each cell is not saved 7149 ** first. 7150 */ 7151 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit); 7152 if( pOld->nOverflow>0 ){ 7153 memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow); 7154 limit = pOld->aiOvfl[0]; 7155 for(j=0; j<limit; j++){ 7156 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7157 piCell += 2; 7158 b.nCell++; 7159 } 7160 for(k=0; k<pOld->nOverflow; k++){ 7161 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ 7162 b.apCell[b.nCell] = pOld->apOvfl[k]; 7163 b.nCell++; 7164 } 7165 } 7166 piEnd = aData + pOld->cellOffset + 2*pOld->nCell; 7167 while( piCell<piEnd ){ 7168 assert( b.nCell<nMaxCells ); 7169 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7170 piCell += 2; 7171 b.nCell++; 7172 } 7173 7174 cntOld[i] = b.nCell; 7175 if( i<nOld-1 && !leafData){ 7176 u16 sz = (u16)szNew[i]; 7177 u8 *pTemp; 7178 assert( b.nCell<nMaxCells ); 7179 b.szCell[b.nCell] = sz; 7180 pTemp = &aSpace1[iSpace1]; 7181 iSpace1 += sz; 7182 assert( sz<=pBt->maxLocal+23 ); 7183 assert( iSpace1 <= (int)pBt->pageSize ); 7184 memcpy(pTemp, apDiv[i], sz); 7185 b.apCell[b.nCell] = pTemp+leafCorrection; 7186 assert( leafCorrection==0 || leafCorrection==4 ); 7187 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; 7188 if( !pOld->leaf ){ 7189 assert( leafCorrection==0 ); 7190 assert( pOld->hdrOffset==0 ); 7191 /* The right pointer of the child page pOld becomes the left 7192 ** pointer of the divider cell */ 7193 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); 7194 }else{ 7195 assert( leafCorrection==4 ); 7196 while( b.szCell[b.nCell]<4 ){ 7197 /* Do not allow any cells smaller than 4 bytes. If a smaller cell 7198 ** does exist, pad it with 0x00 bytes. */ 7199 assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); 7200 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); 7201 aSpace1[iSpace1++] = 0x00; 7202 b.szCell[b.nCell]++; 7203 } 7204 } 7205 b.nCell++; 7206 } 7207 } 7208 7209 /* 7210 ** Figure out the number of pages needed to hold all b.nCell cells. 7211 ** Store this number in "k". Also compute szNew[] which is the total 7212 ** size of all cells on the i-th page and cntNew[] which is the index 7213 ** in b.apCell[] of the cell that divides page i from page i+1. 7214 ** cntNew[k] should equal b.nCell. 7215 ** 7216 ** Values computed by this block: 7217 ** 7218 ** k: The total number of sibling pages 7219 ** szNew[i]: Spaced used on the i-th sibling page. 7220 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to 7221 ** the right of the i-th sibling page. 7222 ** usableSpace: Number of bytes of space available on each sibling. 7223 ** 7224 */ 7225 usableSpace = pBt->usableSize - 12 + leafCorrection; 7226 for(i=0; i<nOld; i++){ 7227 MemPage *p = apOld[i]; 7228 szNew[i] = usableSpace - p->nFree; 7229 if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } 7230 for(j=0; j<p->nOverflow; j++){ 7231 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); 7232 } 7233 cntNew[i] = cntOld[i]; 7234 } 7235 k = nOld; 7236 for(i=0; i<k; i++){ 7237 int sz; 7238 while( szNew[i]>usableSpace ){ 7239 if( i+1>=k ){ 7240 k = i+2; 7241 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } 7242 szNew[k-1] = 0; 7243 cntNew[k-1] = b.nCell; 7244 } 7245 sz = 2 + cachedCellSize(&b, cntNew[i]-1); 7246 szNew[i] -= sz; 7247 if( !leafData ){ 7248 if( cntNew[i]<b.nCell ){ 7249 sz = 2 + cachedCellSize(&b, cntNew[i]); 7250 }else{ 7251 sz = 0; 7252 } 7253 } 7254 szNew[i+1] += sz; 7255 cntNew[i]--; 7256 } 7257 while( cntNew[i]<b.nCell ){ 7258 sz = 2 + cachedCellSize(&b, cntNew[i]); 7259 if( szNew[i]+sz>usableSpace ) break; 7260 szNew[i] += sz; 7261 cntNew[i]++; 7262 if( !leafData ){ 7263 if( cntNew[i]<b.nCell ){ 7264 sz = 2 + cachedCellSize(&b, cntNew[i]); 7265 }else{ 7266 sz = 0; 7267 } 7268 } 7269 szNew[i+1] -= sz; 7270 } 7271 if( cntNew[i]>=b.nCell ){ 7272 k = i+1; 7273 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ 7274 rc = SQLITE_CORRUPT_BKPT; 7275 goto balance_cleanup; 7276 } 7277 } 7278 7279 /* 7280 ** The packing computed by the previous block is biased toward the siblings 7281 ** on the left side (siblings with smaller keys). The left siblings are 7282 ** always nearly full, while the right-most sibling might be nearly empty. 7283 ** The next block of code attempts to adjust the packing of siblings to 7284 ** get a better balance. 7285 ** 7286 ** This adjustment is more than an optimization. The packing above might 7287 ** be so out of balance as to be illegal. For example, the right-most 7288 ** sibling might be completely empty. This adjustment is not optional. 7289 */ 7290 for(i=k-1; i>0; i--){ 7291 int szRight = szNew[i]; /* Size of sibling on the right */ 7292 int szLeft = szNew[i-1]; /* Size of sibling on the left */ 7293 int r; /* Index of right-most cell in left sibling */ 7294 int d; /* Index of first cell to the left of right sibling */ 7295 7296 r = cntNew[i-1] - 1; 7297 d = r + 1 - leafData; 7298 (void)cachedCellSize(&b, d); 7299 do{ 7300 assert( d<nMaxCells ); 7301 assert( r<nMaxCells ); 7302 (void)cachedCellSize(&b, r); 7303 if( szRight!=0 7304 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){ 7305 break; 7306 } 7307 szRight += b.szCell[d] + 2; 7308 szLeft -= b.szCell[r] + 2; 7309 cntNew[i-1] = r; 7310 r--; 7311 d--; 7312 }while( r>=0 ); 7313 szNew[i] = szRight; 7314 szNew[i-1] = szLeft; 7315 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ 7316 rc = SQLITE_CORRUPT_BKPT; 7317 goto balance_cleanup; 7318 } 7319 } 7320 7321 /* Sanity check: For a non-corrupt database file one of the follwing 7322 ** must be true: 7323 ** (1) We found one or more cells (cntNew[0])>0), or 7324 ** (2) pPage is a virtual root page. A virtual root page is when 7325 ** the real root page is page 1 and we are the only child of 7326 ** that page. 7327 */ 7328 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); 7329 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", 7330 apOld[0]->pgno, apOld[0]->nCell, 7331 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, 7332 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 7333 )); 7334 7335 /* 7336 ** Allocate k new pages. Reuse old pages where possible. 7337 */ 7338 pageFlags = apOld[0]->aData[0]; 7339 for(i=0; i<k; i++){ 7340 MemPage *pNew; 7341 if( i<nOld ){ 7342 pNew = apNew[i] = apOld[i]; 7343 apOld[i] = 0; 7344 rc = sqlite3PagerWrite(pNew->pDbPage); 7345 nNew++; 7346 if( rc ) goto balance_cleanup; 7347 }else{ 7348 assert( i>0 ); 7349 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); 7350 if( rc ) goto balance_cleanup; 7351 zeroPage(pNew, pageFlags); 7352 apNew[i] = pNew; 7353 nNew++; 7354 cntOld[i] = b.nCell; 7355 7356 /* Set the pointer-map entry for the new sibling page. */ 7357 if( ISAUTOVACUUM ){ 7358 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); 7359 if( rc!=SQLITE_OK ){ 7360 goto balance_cleanup; 7361 } 7362 } 7363 } 7364 } 7365 7366 /* 7367 ** Reassign page numbers so that the new pages are in ascending order. 7368 ** This helps to keep entries in the disk file in order so that a scan 7369 ** of the table is closer to a linear scan through the file. That in turn 7370 ** helps the operating system to deliver pages from the disk more rapidly. 7371 ** 7372 ** An O(n^2) insertion sort algorithm is used, but since n is never more 7373 ** than (NB+2) (a small constant), that should not be a problem. 7374 ** 7375 ** When NB==3, this one optimization makes the database about 25% faster 7376 ** for large insertions and deletions. 7377 */ 7378 for(i=0; i<nNew; i++){ 7379 aPgOrder[i] = aPgno[i] = apNew[i]->pgno; 7380 aPgFlags[i] = apNew[i]->pDbPage->flags; 7381 for(j=0; j<i; j++){ 7382 if( aPgno[j]==aPgno[i] ){ 7383 /* This branch is taken if the set of sibling pages somehow contains 7384 ** duplicate entries. This can happen if the database is corrupt. 7385 ** It would be simpler to detect this as part of the loop below, but 7386 ** we do the detection here in order to avoid populating the pager 7387 ** cache with two separate objects associated with the same 7388 ** page number. */ 7389 assert( CORRUPT_DB ); 7390 rc = SQLITE_CORRUPT_BKPT; 7391 goto balance_cleanup; 7392 } 7393 } 7394 } 7395 for(i=0; i<nNew; i++){ 7396 int iBest = 0; /* aPgno[] index of page number to use */ 7397 for(j=1; j<nNew; j++){ 7398 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j; 7399 } 7400 pgno = aPgOrder[iBest]; 7401 aPgOrder[iBest] = 0xffffffff; 7402 if( iBest!=i ){ 7403 if( iBest>i ){ 7404 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); 7405 } 7406 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); 7407 apNew[i]->pgno = pgno; 7408 } 7409 } 7410 7411 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " 7412 "%d(%d nc=%d) %d(%d nc=%d)\n", 7413 apNew[0]->pgno, szNew[0], cntNew[0], 7414 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, 7415 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, 7416 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, 7417 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, 7418 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, 7419 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, 7420 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, 7421 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 7422 )); 7423 7424 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7425 put4byte(pRight, apNew[nNew-1]->pgno); 7426 7427 /* If the sibling pages are not leaves, ensure that the right-child pointer 7428 ** of the right-most new sibling page is set to the value that was 7429 ** originally in the same field of the right-most old sibling page. */ 7430 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ 7431 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; 7432 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); 7433 } 7434 7435 /* Make any required updates to pointer map entries associated with 7436 ** cells stored on sibling pages following the balance operation. Pointer 7437 ** map entries associated with divider cells are set by the insertCell() 7438 ** routine. The associated pointer map entries are: 7439 ** 7440 ** a) if the cell contains a reference to an overflow chain, the 7441 ** entry associated with the first page in the overflow chain, and 7442 ** 7443 ** b) if the sibling pages are not leaves, the child page associated 7444 ** with the cell. 7445 ** 7446 ** If the sibling pages are not leaves, then the pointer map entry 7447 ** associated with the right-child of each sibling may also need to be 7448 ** updated. This happens below, after the sibling pages have been 7449 ** populated, not here. 7450 */ 7451 if( ISAUTOVACUUM ){ 7452 MemPage *pNew = apNew[0]; 7453 u8 *aOld = pNew->aData; 7454 int cntOldNext = pNew->nCell + pNew->nOverflow; 7455 int usableSize = pBt->usableSize; 7456 int iNew = 0; 7457 int iOld = 0; 7458 7459 for(i=0; i<b.nCell; i++){ 7460 u8 *pCell = b.apCell[i]; 7461 if( i==cntOldNext ){ 7462 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld]; 7463 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; 7464 aOld = pOld->aData; 7465 } 7466 if( i==cntNew[iNew] ){ 7467 pNew = apNew[++iNew]; 7468 if( !leafData ) continue; 7469 } 7470 7471 /* Cell pCell is destined for new sibling page pNew. Originally, it 7472 ** was either part of sibling page iOld (possibly an overflow cell), 7473 ** or else the divider cell to the left of sibling page iOld. So, 7474 ** if sibling page iOld had the same page number as pNew, and if 7475 ** pCell really was a part of sibling page iOld (not a divider or 7476 ** overflow cell), we can skip updating the pointer map entries. */ 7477 if( iOld>=nNew 7478 || pNew->pgno!=aPgno[iOld] 7479 || pCell<aOld 7480 || pCell>=&aOld[usableSize] 7481 ){ 7482 if( !leafCorrection ){ 7483 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); 7484 } 7485 if( cachedCellSize(&b,i)>pNew->minLocal ){ 7486 ptrmapPutOvflPtr(pNew, pCell, &rc); 7487 } 7488 if( rc ) goto balance_cleanup; 7489 } 7490 } 7491 } 7492 7493 /* Insert new divider cells into pParent. */ 7494 for(i=0; i<nNew-1; i++){ 7495 u8 *pCell; 7496 u8 *pTemp; 7497 int sz; 7498 MemPage *pNew = apNew[i]; 7499 j = cntNew[i]; 7500 7501 assert( j<nMaxCells ); 7502 assert( b.apCell[j]!=0 ); 7503 pCell = b.apCell[j]; 7504 sz = b.szCell[j] + leafCorrection; 7505 pTemp = &aOvflSpace[iOvflSpace]; 7506 if( !pNew->leaf ){ 7507 memcpy(&pNew->aData[8], pCell, 4); 7508 }else if( leafData ){ 7509 /* If the tree is a leaf-data tree, and the siblings are leaves, 7510 ** then there is no divider cell in b.apCell[]. Instead, the divider 7511 ** cell consists of the integer key for the right-most cell of 7512 ** the sibling-page assembled above only. 7513 */ 7514 CellInfo info; 7515 j--; 7516 pNew->xParseCell(pNew, b.apCell[j], &info); 7517 pCell = pTemp; 7518 sz = 4 + putVarint(&pCell[4], info.nKey); 7519 pTemp = 0; 7520 }else{ 7521 pCell -= 4; 7522 /* Obscure case for non-leaf-data trees: If the cell at pCell was 7523 ** previously stored on a leaf node, and its reported size was 4 7524 ** bytes, then it may actually be smaller than this 7525 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of 7526 ** any cell). But it is important to pass the correct size to 7527 ** insertCell(), so reparse the cell now. 7528 ** 7529 ** Note that this can never happen in an SQLite data file, as all 7530 ** cells are at least 4 bytes. It only happens in b-trees used 7531 ** to evaluate "IN (SELECT ...)" and similar clauses. 7532 */ 7533 if( b.szCell[j]==4 ){ 7534 assert(leafCorrection==4); 7535 sz = pParent->xCellSize(pParent, pCell); 7536 } 7537 } 7538 iOvflSpace += sz; 7539 assert( sz<=pBt->maxLocal+23 ); 7540 assert( iOvflSpace <= (int)pBt->pageSize ); 7541 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); 7542 if( rc!=SQLITE_OK ) goto balance_cleanup; 7543 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7544 } 7545 7546 /* Now update the actual sibling pages. The order in which they are updated 7547 ** is important, as this code needs to avoid disrupting any page from which 7548 ** cells may still to be read. In practice, this means: 7549 ** 7550 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) 7551 ** then it is not safe to update page apNew[iPg] until after 7552 ** the left-hand sibling apNew[iPg-1] has been updated. 7553 ** 7554 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) 7555 ** then it is not safe to update page apNew[iPg] until after 7556 ** the right-hand sibling apNew[iPg+1] has been updated. 7557 ** 7558 ** If neither of the above apply, the page is safe to update. 7559 ** 7560 ** The iPg value in the following loop starts at nNew-1 goes down 7561 ** to 0, then back up to nNew-1 again, thus making two passes over 7562 ** the pages. On the initial downward pass, only condition (1) above 7563 ** needs to be tested because (2) will always be true from the previous 7564 ** step. On the upward pass, both conditions are always true, so the 7565 ** upwards pass simply processes pages that were missed on the downward 7566 ** pass. 7567 */ 7568 for(i=1-nNew; i<nNew; i++){ 7569 int iPg = i<0 ? -i : i; 7570 assert( iPg>=0 && iPg<nNew ); 7571 if( abDone[iPg] ) continue; /* Skip pages already processed */ 7572 if( i>=0 /* On the upwards pass, or... */ 7573 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ 7574 ){ 7575 int iNew; 7576 int iOld; 7577 int nNewCell; 7578 7579 /* Verify condition (1): If cells are moving left, update iPg 7580 ** only after iPg-1 has already been updated. */ 7581 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); 7582 7583 /* Verify condition (2): If cells are moving right, update iPg 7584 ** only after iPg+1 has already been updated. */ 7585 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); 7586 7587 if( iPg==0 ){ 7588 iNew = iOld = 0; 7589 nNewCell = cntNew[0]; 7590 }else{ 7591 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell; 7592 iNew = cntNew[iPg-1] + !leafData; 7593 nNewCell = cntNew[iPg] - iNew; 7594 } 7595 7596 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b); 7597 if( rc ) goto balance_cleanup; 7598 abDone[iPg]++; 7599 apNew[iPg]->nFree = usableSpace-szNew[iPg]; 7600 assert( apNew[iPg]->nOverflow==0 ); 7601 assert( apNew[iPg]->nCell==nNewCell ); 7602 } 7603 } 7604 7605 /* All pages have been processed exactly once */ 7606 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); 7607 7608 assert( nOld>0 ); 7609 assert( nNew>0 ); 7610 7611 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ 7612 /* The root page of the b-tree now contains no cells. The only sibling 7613 ** page is the right-child of the parent. Copy the contents of the 7614 ** child page into the parent, decreasing the overall height of the 7615 ** b-tree structure by one. This is described as the "balance-shallower" 7616 ** sub-algorithm in some documentation. 7617 ** 7618 ** If this is an auto-vacuum database, the call to copyNodeContent() 7619 ** sets all pointer-map entries corresponding to database image pages 7620 ** for which the pointer is stored within the content being copied. 7621 ** 7622 ** It is critical that the child page be defragmented before being 7623 ** copied into the parent, because if the parent is page 1 then it will 7624 ** by smaller than the child due to the database header, and so all the 7625 ** free space needs to be up front. 7626 */ 7627 assert( nNew==1 || CORRUPT_DB ); 7628 rc = defragmentPage(apNew[0]); 7629 testcase( rc!=SQLITE_OK ); 7630 assert( apNew[0]->nFree == 7631 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 7632 || rc!=SQLITE_OK 7633 ); 7634 copyNodeContent(apNew[0], pParent, &rc); 7635 freePage(apNew[0], &rc); 7636 }else if( ISAUTOVACUUM && !leafCorrection ){ 7637 /* Fix the pointer map entries associated with the right-child of each 7638 ** sibling page. All other pointer map entries have already been taken 7639 ** care of. */ 7640 for(i=0; i<nNew; i++){ 7641 u32 key = get4byte(&apNew[i]->aData[8]); 7642 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); 7643 } 7644 } 7645 7646 assert( pParent->isInit ); 7647 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", 7648 nOld, nNew, b.nCell)); 7649 7650 /* Free any old pages that were not reused as new pages. 7651 */ 7652 for(i=nNew; i<nOld; i++){ 7653 freePage(apOld[i], &rc); 7654 } 7655 7656 #if 0 7657 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){ 7658 /* The ptrmapCheckPages() contains assert() statements that verify that 7659 ** all pointer map pages are set correctly. This is helpful while 7660 ** debugging. This is usually disabled because a corrupt database may 7661 ** cause an assert() statement to fail. */ 7662 ptrmapCheckPages(apNew, nNew); 7663 ptrmapCheckPages(&pParent, 1); 7664 } 7665 #endif 7666 7667 /* 7668 ** Cleanup before returning. 7669 */ 7670 balance_cleanup: 7671 sqlite3ScratchFree(b.apCell); 7672 for(i=0; i<nOld; i++){ 7673 releasePage(apOld[i]); 7674 } 7675 for(i=0; i<nNew; i++){ 7676 releasePage(apNew[i]); 7677 } 7678 7679 return rc; 7680 } 7681 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) 7682 #pragma optimize("", on) 7683 #endif 7684 7685 7686 /* 7687 ** This function is called when the root page of a b-tree structure is 7688 ** overfull (has one or more overflow pages). 7689 ** 7690 ** A new child page is allocated and the contents of the current root 7691 ** page, including overflow cells, are copied into the child. The root 7692 ** page is then overwritten to make it an empty page with the right-child 7693 ** pointer pointing to the new page. 7694 ** 7695 ** Before returning, all pointer-map entries corresponding to pages 7696 ** that the new child-page now contains pointers to are updated. The 7697 ** entry corresponding to the new right-child pointer of the root 7698 ** page is also updated. 7699 ** 7700 ** If successful, *ppChild is set to contain a reference to the child 7701 ** page and SQLITE_OK is returned. In this case the caller is required 7702 ** to call releasePage() on *ppChild exactly once. If an error occurs, 7703 ** an error code is returned and *ppChild is set to 0. 7704 */ 7705 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ 7706 int rc; /* Return value from subprocedures */ 7707 MemPage *pChild = 0; /* Pointer to a new child page */ 7708 Pgno pgnoChild = 0; /* Page number of the new child page */ 7709 BtShared *pBt = pRoot->pBt; /* The BTree */ 7710 7711 assert( pRoot->nOverflow>0 ); 7712 assert( sqlite3_mutex_held(pBt->mutex) ); 7713 7714 /* Make pRoot, the root page of the b-tree, writable. Allocate a new 7715 ** page that will become the new right-child of pPage. Copy the contents 7716 ** of the node stored on pRoot into the new child page. 7717 */ 7718 rc = sqlite3PagerWrite(pRoot->pDbPage); 7719 if( rc==SQLITE_OK ){ 7720 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); 7721 copyNodeContent(pRoot, pChild, &rc); 7722 if( ISAUTOVACUUM ){ 7723 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); 7724 } 7725 } 7726 if( rc ){ 7727 *ppChild = 0; 7728 releasePage(pChild); 7729 return rc; 7730 } 7731 assert( sqlite3PagerIswriteable(pChild->pDbPage) ); 7732 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 7733 assert( pChild->nCell==pRoot->nCell ); 7734 7735 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); 7736 7737 /* Copy the overflow cells from pRoot to pChild */ 7738 memcpy(pChild->aiOvfl, pRoot->aiOvfl, 7739 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); 7740 memcpy(pChild->apOvfl, pRoot->apOvfl, 7741 pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); 7742 pChild->nOverflow = pRoot->nOverflow; 7743 7744 /* Zero the contents of pRoot. Then install pChild as the right-child. */ 7745 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); 7746 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); 7747 7748 *ppChild = pChild; 7749 return SQLITE_OK; 7750 } 7751 7752 /* 7753 ** The page that pCur currently points to has just been modified in 7754 ** some way. This function figures out if this modification means the 7755 ** tree needs to be balanced, and if so calls the appropriate balancing 7756 ** routine. Balancing routines are: 7757 ** 7758 ** balance_quick() 7759 ** balance_deeper() 7760 ** balance_nonroot() 7761 */ 7762 static int balance(BtCursor *pCur){ 7763 int rc = SQLITE_OK; 7764 const int nMin = pCur->pBt->usableSize * 2 / 3; 7765 u8 aBalanceQuickSpace[13]; 7766 u8 *pFree = 0; 7767 7768 TESTONLY( int balance_quick_called = 0 ); 7769 TESTONLY( int balance_deeper_called = 0 ); 7770 7771 do { 7772 int iPage = pCur->iPage; 7773 MemPage *pPage = pCur->apPage[iPage]; 7774 7775 if( iPage==0 ){ 7776 if( pPage->nOverflow ){ 7777 /* The root page of the b-tree is overfull. In this case call the 7778 ** balance_deeper() function to create a new child for the root-page 7779 ** and copy the current contents of the root-page to it. The 7780 ** next iteration of the do-loop will balance the child page. 7781 */ 7782 assert( (balance_deeper_called++)==0 ); 7783 rc = balance_deeper(pPage, &pCur->apPage[1]); 7784 if( rc==SQLITE_OK ){ 7785 pCur->iPage = 1; 7786 pCur->aiIdx[0] = 0; 7787 pCur->aiIdx[1] = 0; 7788 assert( pCur->apPage[1]->nOverflow ); 7789 } 7790 }else{ 7791 break; 7792 } 7793 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ 7794 break; 7795 }else{ 7796 MemPage * const pParent = pCur->apPage[iPage-1]; 7797 int const iIdx = pCur->aiIdx[iPage-1]; 7798 7799 rc = sqlite3PagerWrite(pParent->pDbPage); 7800 if( rc==SQLITE_OK ){ 7801 #ifndef SQLITE_OMIT_QUICKBALANCE 7802 if( pPage->intKeyLeaf 7803 && pPage->nOverflow==1 7804 && pPage->aiOvfl[0]==pPage->nCell 7805 && pParent->pgno!=1 7806 && pParent->nCell==iIdx 7807 ){ 7808 /* Call balance_quick() to create a new sibling of pPage on which 7809 ** to store the overflow cell. balance_quick() inserts a new cell 7810 ** into pParent, which may cause pParent overflow. If this 7811 ** happens, the next iteration of the do-loop will balance pParent 7812 ** use either balance_nonroot() or balance_deeper(). Until this 7813 ** happens, the overflow cell is stored in the aBalanceQuickSpace[] 7814 ** buffer. 7815 ** 7816 ** The purpose of the following assert() is to check that only a 7817 ** single call to balance_quick() is made for each call to this 7818 ** function. If this were not verified, a subtle bug involving reuse 7819 ** of the aBalanceQuickSpace[] might sneak in. 7820 */ 7821 assert( (balance_quick_called++)==0 ); 7822 rc = balance_quick(pParent, pPage, aBalanceQuickSpace); 7823 }else 7824 #endif 7825 { 7826 /* In this case, call balance_nonroot() to redistribute cells 7827 ** between pPage and up to 2 of its sibling pages. This involves 7828 ** modifying the contents of pParent, which may cause pParent to 7829 ** become overfull or underfull. The next iteration of the do-loop 7830 ** will balance the parent page to correct this. 7831 ** 7832 ** If the parent page becomes overfull, the overflow cell or cells 7833 ** are stored in the pSpace buffer allocated immediately below. 7834 ** A subsequent iteration of the do-loop will deal with this by 7835 ** calling balance_nonroot() (balance_deeper() may be called first, 7836 ** but it doesn't deal with overflow cells - just moves them to a 7837 ** different page). Once this subsequent call to balance_nonroot() 7838 ** has completed, it is safe to release the pSpace buffer used by 7839 ** the previous call, as the overflow cell data will have been 7840 ** copied either into the body of a database page or into the new 7841 ** pSpace buffer passed to the latter call to balance_nonroot(). 7842 */ 7843 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); 7844 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, 7845 pCur->hints&BTREE_BULKLOAD); 7846 if( pFree ){ 7847 /* If pFree is not NULL, it points to the pSpace buffer used 7848 ** by a previous call to balance_nonroot(). Its contents are 7849 ** now stored either on real database pages or within the 7850 ** new pSpace buffer, so it may be safely freed here. */ 7851 sqlite3PageFree(pFree); 7852 } 7853 7854 /* The pSpace buffer will be freed after the next call to 7855 ** balance_nonroot(), or just before this function returns, whichever 7856 ** comes first. */ 7857 pFree = pSpace; 7858 } 7859 } 7860 7861 pPage->nOverflow = 0; 7862 7863 /* The next iteration of the do-loop balances the parent page. */ 7864 releasePage(pPage); 7865 pCur->iPage--; 7866 assert( pCur->iPage>=0 ); 7867 } 7868 }while( rc==SQLITE_OK ); 7869 7870 if( pFree ){ 7871 sqlite3PageFree(pFree); 7872 } 7873 return rc; 7874 } 7875 7876 7877 /* 7878 ** Insert a new record into the BTree. The key is given by (pKey,nKey) 7879 ** and the data is given by (pData,nData). The cursor is used only to 7880 ** define what table the record should be inserted into. The cursor 7881 ** is left pointing at a random location. 7882 ** 7883 ** For an INTKEY table, only the nKey value of the key is used. pKey is 7884 ** ignored. For a ZERODATA table, the pData and nData are both ignored. 7885 ** 7886 ** If the seekResult parameter is non-zero, then a successful call to 7887 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already 7888 ** been performed. seekResult is the search result returned (a negative 7889 ** number if pCur points at an entry that is smaller than (pKey, nKey), or 7890 ** a positive value if pCur points at an entry that is larger than 7891 ** (pKey, nKey)). 7892 ** 7893 ** If the seekResult parameter is non-zero, then the caller guarantees that 7894 ** cursor pCur is pointing at the existing copy of a row that is to be 7895 ** overwritten. If the seekResult parameter is 0, then cursor pCur may 7896 ** point to any entry or to no entry at all and so this function has to seek 7897 ** the cursor before the new key can be inserted. 7898 */ 7899 int sqlite3BtreeInsert( 7900 BtCursor *pCur, /* Insert data into the table of this cursor */ 7901 const void *pKey, i64 nKey, /* The key of the new record */ 7902 const void *pData, int nData, /* The data of the new record */ 7903 int nZero, /* Number of extra 0 bytes to append to data */ 7904 int appendBias, /* True if this is likely an append */ 7905 int seekResult /* Result of prior MovetoUnpacked() call */ 7906 ){ 7907 int rc; 7908 int loc = seekResult; /* -1: before desired location +1: after */ 7909 int szNew = 0; 7910 int idx; 7911 MemPage *pPage; 7912 Btree *p = pCur->pBtree; 7913 BtShared *pBt = p->pBt; 7914 unsigned char *oldCell; 7915 unsigned char *newCell = 0; 7916 7917 if( pCur->eState==CURSOR_FAULT ){ 7918 assert( pCur->skipNext!=SQLITE_OK ); 7919 return pCur->skipNext; 7920 } 7921 7922 assert( cursorHoldsMutex(pCur) ); 7923 assert( (pCur->curFlags & BTCF_WriteFlag)!=0 7924 && pBt->inTransaction==TRANS_WRITE 7925 && (pBt->btsFlags & BTS_READ_ONLY)==0 ); 7926 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 7927 7928 /* Assert that the caller has been consistent. If this cursor was opened 7929 ** expecting an index b-tree, then the caller should be inserting blob 7930 ** keys with no associated data. If the cursor was opened expecting an 7931 ** intkey table, the caller should be inserting integer keys with a 7932 ** blob of associated data. */ 7933 assert( (pKey==0)==(pCur->pKeyInfo==0) ); 7934 7935 /* Save the positions of any other cursors open on this table. 7936 ** 7937 ** In some cases, the call to btreeMoveto() below is a no-op. For 7938 ** example, when inserting data into a table with auto-generated integer 7939 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 7940 ** integer key to use. It then calls this function to actually insert the 7941 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes 7942 ** that the cursor is already where it needs to be and returns without 7943 ** doing any work. To avoid thwarting these optimizations, it is important 7944 ** not to clear the cursor here. 7945 */ 7946 if( pCur->curFlags & BTCF_Multiple ){ 7947 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 7948 if( rc ) return rc; 7949 } 7950 7951 if( pCur->pKeyInfo==0 ){ 7952 assert( pKey==0 ); 7953 /* If this is an insert into a table b-tree, invalidate any incrblob 7954 ** cursors open on the row being replaced */ 7955 invalidateIncrblobCursors(p, nKey, 0); 7956 7957 /* If the cursor is currently on the last row and we are appending a 7958 ** new row onto the end, set the "loc" to avoid an unnecessary 7959 ** btreeMoveto() call */ 7960 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 7961 && pCur->info.nKey==nKey-1 ){ 7962 loc = -1; 7963 }else if( loc==0 ){ 7964 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc); 7965 if( rc ) return rc; 7966 } 7967 }else if( loc==0 ){ 7968 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc); 7969 if( rc ) return rc; 7970 } 7971 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); 7972 7973 pPage = pCur->apPage[pCur->iPage]; 7974 assert( pPage->intKey || nKey>=0 ); 7975 assert( pPage->leaf || !pPage->intKey ); 7976 7977 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", 7978 pCur->pgnoRoot, nKey, nData, pPage->pgno, 7979 loc==0 ? "overwrite" : "new entry")); 7980 assert( pPage->isInit ); 7981 newCell = pBt->pTmpSpace; 7982 assert( newCell!=0 ); 7983 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); 7984 if( rc ) goto end_insert; 7985 assert( szNew==pPage->xCellSize(pPage, newCell) ); 7986 assert( szNew <= MX_CELL_SIZE(pBt) ); 7987 idx = pCur->aiIdx[pCur->iPage]; 7988 if( loc==0 ){ 7989 u16 szOld; 7990 assert( idx<pPage->nCell ); 7991 rc = sqlite3PagerWrite(pPage->pDbPage); 7992 if( rc ){ 7993 goto end_insert; 7994 } 7995 oldCell = findCell(pPage, idx); 7996 if( !pPage->leaf ){ 7997 memcpy(newCell, oldCell, 4); 7998 } 7999 rc = clearCell(pPage, oldCell, &szOld); 8000 dropCell(pPage, idx, szOld, &rc); 8001 if( rc ) goto end_insert; 8002 }else if( loc<0 && pPage->nCell>0 ){ 8003 assert( pPage->leaf ); 8004 idx = ++pCur->aiIdx[pCur->iPage]; 8005 }else{ 8006 assert( pPage->leaf ); 8007 } 8008 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); 8009 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); 8010 8011 /* If no error has occurred and pPage has an overflow cell, call balance() 8012 ** to redistribute the cells within the tree. Since balance() may move 8013 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey 8014 ** variables. 8015 ** 8016 ** Previous versions of SQLite called moveToRoot() to move the cursor 8017 ** back to the root page as balance() used to invalidate the contents 8018 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, 8019 ** set the cursor state to "invalid". This makes common insert operations 8020 ** slightly faster. 8021 ** 8022 ** There is a subtle but important optimization here too. When inserting 8023 ** multiple records into an intkey b-tree using a single cursor (as can 8024 ** happen while processing an "INSERT INTO ... SELECT" statement), it 8025 ** is advantageous to leave the cursor pointing to the last entry in 8026 ** the b-tree if possible. If the cursor is left pointing to the last 8027 ** entry in the table, and the next row inserted has an integer key 8028 ** larger than the largest existing key, it is possible to insert the 8029 ** row without seeking the cursor. This can be a big performance boost. 8030 */ 8031 pCur->info.nSize = 0; 8032 if( rc==SQLITE_OK && pPage->nOverflow ){ 8033 pCur->curFlags &= ~(BTCF_ValidNKey); 8034 rc = balance(pCur); 8035 8036 /* Must make sure nOverflow is reset to zero even if the balance() 8037 ** fails. Internal data structure corruption will result otherwise. 8038 ** Also, set the cursor state to invalid. This stops saveCursorPosition() 8039 ** from trying to save the current position of the cursor. */ 8040 pCur->apPage[pCur->iPage]->nOverflow = 0; 8041 pCur->eState = CURSOR_INVALID; 8042 } 8043 assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); 8044 8045 end_insert: 8046 return rc; 8047 } 8048 8049 /* 8050 ** Delete the entry that the cursor is pointing to. 8051 ** 8052 ** If the second parameter is zero, then the cursor is left pointing at an 8053 ** arbitrary location after the delete. If it is non-zero, then the cursor 8054 ** is left in a state such that the next call to BtreeNext() or BtreePrev() 8055 ** moves it to the same row as it would if the call to BtreeDelete() had 8056 ** been omitted. 8057 */ 8058 int sqlite3BtreeDelete(BtCursor *pCur, int bPreserve){ 8059 Btree *p = pCur->pBtree; 8060 BtShared *pBt = p->pBt; 8061 int rc; /* Return code */ 8062 MemPage *pPage; /* Page to delete cell from */ 8063 unsigned char *pCell; /* Pointer to cell to delete */ 8064 int iCellIdx; /* Index of cell to delete */ 8065 int iCellDepth; /* Depth of node containing pCell */ 8066 u16 szCell; /* Size of the cell being deleted */ 8067 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ 8068 8069 assert( cursorHoldsMutex(pCur) ); 8070 assert( pBt->inTransaction==TRANS_WRITE ); 8071 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 8072 assert( pCur->curFlags & BTCF_WriteFlag ); 8073 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 8074 assert( !hasReadConflicts(p, pCur->pgnoRoot) ); 8075 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); 8076 assert( pCur->eState==CURSOR_VALID ); 8077 8078 iCellDepth = pCur->iPage; 8079 iCellIdx = pCur->aiIdx[iCellDepth]; 8080 pPage = pCur->apPage[iCellDepth]; 8081 pCell = findCell(pPage, iCellIdx); 8082 8083 /* If the page containing the entry to delete is not a leaf page, move 8084 ** the cursor to the largest entry in the tree that is smaller than 8085 ** the entry being deleted. This cell will replace the cell being deleted 8086 ** from the internal node. The 'previous' entry is used for this instead 8087 ** of the 'next' entry, as the previous entry is always a part of the 8088 ** sub-tree headed by the child page of the cell being deleted. This makes 8089 ** balancing the tree following the delete operation easier. */ 8090 if( !pPage->leaf ){ 8091 int notUsed = 0; 8092 rc = sqlite3BtreePrevious(pCur, ¬Used); 8093 if( rc ) return rc; 8094 } 8095 8096 /* Save the positions of any other cursors open on this table before 8097 ** making any modifications. */ 8098 if( pCur->curFlags & BTCF_Multiple ){ 8099 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 8100 if( rc ) return rc; 8101 } 8102 8103 /* If this is a delete operation to remove a row from a table b-tree, 8104 ** invalidate any incrblob cursors open on the row being deleted. */ 8105 if( pCur->pKeyInfo==0 ){ 8106 invalidateIncrblobCursors(p, pCur->info.nKey, 0); 8107 } 8108 8109 /* If the bPreserve flag is set to true, then the cursor position must 8110 ** be preserved following this delete operation. If the current delete 8111 ** will cause a b-tree rebalance, then this is done by saving the cursor 8112 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 8113 ** returning. 8114 ** 8115 ** Or, if the current delete will not cause a rebalance, then the cursor 8116 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately 8117 ** before or after the deleted entry. In this case set bSkipnext to true. */ 8118 if( bPreserve ){ 8119 if( !pPage->leaf 8120 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) 8121 ){ 8122 /* A b-tree rebalance will be required after deleting this entry. 8123 ** Save the cursor key. */ 8124 rc = saveCursorKey(pCur); 8125 if( rc ) return rc; 8126 }else{ 8127 bSkipnext = 1; 8128 } 8129 } 8130 8131 /* Make the page containing the entry to be deleted writable. Then free any 8132 ** overflow pages associated with the entry and finally remove the cell 8133 ** itself from within the page. */ 8134 rc = sqlite3PagerWrite(pPage->pDbPage); 8135 if( rc ) return rc; 8136 rc = clearCell(pPage, pCell, &szCell); 8137 dropCell(pPage, iCellIdx, szCell, &rc); 8138 if( rc ) return rc; 8139 8140 /* If the cell deleted was not located on a leaf page, then the cursor 8141 ** is currently pointing to the largest entry in the sub-tree headed 8142 ** by the child-page of the cell that was just deleted from an internal 8143 ** node. The cell from the leaf node needs to be moved to the internal 8144 ** node to replace the deleted cell. */ 8145 if( !pPage->leaf ){ 8146 MemPage *pLeaf = pCur->apPage[pCur->iPage]; 8147 int nCell; 8148 Pgno n = pCur->apPage[iCellDepth+1]->pgno; 8149 unsigned char *pTmp; 8150 8151 pCell = findCell(pLeaf, pLeaf->nCell-1); 8152 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; 8153 nCell = pLeaf->xCellSize(pLeaf, pCell); 8154 assert( MX_CELL_SIZE(pBt) >= nCell ); 8155 pTmp = pBt->pTmpSpace; 8156 assert( pTmp!=0 ); 8157 rc = sqlite3PagerWrite(pLeaf->pDbPage); 8158 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); 8159 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); 8160 if( rc ) return rc; 8161 } 8162 8163 /* Balance the tree. If the entry deleted was located on a leaf page, 8164 ** then the cursor still points to that page. In this case the first 8165 ** call to balance() repairs the tree, and the if(...) condition is 8166 ** never true. 8167 ** 8168 ** Otherwise, if the entry deleted was on an internal node page, then 8169 ** pCur is pointing to the leaf page from which a cell was removed to 8170 ** replace the cell deleted from the internal node. This is slightly 8171 ** tricky as the leaf node may be underfull, and the internal node may 8172 ** be either under or overfull. In this case run the balancing algorithm 8173 ** on the leaf node first. If the balance proceeds far enough up the 8174 ** tree that we can be sure that any problem in the internal node has 8175 ** been corrected, so be it. Otherwise, after balancing the leaf node, 8176 ** walk the cursor up the tree to the internal node and balance it as 8177 ** well. */ 8178 rc = balance(pCur); 8179 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ 8180 while( pCur->iPage>iCellDepth ){ 8181 releasePage(pCur->apPage[pCur->iPage--]); 8182 } 8183 rc = balance(pCur); 8184 } 8185 8186 if( rc==SQLITE_OK ){ 8187 if( bSkipnext ){ 8188 assert( bPreserve && pCur->iPage==iCellDepth ); 8189 assert( pPage==pCur->apPage[pCur->iPage] ); 8190 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); 8191 pCur->eState = CURSOR_SKIPNEXT; 8192 if( iCellIdx>=pPage->nCell ){ 8193 pCur->skipNext = -1; 8194 pCur->aiIdx[iCellDepth] = pPage->nCell-1; 8195 }else{ 8196 pCur->skipNext = 1; 8197 } 8198 }else{ 8199 rc = moveToRoot(pCur); 8200 if( bPreserve ){ 8201 pCur->eState = CURSOR_REQUIRESEEK; 8202 } 8203 } 8204 } 8205 return rc; 8206 } 8207 8208 /* 8209 ** Create a new BTree table. Write into *piTable the page 8210 ** number for the root page of the new table. 8211 ** 8212 ** The type of type is determined by the flags parameter. Only the 8213 ** following values of flags are currently in use. Other values for 8214 ** flags might not work: 8215 ** 8216 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys 8217 ** BTREE_ZERODATA Used for SQL indices 8218 */ 8219 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ 8220 BtShared *pBt = p->pBt; 8221 MemPage *pRoot; 8222 Pgno pgnoRoot; 8223 int rc; 8224 int ptfFlags; /* Page-type flage for the root page of new table */ 8225 8226 assert( sqlite3BtreeHoldsMutex(p) ); 8227 assert( pBt->inTransaction==TRANS_WRITE ); 8228 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 8229 8230 #ifdef SQLITE_OMIT_AUTOVACUUM 8231 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 8232 if( rc ){ 8233 return rc; 8234 } 8235 #else 8236 if( pBt->autoVacuum ){ 8237 Pgno pgnoMove; /* Move a page here to make room for the root-page */ 8238 MemPage *pPageMove; /* The page to move to. */ 8239 8240 /* Creating a new table may probably require moving an existing database 8241 ** to make room for the new tables root page. In case this page turns 8242 ** out to be an overflow page, delete all overflow page-map caches 8243 ** held by open cursors. 8244 */ 8245 invalidateAllOverflowCache(pBt); 8246 8247 /* Read the value of meta[3] from the database to determine where the 8248 ** root page of the new table should go. meta[3] is the largest root-page 8249 ** created so far, so the new root-page is (meta[3]+1). 8250 */ 8251 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); 8252 pgnoRoot++; 8253 8254 /* The new root-page may not be allocated on a pointer-map page, or the 8255 ** PENDING_BYTE page. 8256 */ 8257 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || 8258 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ 8259 pgnoRoot++; 8260 } 8261 assert( pgnoRoot>=3 || CORRUPT_DB ); 8262 testcase( pgnoRoot<3 ); 8263 8264 /* Allocate a page. The page that currently resides at pgnoRoot will 8265 ** be moved to the allocated page (unless the allocated page happens 8266 ** to reside at pgnoRoot). 8267 */ 8268 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); 8269 if( rc!=SQLITE_OK ){ 8270 return rc; 8271 } 8272 8273 if( pgnoMove!=pgnoRoot ){ 8274 /* pgnoRoot is the page that will be used for the root-page of 8275 ** the new table (assuming an error did not occur). But we were 8276 ** allocated pgnoMove. If required (i.e. if it was not allocated 8277 ** by extending the file), the current page at position pgnoMove 8278 ** is already journaled. 8279 */ 8280 u8 eType = 0; 8281 Pgno iPtrPage = 0; 8282 8283 /* Save the positions of any open cursors. This is required in 8284 ** case they are holding a reference to an xFetch reference 8285 ** corresponding to page pgnoRoot. */ 8286 rc = saveAllCursors(pBt, 0, 0); 8287 releasePage(pPageMove); 8288 if( rc!=SQLITE_OK ){ 8289 return rc; 8290 } 8291 8292 /* Move the page currently at pgnoRoot to pgnoMove. */ 8293 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 8294 if( rc!=SQLITE_OK ){ 8295 return rc; 8296 } 8297 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); 8298 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ 8299 rc = SQLITE_CORRUPT_BKPT; 8300 } 8301 if( rc!=SQLITE_OK ){ 8302 releasePage(pRoot); 8303 return rc; 8304 } 8305 assert( eType!=PTRMAP_ROOTPAGE ); 8306 assert( eType!=PTRMAP_FREEPAGE ); 8307 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); 8308 releasePage(pRoot); 8309 8310 /* Obtain the page at pgnoRoot */ 8311 if( rc!=SQLITE_OK ){ 8312 return rc; 8313 } 8314 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 8315 if( rc!=SQLITE_OK ){ 8316 return rc; 8317 } 8318 rc = sqlite3PagerWrite(pRoot->pDbPage); 8319 if( rc!=SQLITE_OK ){ 8320 releasePage(pRoot); 8321 return rc; 8322 } 8323 }else{ 8324 pRoot = pPageMove; 8325 } 8326 8327 /* Update the pointer-map and meta-data with the new root-page number. */ 8328 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); 8329 if( rc ){ 8330 releasePage(pRoot); 8331 return rc; 8332 } 8333 8334 /* When the new root page was allocated, page 1 was made writable in 8335 ** order either to increase the database filesize, or to decrement the 8336 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. 8337 */ 8338 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); 8339 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); 8340 if( NEVER(rc) ){ 8341 releasePage(pRoot); 8342 return rc; 8343 } 8344 8345 }else{ 8346 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 8347 if( rc ) return rc; 8348 } 8349 #endif 8350 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 8351 if( createTabFlags & BTREE_INTKEY ){ 8352 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; 8353 }else{ 8354 ptfFlags = PTF_ZERODATA | PTF_LEAF; 8355 } 8356 zeroPage(pRoot, ptfFlags); 8357 sqlite3PagerUnref(pRoot->pDbPage); 8358 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); 8359 *piTable = (int)pgnoRoot; 8360 return SQLITE_OK; 8361 } 8362 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ 8363 int rc; 8364 sqlite3BtreeEnter(p); 8365 rc = btreeCreateTable(p, piTable, flags); 8366 sqlite3BtreeLeave(p); 8367 return rc; 8368 } 8369 8370 /* 8371 ** Erase the given database page and all its children. Return 8372 ** the page to the freelist. 8373 */ 8374 static int clearDatabasePage( 8375 BtShared *pBt, /* The BTree that contains the table */ 8376 Pgno pgno, /* Page number to clear */ 8377 int freePageFlag, /* Deallocate page if true */ 8378 int *pnChange /* Add number of Cells freed to this counter */ 8379 ){ 8380 MemPage *pPage; 8381 int rc; 8382 unsigned char *pCell; 8383 int i; 8384 int hdr; 8385 u16 szCell; 8386 8387 assert( sqlite3_mutex_held(pBt->mutex) ); 8388 if( pgno>btreePagecount(pBt) ){ 8389 return SQLITE_CORRUPT_BKPT; 8390 } 8391 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); 8392 if( rc ) return rc; 8393 if( pPage->bBusy ){ 8394 rc = SQLITE_CORRUPT_BKPT; 8395 goto cleardatabasepage_out; 8396 } 8397 pPage->bBusy = 1; 8398 hdr = pPage->hdrOffset; 8399 for(i=0; i<pPage->nCell; i++){ 8400 pCell = findCell(pPage, i); 8401 if( !pPage->leaf ){ 8402 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); 8403 if( rc ) goto cleardatabasepage_out; 8404 } 8405 rc = clearCell(pPage, pCell, &szCell); 8406 if( rc ) goto cleardatabasepage_out; 8407 } 8408 if( !pPage->leaf ){ 8409 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); 8410 if( rc ) goto cleardatabasepage_out; 8411 }else if( pnChange ){ 8412 assert( pPage->intKey || CORRUPT_DB ); 8413 testcase( !pPage->intKey ); 8414 *pnChange += pPage->nCell; 8415 } 8416 if( freePageFlag ){ 8417 freePage(pPage, &rc); 8418 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ 8419 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); 8420 } 8421 8422 cleardatabasepage_out: 8423 pPage->bBusy = 0; 8424 releasePage(pPage); 8425 return rc; 8426 } 8427 8428 /* 8429 ** Delete all information from a single table in the database. iTable is 8430 ** the page number of the root of the table. After this routine returns, 8431 ** the root page is empty, but still exists. 8432 ** 8433 ** This routine will fail with SQLITE_LOCKED if there are any open 8434 ** read cursors on the table. Open write cursors are moved to the 8435 ** root of the table. 8436 ** 8437 ** If pnChange is not NULL, then table iTable must be an intkey table. The 8438 ** integer value pointed to by pnChange is incremented by the number of 8439 ** entries in the table. 8440 */ 8441 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ 8442 int rc; 8443 BtShared *pBt = p->pBt; 8444 sqlite3BtreeEnter(p); 8445 assert( p->inTrans==TRANS_WRITE ); 8446 8447 rc = saveAllCursors(pBt, (Pgno)iTable, 0); 8448 8449 if( SQLITE_OK==rc ){ 8450 /* Invalidate all incrblob cursors open on table iTable (assuming iTable 8451 ** is the root of a table b-tree - if it is not, the following call is 8452 ** a no-op). */ 8453 invalidateIncrblobCursors(p, 0, 1); 8454 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); 8455 } 8456 sqlite3BtreeLeave(p); 8457 return rc; 8458 } 8459 8460 /* 8461 ** Delete all information from the single table that pCur is open on. 8462 ** 8463 ** This routine only work for pCur on an ephemeral table. 8464 */ 8465 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ 8466 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); 8467 } 8468 8469 /* 8470 ** Erase all information in a table and add the root of the table to 8471 ** the freelist. Except, the root of the principle table (the one on 8472 ** page 1) is never added to the freelist. 8473 ** 8474 ** This routine will fail with SQLITE_LOCKED if there are any open 8475 ** cursors on the table. 8476 ** 8477 ** If AUTOVACUUM is enabled and the page at iTable is not the last 8478 ** root page in the database file, then the last root page 8479 ** in the database file is moved into the slot formerly occupied by 8480 ** iTable and that last slot formerly occupied by the last root page 8481 ** is added to the freelist instead of iTable. In this say, all 8482 ** root pages are kept at the beginning of the database file, which 8483 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the 8484 ** page number that used to be the last root page in the file before 8485 ** the move. If no page gets moved, *piMoved is set to 0. 8486 ** The last root page is recorded in meta[3] and the value of 8487 ** meta[3] is updated by this procedure. 8488 */ 8489 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ 8490 int rc; 8491 MemPage *pPage = 0; 8492 BtShared *pBt = p->pBt; 8493 8494 assert( sqlite3BtreeHoldsMutex(p) ); 8495 assert( p->inTrans==TRANS_WRITE ); 8496 8497 /* It is illegal to drop a table if any cursors are open on the 8498 ** database. This is because in auto-vacuum mode the backend may 8499 ** need to move another root-page to fill a gap left by the deleted 8500 ** root page. If an open cursor was using this page a problem would 8501 ** occur. 8502 ** 8503 ** This error is caught long before control reaches this point. 8504 */ 8505 if( NEVER(pBt->pCursor) ){ 8506 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db); 8507 return SQLITE_LOCKED_SHAREDCACHE; 8508 } 8509 8510 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); 8511 if( rc ) return rc; 8512 rc = sqlite3BtreeClearTable(p, iTable, 0); 8513 if( rc ){ 8514 releasePage(pPage); 8515 return rc; 8516 } 8517 8518 *piMoved = 0; 8519 8520 if( iTable>1 ){ 8521 #ifdef SQLITE_OMIT_AUTOVACUUM 8522 freePage(pPage, &rc); 8523 releasePage(pPage); 8524 #else 8525 if( pBt->autoVacuum ){ 8526 Pgno maxRootPgno; 8527 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); 8528 8529 if( iTable==maxRootPgno ){ 8530 /* If the table being dropped is the table with the largest root-page 8531 ** number in the database, put the root page on the free list. 8532 */ 8533 freePage(pPage, &rc); 8534 releasePage(pPage); 8535 if( rc!=SQLITE_OK ){ 8536 return rc; 8537 } 8538 }else{ 8539 /* The table being dropped does not have the largest root-page 8540 ** number in the database. So move the page that does into the 8541 ** gap left by the deleted root-page. 8542 */ 8543 MemPage *pMove; 8544 releasePage(pPage); 8545 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 8546 if( rc!=SQLITE_OK ){ 8547 return rc; 8548 } 8549 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); 8550 releasePage(pMove); 8551 if( rc!=SQLITE_OK ){ 8552 return rc; 8553 } 8554 pMove = 0; 8555 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 8556 freePage(pMove, &rc); 8557 releasePage(pMove); 8558 if( rc!=SQLITE_OK ){ 8559 return rc; 8560 } 8561 *piMoved = maxRootPgno; 8562 } 8563 8564 /* Set the new 'max-root-page' value in the database header. This 8565 ** is the old value less one, less one more if that happens to 8566 ** be a root-page number, less one again if that is the 8567 ** PENDING_BYTE_PAGE. 8568 */ 8569 maxRootPgno--; 8570 while( maxRootPgno==PENDING_BYTE_PAGE(pBt) 8571 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ 8572 maxRootPgno--; 8573 } 8574 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); 8575 8576 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); 8577 }else{ 8578 freePage(pPage, &rc); 8579 releasePage(pPage); 8580 } 8581 #endif 8582 }else{ 8583 /* If sqlite3BtreeDropTable was called on page 1. 8584 ** This really never should happen except in a corrupt 8585 ** database. 8586 */ 8587 zeroPage(pPage, PTF_INTKEY|PTF_LEAF ); 8588 releasePage(pPage); 8589 } 8590 return rc; 8591 } 8592 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ 8593 int rc; 8594 sqlite3BtreeEnter(p); 8595 rc = btreeDropTable(p, iTable, piMoved); 8596 sqlite3BtreeLeave(p); 8597 return rc; 8598 } 8599 8600 8601 /* 8602 ** This function may only be called if the b-tree connection already 8603 ** has a read or write transaction open on the database. 8604 ** 8605 ** Read the meta-information out of a database file. Meta[0] 8606 ** is the number of free pages currently in the database. Meta[1] 8607 ** through meta[15] are available for use by higher layers. Meta[0] 8608 ** is read-only, the others are read/write. 8609 ** 8610 ** The schema layer numbers meta values differently. At the schema 8611 ** layer (and the SetCookie and ReadCookie opcodes) the number of 8612 ** free pages is not visible. So Cookie[0] is the same as Meta[1]. 8613 ** 8614 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead 8615 ** of reading the value out of the header, it instead loads the "DataVersion" 8616 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the 8617 ** database file. It is a number computed by the pager. But its access 8618 ** pattern is the same as header meta values, and so it is convenient to 8619 ** read it from this routine. 8620 */ 8621 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ 8622 BtShared *pBt = p->pBt; 8623 8624 sqlite3BtreeEnter(p); 8625 assert( p->inTrans>TRANS_NONE ); 8626 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); 8627 assert( pBt->pPage1 ); 8628 assert( idx>=0 && idx<=15 ); 8629 8630 if( idx==BTREE_DATA_VERSION ){ 8631 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; 8632 }else{ 8633 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); 8634 } 8635 8636 /* If auto-vacuum is disabled in this build and this is an auto-vacuum 8637 ** database, mark the database as read-only. */ 8638 #ifdef SQLITE_OMIT_AUTOVACUUM 8639 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ 8640 pBt->btsFlags |= BTS_READ_ONLY; 8641 } 8642 #endif 8643 8644 sqlite3BtreeLeave(p); 8645 } 8646 8647 /* 8648 ** Write meta-information back into the database. Meta[0] is 8649 ** read-only and may not be written. 8650 */ 8651 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ 8652 BtShared *pBt = p->pBt; 8653 unsigned char *pP1; 8654 int rc; 8655 assert( idx>=1 && idx<=15 ); 8656 sqlite3BtreeEnter(p); 8657 assert( p->inTrans==TRANS_WRITE ); 8658 assert( pBt->pPage1!=0 ); 8659 pP1 = pBt->pPage1->aData; 8660 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 8661 if( rc==SQLITE_OK ){ 8662 put4byte(&pP1[36 + idx*4], iMeta); 8663 #ifndef SQLITE_OMIT_AUTOVACUUM 8664 if( idx==BTREE_INCR_VACUUM ){ 8665 assert( pBt->autoVacuum || iMeta==0 ); 8666 assert( iMeta==0 || iMeta==1 ); 8667 pBt->incrVacuum = (u8)iMeta; 8668 } 8669 #endif 8670 } 8671 sqlite3BtreeLeave(p); 8672 return rc; 8673 } 8674 8675 #ifndef SQLITE_OMIT_BTREECOUNT 8676 /* 8677 ** The first argument, pCur, is a cursor opened on some b-tree. Count the 8678 ** number of entries in the b-tree and write the result to *pnEntry. 8679 ** 8680 ** SQLITE_OK is returned if the operation is successfully executed. 8681 ** Otherwise, if an error is encountered (i.e. an IO error or database 8682 ** corruption) an SQLite error code is returned. 8683 */ 8684 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ 8685 i64 nEntry = 0; /* Value to return in *pnEntry */ 8686 int rc; /* Return code */ 8687 8688 if( pCur->pgnoRoot==0 ){ 8689 *pnEntry = 0; 8690 return SQLITE_OK; 8691 } 8692 rc = moveToRoot(pCur); 8693 8694 /* Unless an error occurs, the following loop runs one iteration for each 8695 ** page in the B-Tree structure (not including overflow pages). 8696 */ 8697 while( rc==SQLITE_OK ){ 8698 int iIdx; /* Index of child node in parent */ 8699 MemPage *pPage; /* Current page of the b-tree */ 8700 8701 /* If this is a leaf page or the tree is not an int-key tree, then 8702 ** this page contains countable entries. Increment the entry counter 8703 ** accordingly. 8704 */ 8705 pPage = pCur->apPage[pCur->iPage]; 8706 if( pPage->leaf || !pPage->intKey ){ 8707 nEntry += pPage->nCell; 8708 } 8709 8710 /* pPage is a leaf node. This loop navigates the cursor so that it 8711 ** points to the first interior cell that it points to the parent of 8712 ** the next page in the tree that has not yet been visited. The 8713 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell 8714 ** of the page, or to the number of cells in the page if the next page 8715 ** to visit is the right-child of its parent. 8716 ** 8717 ** If all pages in the tree have been visited, return SQLITE_OK to the 8718 ** caller. 8719 */ 8720 if( pPage->leaf ){ 8721 do { 8722 if( pCur->iPage==0 ){ 8723 /* All pages of the b-tree have been visited. Return successfully. */ 8724 *pnEntry = nEntry; 8725 return moveToRoot(pCur); 8726 } 8727 moveToParent(pCur); 8728 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); 8729 8730 pCur->aiIdx[pCur->iPage]++; 8731 pPage = pCur->apPage[pCur->iPage]; 8732 } 8733 8734 /* Descend to the child node of the cell that the cursor currently 8735 ** points at. This is the right-child if (iIdx==pPage->nCell). 8736 */ 8737 iIdx = pCur->aiIdx[pCur->iPage]; 8738 if( iIdx==pPage->nCell ){ 8739 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 8740 }else{ 8741 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); 8742 } 8743 } 8744 8745 /* An error has occurred. Return an error code. */ 8746 return rc; 8747 } 8748 #endif 8749 8750 /* 8751 ** Return the pager associated with a BTree. This routine is used for 8752 ** testing and debugging only. 8753 */ 8754 Pager *sqlite3BtreePager(Btree *p){ 8755 return p->pBt->pPager; 8756 } 8757 8758 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 8759 /* 8760 ** Append a message to the error message string. 8761 */ 8762 static void checkAppendMsg( 8763 IntegrityCk *pCheck, 8764 const char *zFormat, 8765 ... 8766 ){ 8767 va_list ap; 8768 if( !pCheck->mxErr ) return; 8769 pCheck->mxErr--; 8770 pCheck->nErr++; 8771 va_start(ap, zFormat); 8772 if( pCheck->errMsg.nChar ){ 8773 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); 8774 } 8775 if( pCheck->zPfx ){ 8776 sqlite3XPrintf(&pCheck->errMsg, 0, pCheck->zPfx, pCheck->v1, pCheck->v2); 8777 } 8778 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap); 8779 va_end(ap); 8780 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ 8781 pCheck->mallocFailed = 1; 8782 } 8783 } 8784 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 8785 8786 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 8787 8788 /* 8789 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that 8790 ** corresponds to page iPg is already set. 8791 */ 8792 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 8793 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 8794 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); 8795 } 8796 8797 /* 8798 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. 8799 */ 8800 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 8801 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 8802 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); 8803 } 8804 8805 8806 /* 8807 ** Add 1 to the reference count for page iPage. If this is the second 8808 ** reference to the page, add an error message to pCheck->zErrMsg. 8809 ** Return 1 if there are 2 or more references to the page and 0 if 8810 ** if this is the first reference to the page. 8811 ** 8812 ** Also check that the page number is in bounds. 8813 */ 8814 static int checkRef(IntegrityCk *pCheck, Pgno iPage){ 8815 if( iPage==0 ) return 1; 8816 if( iPage>pCheck->nPage ){ 8817 checkAppendMsg(pCheck, "invalid page number %d", iPage); 8818 return 1; 8819 } 8820 if( getPageReferenced(pCheck, iPage) ){ 8821 checkAppendMsg(pCheck, "2nd reference to page %d", iPage); 8822 return 1; 8823 } 8824 setPageReferenced(pCheck, iPage); 8825 return 0; 8826 } 8827 8828 #ifndef SQLITE_OMIT_AUTOVACUUM 8829 /* 8830 ** Check that the entry in the pointer-map for page iChild maps to 8831 ** page iParent, pointer type ptrType. If not, append an error message 8832 ** to pCheck. 8833 */ 8834 static void checkPtrmap( 8835 IntegrityCk *pCheck, /* Integrity check context */ 8836 Pgno iChild, /* Child page number */ 8837 u8 eType, /* Expected pointer map type */ 8838 Pgno iParent /* Expected pointer map parent page number */ 8839 ){ 8840 int rc; 8841 u8 ePtrmapType; 8842 Pgno iPtrmapParent; 8843 8844 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); 8845 if( rc!=SQLITE_OK ){ 8846 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; 8847 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); 8848 return; 8849 } 8850 8851 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ 8852 checkAppendMsg(pCheck, 8853 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 8854 iChild, eType, iParent, ePtrmapType, iPtrmapParent); 8855 } 8856 } 8857 #endif 8858 8859 /* 8860 ** Check the integrity of the freelist or of an overflow page list. 8861 ** Verify that the number of pages on the list is N. 8862 */ 8863 static void checkList( 8864 IntegrityCk *pCheck, /* Integrity checking context */ 8865 int isFreeList, /* True for a freelist. False for overflow page list */ 8866 int iPage, /* Page number for first page in the list */ 8867 int N /* Expected number of pages in the list */ 8868 ){ 8869 int i; 8870 int expected = N; 8871 int iFirst = iPage; 8872 while( N-- > 0 && pCheck->mxErr ){ 8873 DbPage *pOvflPage; 8874 unsigned char *pOvflData; 8875 if( iPage<1 ){ 8876 checkAppendMsg(pCheck, 8877 "%d of %d pages missing from overflow list starting at %d", 8878 N+1, expected, iFirst); 8879 break; 8880 } 8881 if( checkRef(pCheck, iPage) ) break; 8882 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ 8883 checkAppendMsg(pCheck, "failed to get page %d", iPage); 8884 break; 8885 } 8886 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); 8887 if( isFreeList ){ 8888 int n = get4byte(&pOvflData[4]); 8889 #ifndef SQLITE_OMIT_AUTOVACUUM 8890 if( pCheck->pBt->autoVacuum ){ 8891 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); 8892 } 8893 #endif 8894 if( n>(int)pCheck->pBt->usableSize/4-2 ){ 8895 checkAppendMsg(pCheck, 8896 "freelist leaf count too big on page %d", iPage); 8897 N--; 8898 }else{ 8899 for(i=0; i<n; i++){ 8900 Pgno iFreePage = get4byte(&pOvflData[8+i*4]); 8901 #ifndef SQLITE_OMIT_AUTOVACUUM 8902 if( pCheck->pBt->autoVacuum ){ 8903 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); 8904 } 8905 #endif 8906 checkRef(pCheck, iFreePage); 8907 } 8908 N -= n; 8909 } 8910 } 8911 #ifndef SQLITE_OMIT_AUTOVACUUM 8912 else{ 8913 /* If this database supports auto-vacuum and iPage is not the last 8914 ** page in this overflow list, check that the pointer-map entry for 8915 ** the following page matches iPage. 8916 */ 8917 if( pCheck->pBt->autoVacuum && N>0 ){ 8918 i = get4byte(pOvflData); 8919 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); 8920 } 8921 } 8922 #endif 8923 iPage = get4byte(pOvflData); 8924 sqlite3PagerUnref(pOvflPage); 8925 8926 if( isFreeList && N<(iPage!=0) ){ 8927 checkAppendMsg(pCheck, "free-page count in header is too small"); 8928 } 8929 } 8930 } 8931 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 8932 8933 /* 8934 ** An implementation of a min-heap. 8935 ** 8936 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the 8937 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] 8938 ** and aHeap[N*2+1]. 8939 ** 8940 ** The heap property is this: Every node is less than or equal to both 8941 ** of its daughter nodes. A consequence of the heap property is that the 8942 ** root node aHeap[1] is always the minimum value currently in the heap. 8943 ** 8944 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto 8945 ** the heap, preserving the heap property. The btreeHeapPull() routine 8946 ** removes the root element from the heap (the minimum value in the heap) 8947 ** and then moves other nodes around as necessary to preserve the heap 8948 ** property. 8949 ** 8950 ** This heap is used for cell overlap and coverage testing. Each u32 8951 ** entry represents the span of a cell or freeblock on a btree page. 8952 ** The upper 16 bits are the index of the first byte of a range and the 8953 ** lower 16 bits are the index of the last byte of that range. 8954 */ 8955 static void btreeHeapInsert(u32 *aHeap, u32 x){ 8956 u32 j, i = ++aHeap[0]; 8957 aHeap[i] = x; 8958 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ 8959 x = aHeap[j]; 8960 aHeap[j] = aHeap[i]; 8961 aHeap[i] = x; 8962 i = j; 8963 } 8964 } 8965 static int btreeHeapPull(u32 *aHeap, u32 *pOut){ 8966 u32 j, i, x; 8967 if( (x = aHeap[0])==0 ) return 0; 8968 *pOut = aHeap[1]; 8969 aHeap[1] = aHeap[x]; 8970 aHeap[x] = 0xffffffff; 8971 aHeap[0]--; 8972 i = 1; 8973 while( (j = i*2)<=aHeap[0] ){ 8974 if( aHeap[j]>aHeap[j+1] ) j++; 8975 if( aHeap[i]<aHeap[j] ) break; 8976 x = aHeap[i]; 8977 aHeap[i] = aHeap[j]; 8978 aHeap[j] = x; 8979 i = j; 8980 } 8981 return 1; 8982 } 8983 8984 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 8985 /* 8986 ** Do various sanity checks on a single page of a tree. Return 8987 ** the tree depth. Root pages return 0. Parents of root pages 8988 ** return 1, and so forth. 8989 ** 8990 ** These checks are done: 8991 ** 8992 ** 1. Make sure that cells and freeblocks do not overlap 8993 ** but combine to completely cover the page. 8994 ** 2. Make sure integer cell keys are in order. 8995 ** 3. Check the integrity of overflow pages. 8996 ** 4. Recursively call checkTreePage on all children. 8997 ** 5. Verify that the depth of all children is the same. 8998 */ 8999 static int checkTreePage( 9000 IntegrityCk *pCheck, /* Context for the sanity check */ 9001 int iPage, /* Page number of the page to check */ 9002 i64 *piMinKey, /* Write minimum integer primary key here */ 9003 i64 maxKey /* Error if integer primary key greater than this */ 9004 ){ 9005 MemPage *pPage = 0; /* The page being analyzed */ 9006 int i; /* Loop counter */ 9007 int rc; /* Result code from subroutine call */ 9008 int depth = -1, d2; /* Depth of a subtree */ 9009 int pgno; /* Page number */ 9010 int nFrag; /* Number of fragmented bytes on the page */ 9011 int hdr; /* Offset to the page header */ 9012 int cellStart; /* Offset to the start of the cell pointer array */ 9013 int nCell; /* Number of cells */ 9014 int doCoverageCheck = 1; /* True if cell coverage checking should be done */ 9015 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey 9016 ** False if IPK must be strictly less than maxKey */ 9017 u8 *data; /* Page content */ 9018 u8 *pCell; /* Cell content */ 9019 u8 *pCellIdx; /* Next element of the cell pointer array */ 9020 BtShared *pBt; /* The BtShared object that owns pPage */ 9021 u32 pc; /* Address of a cell */ 9022 u32 usableSize; /* Usable size of the page */ 9023 u32 contentOffset; /* Offset to the start of the cell content area */ 9024 u32 *heap = 0; /* Min-heap used for checking cell coverage */ 9025 u32 x, prev = 0; /* Next and previous entry on the min-heap */ 9026 const char *saved_zPfx = pCheck->zPfx; 9027 int saved_v1 = pCheck->v1; 9028 int saved_v2 = pCheck->v2; 9029 u8 savedIsInit = 0; 9030 9031 /* Check that the page exists 9032 */ 9033 pBt = pCheck->pBt; 9034 usableSize = pBt->usableSize; 9035 if( iPage==0 ) return 0; 9036 if( checkRef(pCheck, iPage) ) return 0; 9037 pCheck->zPfx = "Page %d: "; 9038 pCheck->v1 = iPage; 9039 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ 9040 checkAppendMsg(pCheck, 9041 "unable to get the page. error code=%d", rc); 9042 goto end_of_check; 9043 } 9044 9045 /* Clear MemPage.isInit to make sure the corruption detection code in 9046 ** btreeInitPage() is executed. */ 9047 savedIsInit = pPage->isInit; 9048 pPage->isInit = 0; 9049 if( (rc = btreeInitPage(pPage))!=0 ){ 9050 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ 9051 checkAppendMsg(pCheck, 9052 "btreeInitPage() returns error code %d", rc); 9053 goto end_of_check; 9054 } 9055 data = pPage->aData; 9056 hdr = pPage->hdrOffset; 9057 9058 /* Set up for cell analysis */ 9059 pCheck->zPfx = "On tree page %d cell %d: "; 9060 contentOffset = get2byteNotZero(&data[hdr+5]); 9061 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ 9062 9063 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 9064 ** number of cells on the page. */ 9065 nCell = get2byte(&data[hdr+3]); 9066 assert( pPage->nCell==nCell ); 9067 9068 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page 9069 ** immediately follows the b-tree page header. */ 9070 cellStart = hdr + 12 - 4*pPage->leaf; 9071 assert( pPage->aCellIdx==&data[cellStart] ); 9072 pCellIdx = &data[cellStart + 2*(nCell-1)]; 9073 9074 if( !pPage->leaf ){ 9075 /* Analyze the right-child page of internal pages */ 9076 pgno = get4byte(&data[hdr+8]); 9077 #ifndef SQLITE_OMIT_AUTOVACUUM 9078 if( pBt->autoVacuum ){ 9079 pCheck->zPfx = "On page %d at right child: "; 9080 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 9081 } 9082 #endif 9083 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); 9084 keyCanBeEqual = 0; 9085 }else{ 9086 /* For leaf pages, the coverage check will occur in the same loop 9087 ** as the other cell checks, so initialize the heap. */ 9088 heap = pCheck->heap; 9089 heap[0] = 0; 9090 } 9091 9092 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte 9093 ** integer offsets to the cell contents. */ 9094 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ 9095 CellInfo info; 9096 9097 /* Check cell size */ 9098 pCheck->v2 = i; 9099 assert( pCellIdx==&data[cellStart + i*2] ); 9100 pc = get2byteAligned(pCellIdx); 9101 pCellIdx -= 2; 9102 if( pc<contentOffset || pc>usableSize-4 ){ 9103 checkAppendMsg(pCheck, "Offset %d out of range %d..%d", 9104 pc, contentOffset, usableSize-4); 9105 doCoverageCheck = 0; 9106 continue; 9107 } 9108 pCell = &data[pc]; 9109 pPage->xParseCell(pPage, pCell, &info); 9110 if( pc+info.nSize>usableSize ){ 9111 checkAppendMsg(pCheck, "Extends off end of page"); 9112 doCoverageCheck = 0; 9113 continue; 9114 } 9115 9116 /* Check for integer primary key out of range */ 9117 if( pPage->intKey ){ 9118 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ 9119 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); 9120 } 9121 maxKey = info.nKey; 9122 } 9123 9124 /* Check the content overflow list */ 9125 if( info.nPayload>info.nLocal ){ 9126 int nPage; /* Number of pages on the overflow chain */ 9127 Pgno pgnoOvfl; /* First page of the overflow chain */ 9128 assert( pc + info.iOverflow <= usableSize ); 9129 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); 9130 pgnoOvfl = get4byte(&pCell[info.iOverflow]); 9131 #ifndef SQLITE_OMIT_AUTOVACUUM 9132 if( pBt->autoVacuum ){ 9133 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); 9134 } 9135 #endif 9136 checkList(pCheck, 0, pgnoOvfl, nPage); 9137 } 9138 9139 if( !pPage->leaf ){ 9140 /* Check sanity of left child page for internal pages */ 9141 pgno = get4byte(pCell); 9142 #ifndef SQLITE_OMIT_AUTOVACUUM 9143 if( pBt->autoVacuum ){ 9144 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 9145 } 9146 #endif 9147 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); 9148 keyCanBeEqual = 0; 9149 if( d2!=depth ){ 9150 checkAppendMsg(pCheck, "Child page depth differs"); 9151 depth = d2; 9152 } 9153 }else{ 9154 /* Populate the coverage-checking heap for leaf pages */ 9155 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); 9156 } 9157 } 9158 *piMinKey = maxKey; 9159 9160 /* Check for complete coverage of the page 9161 */ 9162 pCheck->zPfx = 0; 9163 if( doCoverageCheck && pCheck->mxErr>0 ){ 9164 /* For leaf pages, the min-heap has already been initialized and the 9165 ** cells have already been inserted. But for internal pages, that has 9166 ** not yet been done, so do it now */ 9167 if( !pPage->leaf ){ 9168 heap = pCheck->heap; 9169 heap[0] = 0; 9170 for(i=nCell-1; i>=0; i--){ 9171 u32 size; 9172 pc = get2byteAligned(&data[cellStart+i*2]); 9173 size = pPage->xCellSize(pPage, &data[pc]); 9174 btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); 9175 } 9176 } 9177 /* Add the freeblocks to the min-heap 9178 ** 9179 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header 9180 ** is the offset of the first freeblock, or zero if there are no 9181 ** freeblocks on the page. 9182 */ 9183 i = get2byte(&data[hdr+1]); 9184 while( i>0 ){ 9185 int size, j; 9186 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */ 9187 size = get2byte(&data[i+2]); 9188 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */ 9189 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); 9190 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a 9191 ** big-endian integer which is the offset in the b-tree page of the next 9192 ** freeblock in the chain, or zero if the freeblock is the last on the 9193 ** chain. */ 9194 j = get2byte(&data[i]); 9195 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of 9196 ** increasing offset. */ 9197 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ 9198 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */ 9199 i = j; 9200 } 9201 /* Analyze the min-heap looking for overlap between cells and/or 9202 ** freeblocks, and counting the number of untracked bytes in nFrag. 9203 ** 9204 ** Each min-heap entry is of the form: (start_address<<16)|end_address. 9205 ** There is an implied first entry the covers the page header, the cell 9206 ** pointer index, and the gap between the cell pointer index and the start 9207 ** of cell content. 9208 ** 9209 ** The loop below pulls entries from the min-heap in order and compares 9210 ** the start_address against the previous end_address. If there is an 9211 ** overlap, that means bytes are used multiple times. If there is a gap, 9212 ** that gap is added to the fragmentation count. 9213 */ 9214 nFrag = 0; 9215 prev = contentOffset - 1; /* Implied first min-heap entry */ 9216 while( btreeHeapPull(heap,&x) ){ 9217 if( (prev&0xffff)>=(x>>16) ){ 9218 checkAppendMsg(pCheck, 9219 "Multiple uses for byte %u of page %d", x>>16, iPage); 9220 break; 9221 }else{ 9222 nFrag += (x>>16) - (prev&0xffff) - 1; 9223 prev = x; 9224 } 9225 } 9226 nFrag += usableSize - (prev&0xffff) - 1; 9227 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments 9228 ** is stored in the fifth field of the b-tree page header. 9229 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the 9230 ** number of fragmented free bytes within the cell content area. 9231 */ 9232 if( heap[0]==0 && nFrag!=data[hdr+7] ){ 9233 checkAppendMsg(pCheck, 9234 "Fragmentation of %d bytes reported as %d on page %d", 9235 nFrag, data[hdr+7], iPage); 9236 } 9237 } 9238 9239 end_of_check: 9240 if( !doCoverageCheck ) pPage->isInit = savedIsInit; 9241 releasePage(pPage); 9242 pCheck->zPfx = saved_zPfx; 9243 pCheck->v1 = saved_v1; 9244 pCheck->v2 = saved_v2; 9245 return depth+1; 9246 } 9247 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 9248 9249 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9250 /* 9251 ** This routine does a complete check of the given BTree file. aRoot[] is 9252 ** an array of pages numbers were each page number is the root page of 9253 ** a table. nRoot is the number of entries in aRoot. 9254 ** 9255 ** A read-only or read-write transaction must be opened before calling 9256 ** this function. 9257 ** 9258 ** Write the number of error seen in *pnErr. Except for some memory 9259 ** allocation errors, an error message held in memory obtained from 9260 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is 9261 ** returned. If a memory allocation error occurs, NULL is returned. 9262 */ 9263 char *sqlite3BtreeIntegrityCheck( 9264 Btree *p, /* The btree to be checked */ 9265 int *aRoot, /* An array of root pages numbers for individual trees */ 9266 int nRoot, /* Number of entries in aRoot[] */ 9267 int mxErr, /* Stop reporting errors after this many */ 9268 int *pnErr /* Write number of errors seen to this variable */ 9269 ){ 9270 Pgno i; 9271 IntegrityCk sCheck; 9272 BtShared *pBt = p->pBt; 9273 int savedDbFlags = pBt->db->flags; 9274 char zErr[100]; 9275 VVA_ONLY( int nRef ); 9276 9277 sqlite3BtreeEnter(p); 9278 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); 9279 assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 ); 9280 sCheck.pBt = pBt; 9281 sCheck.pPager = pBt->pPager; 9282 sCheck.nPage = btreePagecount(sCheck.pBt); 9283 sCheck.mxErr = mxErr; 9284 sCheck.nErr = 0; 9285 sCheck.mallocFailed = 0; 9286 sCheck.zPfx = 0; 9287 sCheck.v1 = 0; 9288 sCheck.v2 = 0; 9289 sCheck.aPgRef = 0; 9290 sCheck.heap = 0; 9291 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); 9292 if( sCheck.nPage==0 ){ 9293 goto integrity_ck_cleanup; 9294 } 9295 9296 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); 9297 if( !sCheck.aPgRef ){ 9298 sCheck.mallocFailed = 1; 9299 goto integrity_ck_cleanup; 9300 } 9301 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); 9302 if( sCheck.heap==0 ){ 9303 sCheck.mallocFailed = 1; 9304 goto integrity_ck_cleanup; 9305 } 9306 9307 i = PENDING_BYTE_PAGE(pBt); 9308 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); 9309 9310 /* Check the integrity of the freelist 9311 */ 9312 sCheck.zPfx = "Main freelist: "; 9313 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), 9314 get4byte(&pBt->pPage1->aData[36])); 9315 sCheck.zPfx = 0; 9316 9317 /* Check all the tables. 9318 */ 9319 testcase( pBt->db->flags & SQLITE_CellSizeCk ); 9320 pBt->db->flags &= ~SQLITE_CellSizeCk; 9321 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ 9322 i64 notUsed; 9323 if( aRoot[i]==0 ) continue; 9324 #ifndef SQLITE_OMIT_AUTOVACUUM 9325 if( pBt->autoVacuum && aRoot[i]>1 ){ 9326 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); 9327 } 9328 #endif 9329 checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64); 9330 } 9331 pBt->db->flags = savedDbFlags; 9332 9333 /* Make sure every page in the file is referenced 9334 */ 9335 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ 9336 #ifdef SQLITE_OMIT_AUTOVACUUM 9337 if( getPageReferenced(&sCheck, i)==0 ){ 9338 checkAppendMsg(&sCheck, "Page %d is never used", i); 9339 } 9340 #else 9341 /* If the database supports auto-vacuum, make sure no tables contain 9342 ** references to pointer-map pages. 9343 */ 9344 if( getPageReferenced(&sCheck, i)==0 && 9345 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ 9346 checkAppendMsg(&sCheck, "Page %d is never used", i); 9347 } 9348 if( getPageReferenced(&sCheck, i)!=0 && 9349 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ 9350 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); 9351 } 9352 #endif 9353 } 9354 9355 /* Clean up and report errors. 9356 */ 9357 integrity_ck_cleanup: 9358 sqlite3PageFree(sCheck.heap); 9359 sqlite3_free(sCheck.aPgRef); 9360 if( sCheck.mallocFailed ){ 9361 sqlite3StrAccumReset(&sCheck.errMsg); 9362 sCheck.nErr++; 9363 } 9364 *pnErr = sCheck.nErr; 9365 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); 9366 /* Make sure this analysis did not leave any unref() pages. */ 9367 assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); 9368 sqlite3BtreeLeave(p); 9369 return sqlite3StrAccumFinish(&sCheck.errMsg); 9370 } 9371 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 9372 9373 /* 9374 ** Return the full pathname of the underlying database file. Return 9375 ** an empty string if the database is in-memory or a TEMP database. 9376 ** 9377 ** The pager filename is invariant as long as the pager is 9378 ** open so it is safe to access without the BtShared mutex. 9379 */ 9380 const char *sqlite3BtreeGetFilename(Btree *p){ 9381 assert( p->pBt->pPager!=0 ); 9382 return sqlite3PagerFilename(p->pBt->pPager, 1); 9383 } 9384 9385 /* 9386 ** Return the pathname of the journal file for this database. The return 9387 ** value of this routine is the same regardless of whether the journal file 9388 ** has been created or not. 9389 ** 9390 ** The pager journal filename is invariant as long as the pager is 9391 ** open so it is safe to access without the BtShared mutex. 9392 */ 9393 const char *sqlite3BtreeGetJournalname(Btree *p){ 9394 assert( p->pBt->pPager!=0 ); 9395 return sqlite3PagerJournalname(p->pBt->pPager); 9396 } 9397 9398 /* 9399 ** Return non-zero if a transaction is active. 9400 */ 9401 int sqlite3BtreeIsInTrans(Btree *p){ 9402 assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); 9403 return (p && (p->inTrans==TRANS_WRITE)); 9404 } 9405 9406 #ifndef SQLITE_OMIT_WAL 9407 /* 9408 ** Run a checkpoint on the Btree passed as the first argument. 9409 ** 9410 ** Return SQLITE_LOCKED if this or any other connection has an open 9411 ** transaction on the shared-cache the argument Btree is connected to. 9412 ** 9413 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. 9414 */ 9415 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ 9416 int rc = SQLITE_OK; 9417 if( p ){ 9418 BtShared *pBt = p->pBt; 9419 sqlite3BtreeEnter(p); 9420 if( pBt->inTransaction!=TRANS_NONE ){ 9421 rc = SQLITE_LOCKED; 9422 }else{ 9423 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt); 9424 } 9425 sqlite3BtreeLeave(p); 9426 } 9427 return rc; 9428 } 9429 #endif 9430 9431 /* 9432 ** Return non-zero if a read (or write) transaction is active. 9433 */ 9434 int sqlite3BtreeIsInReadTrans(Btree *p){ 9435 assert( p ); 9436 assert( sqlite3_mutex_held(p->db->mutex) ); 9437 return p->inTrans!=TRANS_NONE; 9438 } 9439 9440 int sqlite3BtreeIsInBackup(Btree *p){ 9441 assert( p ); 9442 assert( sqlite3_mutex_held(p->db->mutex) ); 9443 return p->nBackup!=0; 9444 } 9445 9446 /* 9447 ** This function returns a pointer to a blob of memory associated with 9448 ** a single shared-btree. The memory is used by client code for its own 9449 ** purposes (for example, to store a high-level schema associated with 9450 ** the shared-btree). The btree layer manages reference counting issues. 9451 ** 9452 ** The first time this is called on a shared-btree, nBytes bytes of memory 9453 ** are allocated, zeroed, and returned to the caller. For each subsequent 9454 ** call the nBytes parameter is ignored and a pointer to the same blob 9455 ** of memory returned. 9456 ** 9457 ** If the nBytes parameter is 0 and the blob of memory has not yet been 9458 ** allocated, a null pointer is returned. If the blob has already been 9459 ** allocated, it is returned as normal. 9460 ** 9461 ** Just before the shared-btree is closed, the function passed as the 9462 ** xFree argument when the memory allocation was made is invoked on the 9463 ** blob of allocated memory. The xFree function should not call sqlite3_free() 9464 ** on the memory, the btree layer does that. 9465 */ 9466 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ 9467 BtShared *pBt = p->pBt; 9468 sqlite3BtreeEnter(p); 9469 if( !pBt->pSchema && nBytes ){ 9470 pBt->pSchema = sqlite3DbMallocZero(0, nBytes); 9471 pBt->xFreeSchema = xFree; 9472 } 9473 sqlite3BtreeLeave(p); 9474 return pBt->pSchema; 9475 } 9476 9477 /* 9478 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 9479 ** btree as the argument handle holds an exclusive lock on the 9480 ** sqlite_master table. Otherwise SQLITE_OK. 9481 */ 9482 int sqlite3BtreeSchemaLocked(Btree *p){ 9483 int rc; 9484 assert( sqlite3_mutex_held(p->db->mutex) ); 9485 sqlite3BtreeEnter(p); 9486 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); 9487 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); 9488 sqlite3BtreeLeave(p); 9489 return rc; 9490 } 9491 9492 9493 #ifndef SQLITE_OMIT_SHARED_CACHE 9494 /* 9495 ** Obtain a lock on the table whose root page is iTab. The 9496 ** lock is a write lock if isWritelock is true or a read lock 9497 ** if it is false. 9498 */ 9499 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ 9500 int rc = SQLITE_OK; 9501 assert( p->inTrans!=TRANS_NONE ); 9502 if( p->sharable ){ 9503 u8 lockType = READ_LOCK + isWriteLock; 9504 assert( READ_LOCK+1==WRITE_LOCK ); 9505 assert( isWriteLock==0 || isWriteLock==1 ); 9506 9507 sqlite3BtreeEnter(p); 9508 rc = querySharedCacheTableLock(p, iTab, lockType); 9509 if( rc==SQLITE_OK ){ 9510 rc = setSharedCacheTableLock(p, iTab, lockType); 9511 } 9512 sqlite3BtreeLeave(p); 9513 } 9514 return rc; 9515 } 9516 #endif 9517 9518 #ifndef SQLITE_OMIT_INCRBLOB 9519 /* 9520 ** Argument pCsr must be a cursor opened for writing on an 9521 ** INTKEY table currently pointing at a valid table entry. 9522 ** This function modifies the data stored as part of that entry. 9523 ** 9524 ** Only the data content may only be modified, it is not possible to 9525 ** change the length of the data stored. If this function is called with 9526 ** parameters that attempt to write past the end of the existing data, 9527 ** no modifications are made and SQLITE_CORRUPT is returned. 9528 */ 9529 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ 9530 int rc; 9531 assert( cursorHoldsMutex(pCsr) ); 9532 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); 9533 assert( pCsr->curFlags & BTCF_Incrblob ); 9534 9535 rc = restoreCursorPosition(pCsr); 9536 if( rc!=SQLITE_OK ){ 9537 return rc; 9538 } 9539 assert( pCsr->eState!=CURSOR_REQUIRESEEK ); 9540 if( pCsr->eState!=CURSOR_VALID ){ 9541 return SQLITE_ABORT; 9542 } 9543 9544 /* Save the positions of all other cursors open on this table. This is 9545 ** required in case any of them are holding references to an xFetch 9546 ** version of the b-tree page modified by the accessPayload call below. 9547 ** 9548 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() 9549 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence 9550 ** saveAllCursors can only return SQLITE_OK. 9551 */ 9552 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); 9553 assert( rc==SQLITE_OK ); 9554 9555 /* Check some assumptions: 9556 ** (a) the cursor is open for writing, 9557 ** (b) there is a read/write transaction open, 9558 ** (c) the connection holds a write-lock on the table (if required), 9559 ** (d) there are no conflicting read-locks, and 9560 ** (e) the cursor points at a valid row of an intKey table. 9561 */ 9562 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ 9563 return SQLITE_READONLY; 9564 } 9565 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 9566 && pCsr->pBt->inTransaction==TRANS_WRITE ); 9567 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); 9568 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); 9569 assert( pCsr->apPage[pCsr->iPage]->intKey ); 9570 9571 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); 9572 } 9573 9574 /* 9575 ** Mark this cursor as an incremental blob cursor. 9576 */ 9577 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ 9578 pCur->curFlags |= BTCF_Incrblob; 9579 pCur->pBtree->hasIncrblobCur = 1; 9580 } 9581 #endif 9582 9583 /* 9584 ** Set both the "read version" (single byte at byte offset 18) and 9585 ** "write version" (single byte at byte offset 19) fields in the database 9586 ** header to iVersion. 9587 */ 9588 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ 9589 BtShared *pBt = pBtree->pBt; 9590 int rc; /* Return code */ 9591 9592 assert( iVersion==1 || iVersion==2 ); 9593 9594 /* If setting the version fields to 1, do not automatically open the 9595 ** WAL connection, even if the version fields are currently set to 2. 9596 */ 9597 pBt->btsFlags &= ~BTS_NO_WAL; 9598 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; 9599 9600 rc = sqlite3BtreeBeginTrans(pBtree, 0); 9601 if( rc==SQLITE_OK ){ 9602 u8 *aData = pBt->pPage1->aData; 9603 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ 9604 rc = sqlite3BtreeBeginTrans(pBtree, 2); 9605 if( rc==SQLITE_OK ){ 9606 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 9607 if( rc==SQLITE_OK ){ 9608 aData[18] = (u8)iVersion; 9609 aData[19] = (u8)iVersion; 9610 } 9611 } 9612 } 9613 } 9614 9615 pBt->btsFlags &= ~BTS_NO_WAL; 9616 return rc; 9617 } 9618 9619 /* 9620 ** set the mask of hint flags for cursor pCsr. 9621 */ 9622 void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){ 9623 assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 ); 9624 pCsr->hints = mask; 9625 } 9626 9627 #ifdef SQLITE_DEBUG 9628 /* 9629 ** Return true if the cursor has a hint specified. This routine is 9630 ** only used from within assert() statements 9631 */ 9632 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ 9633 return (pCsr->hints & mask)!=0; 9634 } 9635 #endif 9636 9637 /* 9638 ** Return true if the given Btree is read-only. 9639 */ 9640 int sqlite3BtreeIsReadonly(Btree *p){ 9641 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; 9642 } 9643 9644 /* 9645 ** Return the size of the header added to each page by this module. 9646 */ 9647 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } 9648