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