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