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