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