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