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