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_MAIN. 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 #ifdef SQLITE_DEBUG 116 /* 117 ** Return and reset the seek counter for a Btree object. 118 */ 119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){ 120 u64 n = pBt->nSeek; 121 pBt->nSeek = 0; 122 return n; 123 } 124 #endif 125 126 /* 127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single 128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL. 129 ** 130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to 131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message 132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented 133 ** with the page number and filename associated with the (MemPage*). 134 */ 135 #ifdef SQLITE_DEBUG 136 int corruptPageError(int lineno, MemPage *p){ 137 char *zMsg; 138 sqlite3BeginBenignMalloc(); 139 zMsg = sqlite3_mprintf("database corruption page %d of %s", 140 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0) 141 ); 142 sqlite3EndBenignMalloc(); 143 if( zMsg ){ 144 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); 145 } 146 sqlite3_free(zMsg); 147 return SQLITE_CORRUPT_BKPT; 148 } 149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage) 150 #else 151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno) 152 #endif 153 154 #ifndef SQLITE_OMIT_SHARED_CACHE 155 156 #ifdef SQLITE_DEBUG 157 /* 158 **** This function is only used as part of an assert() statement. *** 159 ** 160 ** Check to see if pBtree holds the required locks to read or write to the 161 ** table with root page iRoot. Return 1 if it does and 0 if not. 162 ** 163 ** For example, when writing to a table with root-page iRoot via 164 ** Btree connection pBtree: 165 ** 166 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); 167 ** 168 ** When writing to an index that resides in a sharable database, the 169 ** caller should have first obtained a lock specifying the root page of 170 ** the corresponding table. This makes things a bit more complicated, 171 ** as this module treats each table as a separate structure. To determine 172 ** the table corresponding to the index being written, this 173 ** function has to search through the database schema. 174 ** 175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may 176 ** hold a write-lock on the schema table (root page 1). This is also 177 ** acceptable. 178 */ 179 static int hasSharedCacheTableLock( 180 Btree *pBtree, /* Handle that must hold lock */ 181 Pgno iRoot, /* Root page of b-tree */ 182 int isIndex, /* True if iRoot is the root of an index b-tree */ 183 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ 184 ){ 185 Schema *pSchema = (Schema *)pBtree->pBt->pSchema; 186 Pgno iTab = 0; 187 BtLock *pLock; 188 189 /* If this database is not shareable, or if the client is reading 190 ** and has the read-uncommitted flag set, then no lock is required. 191 ** Return true immediately. 192 */ 193 if( (pBtree->sharable==0) 194 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit)) 195 ){ 196 return 1; 197 } 198 199 /* If the client is reading or writing an index and the schema is 200 ** not loaded, then it is too difficult to actually check to see if 201 ** the correct locks are held. So do not bother - just return true. 202 ** This case does not come up very often anyhow. 203 */ 204 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ 205 return 1; 206 } 207 208 /* Figure out the root-page that the lock should be held on. For table 209 ** b-trees, this is just the root page of the b-tree being read or 210 ** written. For index b-trees, it is the root page of the associated 211 ** table. */ 212 if( isIndex ){ 213 HashElem *p; 214 int bSeen = 0; 215 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ 216 Index *pIdx = (Index *)sqliteHashData(p); 217 if( pIdx->tnum==(int)iRoot ){ 218 if( bSeen ){ 219 /* Two or more indexes share the same root page. There must 220 ** be imposter tables. So just return true. The assert is not 221 ** useful in that case. */ 222 return 1; 223 } 224 iTab = pIdx->pTable->tnum; 225 bSeen = 1; 226 } 227 } 228 }else{ 229 iTab = iRoot; 230 } 231 232 /* Search for the required lock. Either a write-lock on root-page iTab, a 233 ** write-lock on the schema table, or (if the client is reading) a 234 ** read-lock on iTab will suffice. Return 1 if any of these are found. */ 235 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ 236 if( pLock->pBtree==pBtree 237 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) 238 && pLock->eLock>=eLockType 239 ){ 240 return 1; 241 } 242 } 243 244 /* Failed to find the required lock. */ 245 return 0; 246 } 247 #endif /* SQLITE_DEBUG */ 248 249 #ifdef SQLITE_DEBUG 250 /* 251 **** This function may be used as part of assert() statements only. **** 252 ** 253 ** Return true if it would be illegal for pBtree to write into the 254 ** table or index rooted at iRoot because other shared connections are 255 ** simultaneously reading that same table or index. 256 ** 257 ** It is illegal for pBtree to write if some other Btree object that 258 ** shares the same BtShared object is currently reading or writing 259 ** the iRoot table. Except, if the other Btree object has the 260 ** read-uncommitted flag set, then it is OK for the other object to 261 ** have a read cursor. 262 ** 263 ** For example, before writing to any part of the table or index 264 ** rooted at page iRoot, one should call: 265 ** 266 ** assert( !hasReadConflicts(pBtree, iRoot) ); 267 */ 268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ 269 BtCursor *p; 270 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 271 if( p->pgnoRoot==iRoot 272 && p->pBtree!=pBtree 273 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit) 274 ){ 275 return 1; 276 } 277 } 278 return 0; 279 } 280 #endif /* #ifdef SQLITE_DEBUG */ 281 282 /* 283 ** Query to see if Btree handle p may obtain a lock of type eLock 284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return 285 ** SQLITE_OK if the lock may be obtained (by calling 286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. 287 */ 288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ 289 BtShared *pBt = p->pBt; 290 BtLock *pIter; 291 292 assert( sqlite3BtreeHoldsMutex(p) ); 293 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 294 assert( p->db!=0 ); 295 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 ); 296 297 /* If requesting a write-lock, then the Btree must have an open write 298 ** transaction on this file. And, obviously, for this to be so there 299 ** must be an open write transaction on the file itself. 300 */ 301 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); 302 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); 303 304 /* This routine is a no-op if the shared-cache is not enabled */ 305 if( !p->sharable ){ 306 return SQLITE_OK; 307 } 308 309 /* If some other connection is holding an exclusive lock, the 310 ** requested lock may not be obtained. 311 */ 312 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ 313 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); 314 return SQLITE_LOCKED_SHAREDCACHE; 315 } 316 317 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 318 /* The condition (pIter->eLock!=eLock) in the following if(...) 319 ** statement is a simplification of: 320 ** 321 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) 322 ** 323 ** since we know that if eLock==WRITE_LOCK, then no other connection 324 ** may hold a WRITE_LOCK on any table in this file (since there can 325 ** only be a single writer). 326 */ 327 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); 328 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); 329 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ 330 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); 331 if( eLock==WRITE_LOCK ){ 332 assert( p==pBt->pWriter ); 333 pBt->btsFlags |= BTS_PENDING; 334 } 335 return SQLITE_LOCKED_SHAREDCACHE; 336 } 337 } 338 return SQLITE_OK; 339 } 340 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 341 342 #ifndef SQLITE_OMIT_SHARED_CACHE 343 /* 344 ** Add a lock on the table with root-page iTable to the shared-btree used 345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 346 ** WRITE_LOCK. 347 ** 348 ** This function assumes the following: 349 ** 350 ** (a) The specified Btree object p is connected to a sharable 351 ** database (one with the BtShared.sharable flag set), and 352 ** 353 ** (b) No other Btree objects hold a lock that conflicts 354 ** with the requested lock (i.e. querySharedCacheTableLock() has 355 ** already been called and returned SQLITE_OK). 356 ** 357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 358 ** is returned if a malloc attempt fails. 359 */ 360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ 361 BtShared *pBt = p->pBt; 362 BtLock *pLock = 0; 363 BtLock *pIter; 364 365 assert( sqlite3BtreeHoldsMutex(p) ); 366 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 367 assert( p->db!=0 ); 368 369 /* A connection with the read-uncommitted flag set will never try to 370 ** obtain a read-lock using this function. The only read-lock obtained 371 ** by a connection in read-uncommitted mode is on the sqlite_schema 372 ** table, and that lock is obtained in BtreeBeginTrans(). */ 373 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK ); 374 375 /* This function should only be called on a sharable b-tree after it 376 ** has been determined that no other b-tree holds a conflicting lock. */ 377 assert( p->sharable ); 378 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); 379 380 /* First search the list for an existing lock on this table. */ 381 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 382 if( pIter->iTable==iTable && pIter->pBtree==p ){ 383 pLock = pIter; 384 break; 385 } 386 } 387 388 /* If the above search did not find a BtLock struct associating Btree p 389 ** with table iTable, allocate one and link it into the list. 390 */ 391 if( !pLock ){ 392 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); 393 if( !pLock ){ 394 return SQLITE_NOMEM_BKPT; 395 } 396 pLock->iTable = iTable; 397 pLock->pBtree = p; 398 pLock->pNext = pBt->pLock; 399 pBt->pLock = pLock; 400 } 401 402 /* Set the BtLock.eLock variable to the maximum of the current lock 403 ** and the requested lock. This means if a write-lock was already held 404 ** and a read-lock requested, we don't incorrectly downgrade the lock. 405 */ 406 assert( WRITE_LOCK>READ_LOCK ); 407 if( eLock>pLock->eLock ){ 408 pLock->eLock = eLock; 409 } 410 411 return SQLITE_OK; 412 } 413 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 414 415 #ifndef SQLITE_OMIT_SHARED_CACHE 416 /* 417 ** Release all the table locks (locks obtained via calls to 418 ** the setSharedCacheTableLock() procedure) held by Btree object p. 419 ** 420 ** This function assumes that Btree p has an open read or write 421 ** transaction. If it does not, then the BTS_PENDING flag 422 ** may be incorrectly cleared. 423 */ 424 static void clearAllSharedCacheTableLocks(Btree *p){ 425 BtShared *pBt = p->pBt; 426 BtLock **ppIter = &pBt->pLock; 427 428 assert( sqlite3BtreeHoldsMutex(p) ); 429 assert( p->sharable || 0==*ppIter ); 430 assert( p->inTrans>0 ); 431 432 while( *ppIter ){ 433 BtLock *pLock = *ppIter; 434 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); 435 assert( pLock->pBtree->inTrans>=pLock->eLock ); 436 if( pLock->pBtree==p ){ 437 *ppIter = pLock->pNext; 438 assert( pLock->iTable!=1 || pLock==&p->lock ); 439 if( pLock->iTable!=1 ){ 440 sqlite3_free(pLock); 441 } 442 }else{ 443 ppIter = &pLock->pNext; 444 } 445 } 446 447 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); 448 if( pBt->pWriter==p ){ 449 pBt->pWriter = 0; 450 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 451 }else if( pBt->nTransaction==2 ){ 452 /* This function is called when Btree p is concluding its 453 ** transaction. If there currently exists a writer, and p is not 454 ** that writer, then the number of locks held by connections other 455 ** than the writer must be about to drop to zero. In this case 456 ** set the BTS_PENDING flag to 0. 457 ** 458 ** If there is not currently a writer, then BTS_PENDING must 459 ** be zero already. So this next line is harmless in that case. 460 */ 461 pBt->btsFlags &= ~BTS_PENDING; 462 } 463 } 464 465 /* 466 ** This function changes all write-locks held by Btree p into read-locks. 467 */ 468 static void downgradeAllSharedCacheTableLocks(Btree *p){ 469 BtShared *pBt = p->pBt; 470 if( pBt->pWriter==p ){ 471 BtLock *pLock; 472 pBt->pWriter = 0; 473 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 474 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ 475 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); 476 pLock->eLock = READ_LOCK; 477 } 478 } 479 } 480 481 #endif /* SQLITE_OMIT_SHARED_CACHE */ 482 483 static void releasePage(MemPage *pPage); /* Forward reference */ 484 static void releasePageOne(MemPage *pPage); /* Forward reference */ 485 static void releasePageNotNull(MemPage *pPage); /* Forward reference */ 486 487 /* 488 ***** This routine is used inside of assert() only **** 489 ** 490 ** Verify that the cursor holds the mutex on its BtShared 491 */ 492 #ifdef SQLITE_DEBUG 493 static int cursorHoldsMutex(BtCursor *p){ 494 return sqlite3_mutex_held(p->pBt->mutex); 495 } 496 497 /* Verify that the cursor and the BtShared agree about what is the current 498 ** database connetion. This is important in shared-cache mode. If the database 499 ** connection pointers get out-of-sync, it is possible for routines like 500 ** btreeInitPage() to reference an stale connection pointer that references a 501 ** a connection that has already closed. This routine is used inside assert() 502 ** statements only and for the purpose of double-checking that the btree code 503 ** does keep the database connection pointers up-to-date. 504 */ 505 static int cursorOwnsBtShared(BtCursor *p){ 506 assert( cursorHoldsMutex(p) ); 507 return (p->pBtree->db==p->pBt->db); 508 } 509 #endif 510 511 /* 512 ** Invalidate the overflow cache of the cursor passed as the first argument. 513 ** on the shared btree structure pBt. 514 */ 515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) 516 517 /* 518 ** Invalidate the overflow page-list cache for all cursors opened 519 ** on the shared btree structure pBt. 520 */ 521 static void invalidateAllOverflowCache(BtShared *pBt){ 522 BtCursor *p; 523 assert( sqlite3_mutex_held(pBt->mutex) ); 524 for(p=pBt->pCursor; p; p=p->pNext){ 525 invalidateOverflowCache(p); 526 } 527 } 528 529 #ifndef SQLITE_OMIT_INCRBLOB 530 /* 531 ** This function is called before modifying the contents of a table 532 ** to invalidate any incrblob cursors that are open on the 533 ** row or one of the rows being modified. 534 ** 535 ** If argument isClearTable is true, then the entire contents of the 536 ** table is about to be deleted. In this case invalidate all incrblob 537 ** cursors open on any row within the table with root-page pgnoRoot. 538 ** 539 ** Otherwise, if argument isClearTable is false, then the row with 540 ** rowid iRow is being replaced or deleted. In this case invalidate 541 ** only those incrblob cursors open on that specific row. 542 */ 543 static void invalidateIncrblobCursors( 544 Btree *pBtree, /* The database file to check */ 545 Pgno pgnoRoot, /* The table that might be changing */ 546 i64 iRow, /* The rowid that might be changing */ 547 int isClearTable /* True if all rows are being deleted */ 548 ){ 549 BtCursor *p; 550 assert( pBtree->hasIncrblobCur ); 551 assert( sqlite3BtreeHoldsMutex(pBtree) ); 552 pBtree->hasIncrblobCur = 0; 553 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 554 if( (p->curFlags & BTCF_Incrblob)!=0 ){ 555 pBtree->hasIncrblobCur = 1; 556 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){ 557 p->eState = CURSOR_INVALID; 558 } 559 } 560 } 561 } 562 563 #else 564 /* Stub function when INCRBLOB is omitted */ 565 #define invalidateIncrblobCursors(w,x,y,z) 566 #endif /* SQLITE_OMIT_INCRBLOB */ 567 568 /* 569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 570 ** when a page that previously contained data becomes a free-list leaf 571 ** page. 572 ** 573 ** The BtShared.pHasContent bitvec exists to work around an obscure 574 ** bug caused by the interaction of two useful IO optimizations surrounding 575 ** free-list leaf pages: 576 ** 577 ** 1) When all data is deleted from a page and the page becomes 578 ** a free-list leaf page, the page is not written to the database 579 ** (as free-list leaf pages contain no meaningful data). Sometimes 580 ** such a page is not even journalled (as it will not be modified, 581 ** why bother journalling it?). 582 ** 583 ** 2) When a free-list leaf page is reused, its content is not read 584 ** from the database or written to the journal file (why should it 585 ** be, if it is not at all meaningful?). 586 ** 587 ** By themselves, these optimizations work fine and provide a handy 588 ** performance boost to bulk delete or insert operations. However, if 589 ** a page is moved to the free-list and then reused within the same 590 ** transaction, a problem comes up. If the page is not journalled when 591 ** it is moved to the free-list and it is also not journalled when it 592 ** is extracted from the free-list and reused, then the original data 593 ** may be lost. In the event of a rollback, it may not be possible 594 ** to restore the database to its original configuration. 595 ** 596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 597 ** moved to become a free-list leaf page, the corresponding bit is 598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list, 599 ** optimization 2 above is omitted if the corresponding bit is already 600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared 601 ** at the end of every transaction. 602 */ 603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ 604 int rc = SQLITE_OK; 605 if( !pBt->pHasContent ){ 606 assert( pgno<=pBt->nPage ); 607 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); 608 if( !pBt->pHasContent ){ 609 rc = SQLITE_NOMEM_BKPT; 610 } 611 } 612 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ 613 rc = sqlite3BitvecSet(pBt->pHasContent, pgno); 614 } 615 return rc; 616 } 617 618 /* 619 ** Query the BtShared.pHasContent vector. 620 ** 621 ** This function is called when a free-list leaf page is removed from the 622 ** free-list for reuse. It returns false if it is safe to retrieve the 623 ** page from the pager layer with the 'no-content' flag set. True otherwise. 624 */ 625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ 626 Bitvec *p = pBt->pHasContent; 627 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno)); 628 } 629 630 /* 631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be 632 ** invoked at the conclusion of each write-transaction. 633 */ 634 static void btreeClearHasContent(BtShared *pBt){ 635 sqlite3BitvecDestroy(pBt->pHasContent); 636 pBt->pHasContent = 0; 637 } 638 639 /* 640 ** Release all of the apPage[] pages for a cursor. 641 */ 642 static void btreeReleaseAllCursorPages(BtCursor *pCur){ 643 int i; 644 if( pCur->iPage>=0 ){ 645 for(i=0; i<pCur->iPage; i++){ 646 releasePageNotNull(pCur->apPage[i]); 647 } 648 releasePageNotNull(pCur->pPage); 649 pCur->iPage = -1; 650 } 651 } 652 653 /* 654 ** The cursor passed as the only argument must point to a valid entry 655 ** when this function is called (i.e. have eState==CURSOR_VALID). This 656 ** function saves the current cursor key in variables pCur->nKey and 657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 658 ** code otherwise. 659 ** 660 ** If the cursor is open on an intkey table, then the integer key 661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to 662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 663 ** set to point to a malloced buffer pCur->nKey bytes in size containing 664 ** the key. 665 */ 666 static int saveCursorKey(BtCursor *pCur){ 667 int rc = SQLITE_OK; 668 assert( CURSOR_VALID==pCur->eState ); 669 assert( 0==pCur->pKey ); 670 assert( cursorHoldsMutex(pCur) ); 671 672 if( pCur->curIntKey ){ 673 /* Only the rowid is required for a table btree */ 674 pCur->nKey = sqlite3BtreeIntegerKey(pCur); 675 }else{ 676 /* For an index btree, save the complete key content. It is possible 677 ** that the current key is corrupt. In that case, it is possible that 678 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by 679 ** up to the size of 1 varint plus 1 8-byte value when the cursor 680 ** position is restored. Hence the 17 bytes of padding allocated 681 ** below. */ 682 void *pKey; 683 pCur->nKey = sqlite3BtreePayloadSize(pCur); 684 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 ); 685 if( pKey ){ 686 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); 687 if( rc==SQLITE_OK ){ 688 memset(((u8*)pKey)+pCur->nKey, 0, 9+8); 689 pCur->pKey = pKey; 690 }else{ 691 sqlite3_free(pKey); 692 } 693 }else{ 694 rc = SQLITE_NOMEM_BKPT; 695 } 696 } 697 assert( !pCur->curIntKey || !pCur->pKey ); 698 return rc; 699 } 700 701 /* 702 ** Save the current cursor position in the variables BtCursor.nKey 703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. 704 ** 705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) 706 ** prior to calling this routine. 707 */ 708 static int saveCursorPosition(BtCursor *pCur){ 709 int rc; 710 711 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); 712 assert( 0==pCur->pKey ); 713 assert( cursorHoldsMutex(pCur) ); 714 715 if( pCur->curFlags & BTCF_Pinned ){ 716 return SQLITE_CONSTRAINT_PINNED; 717 } 718 if( pCur->eState==CURSOR_SKIPNEXT ){ 719 pCur->eState = CURSOR_VALID; 720 }else{ 721 pCur->skipNext = 0; 722 } 723 724 rc = saveCursorKey(pCur); 725 if( rc==SQLITE_OK ){ 726 btreeReleaseAllCursorPages(pCur); 727 pCur->eState = CURSOR_REQUIRESEEK; 728 } 729 730 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); 731 return rc; 732 } 733 734 /* Forward reference */ 735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); 736 737 /* 738 ** Save the positions of all cursors (except pExcept) that are open on 739 ** the table with root-page iRoot. "Saving the cursor position" means that 740 ** the location in the btree is remembered in such a way that it can be 741 ** moved back to the same spot after the btree has been modified. This 742 ** routine is called just before cursor pExcept is used to modify the 743 ** table, for example in BtreeDelete() or BtreeInsert(). 744 ** 745 ** If there are two or more cursors on the same btree, then all such 746 ** cursors should have their BTCF_Multiple flag set. The btreeCursor() 747 ** routine enforces that rule. This routine only needs to be called in 748 ** the uncommon case when pExpect has the BTCF_Multiple flag set. 749 ** 750 ** If pExpect!=NULL and if no other cursors are found on the same root-page, 751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another 752 ** pointless call to this routine. 753 ** 754 ** Implementation note: This routine merely checks to see if any cursors 755 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) 756 ** event that cursors are in need to being saved. 757 */ 758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ 759 BtCursor *p; 760 assert( sqlite3_mutex_held(pBt->mutex) ); 761 assert( pExcept==0 || pExcept->pBt==pBt ); 762 for(p=pBt->pCursor; p; p=p->pNext){ 763 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; 764 } 765 if( p ) return saveCursorsOnList(p, iRoot, pExcept); 766 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; 767 return SQLITE_OK; 768 } 769 770 /* This helper routine to saveAllCursors does the actual work of saving 771 ** the cursors if and when a cursor is found that actually requires saving. 772 ** The common case is that no cursors need to be saved, so this routine is 773 ** broken out from its caller to avoid unnecessary stack pointer movement. 774 */ 775 static int SQLITE_NOINLINE saveCursorsOnList( 776 BtCursor *p, /* The first cursor that needs saving */ 777 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ 778 BtCursor *pExcept /* Do not save this cursor */ 779 ){ 780 do{ 781 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ 782 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 783 int rc = saveCursorPosition(p); 784 if( SQLITE_OK!=rc ){ 785 return rc; 786 } 787 }else{ 788 testcase( p->iPage>=0 ); 789 btreeReleaseAllCursorPages(p); 790 } 791 } 792 p = p->pNext; 793 }while( p ); 794 return SQLITE_OK; 795 } 796 797 /* 798 ** Clear the current cursor position. 799 */ 800 void sqlite3BtreeClearCursor(BtCursor *pCur){ 801 assert( cursorHoldsMutex(pCur) ); 802 sqlite3_free(pCur->pKey); 803 pCur->pKey = 0; 804 pCur->eState = CURSOR_INVALID; 805 } 806 807 /* 808 ** In this version of BtreeMoveto, pKey is a packed index record 809 ** such as is generated by the OP_MakeRecord opcode. Unpack the 810 ** record and then call BtreeMovetoUnpacked() to do the work. 811 */ 812 static int btreeMoveto( 813 BtCursor *pCur, /* Cursor open on the btree to be searched */ 814 const void *pKey, /* Packed key if the btree is an index */ 815 i64 nKey, /* Integer key for tables. Size of pKey for indices */ 816 int bias, /* Bias search to the high end */ 817 int *pRes /* Write search results here */ 818 ){ 819 int rc; /* Status code */ 820 UnpackedRecord *pIdxKey; /* Unpacked index key */ 821 822 if( pKey ){ 823 KeyInfo *pKeyInfo = pCur->pKeyInfo; 824 assert( nKey==(i64)(int)nKey ); 825 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); 826 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; 827 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); 828 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ 829 rc = SQLITE_CORRUPT_BKPT; 830 }else{ 831 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes); 832 } 833 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); 834 }else{ 835 pIdxKey = 0; 836 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes); 837 } 838 return rc; 839 } 840 841 /* 842 ** Restore the cursor to the position it was in (or as close to as possible) 843 ** when saveCursorPosition() was called. Note that this call deletes the 844 ** saved position info stored by saveCursorPosition(), so there can be 845 ** at most one effective restoreCursorPosition() call after each 846 ** saveCursorPosition(). 847 */ 848 static int btreeRestoreCursorPosition(BtCursor *pCur){ 849 int rc; 850 int skipNext = 0; 851 assert( cursorOwnsBtShared(pCur) ); 852 assert( pCur->eState>=CURSOR_REQUIRESEEK ); 853 if( pCur->eState==CURSOR_FAULT ){ 854 return pCur->skipNext; 855 } 856 pCur->eState = CURSOR_INVALID; 857 if( sqlite3FaultSim(410) ){ 858 rc = SQLITE_IOERR; 859 }else{ 860 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); 861 } 862 if( rc==SQLITE_OK ){ 863 sqlite3_free(pCur->pKey); 864 pCur->pKey = 0; 865 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); 866 if( skipNext ) pCur->skipNext = skipNext; 867 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ 868 pCur->eState = CURSOR_SKIPNEXT; 869 } 870 } 871 return rc; 872 } 873 874 #define restoreCursorPosition(p) \ 875 (p->eState>=CURSOR_REQUIRESEEK ? \ 876 btreeRestoreCursorPosition(p) : \ 877 SQLITE_OK) 878 879 /* 880 ** Determine whether or not a cursor has moved from the position where 881 ** it was last placed, or has been invalidated for any other reason. 882 ** Cursors can move when the row they are pointing at is deleted out 883 ** from under them, for example. Cursor might also move if a btree 884 ** is rebalanced. 885 ** 886 ** Calling this routine with a NULL cursor pointer returns false. 887 ** 888 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor 889 ** back to where it ought to be if this routine returns true. 890 */ 891 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ 892 assert( EIGHT_BYTE_ALIGNMENT(pCur) 893 || pCur==sqlite3BtreeFakeValidCursor() ); 894 assert( offsetof(BtCursor, eState)==0 ); 895 assert( sizeof(pCur->eState)==1 ); 896 return CURSOR_VALID != *(u8*)pCur; 897 } 898 899 /* 900 ** Return a pointer to a fake BtCursor object that will always answer 901 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake 902 ** cursor returned must not be used with any other Btree interface. 903 */ 904 BtCursor *sqlite3BtreeFakeValidCursor(void){ 905 static u8 fakeCursor = CURSOR_VALID; 906 assert( offsetof(BtCursor, eState)==0 ); 907 return (BtCursor*)&fakeCursor; 908 } 909 910 /* 911 ** This routine restores a cursor back to its original position after it 912 ** has been moved by some outside activity (such as a btree rebalance or 913 ** a row having been deleted out from under the cursor). 914 ** 915 ** On success, the *pDifferentRow parameter is false if the cursor is left 916 ** pointing at exactly the same row. *pDifferntRow is the row the cursor 917 ** was pointing to has been deleted, forcing the cursor to point to some 918 ** nearby row. 919 ** 920 ** This routine should only be called for a cursor that just returned 921 ** TRUE from sqlite3BtreeCursorHasMoved(). 922 */ 923 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ 924 int rc; 925 926 assert( pCur!=0 ); 927 assert( pCur->eState!=CURSOR_VALID ); 928 rc = restoreCursorPosition(pCur); 929 if( rc ){ 930 *pDifferentRow = 1; 931 return rc; 932 } 933 if( pCur->eState!=CURSOR_VALID ){ 934 *pDifferentRow = 1; 935 }else{ 936 *pDifferentRow = 0; 937 } 938 return SQLITE_OK; 939 } 940 941 #ifdef SQLITE_ENABLE_CURSOR_HINTS 942 /* 943 ** Provide hints to the cursor. The particular hint given (and the type 944 ** and number of the varargs parameters) is determined by the eHintType 945 ** parameter. See the definitions of the BTREE_HINT_* macros for details. 946 */ 947 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ 948 /* Used only by system that substitute their own storage engine */ 949 } 950 #endif 951 952 /* 953 ** Provide flag hints to the cursor. 954 */ 955 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ 956 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); 957 pCur->hints = x; 958 } 959 960 961 #ifndef SQLITE_OMIT_AUTOVACUUM 962 /* 963 ** Given a page number of a regular database page, return the page 964 ** number for the pointer-map page that contains the entry for the 965 ** input page number. 966 ** 967 ** Return 0 (not a valid page) for pgno==1 since there is 968 ** no pointer map associated with page 1. The integrity_check logic 969 ** requires that ptrmapPageno(*,1)!=1. 970 */ 971 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ 972 int nPagesPerMapPage; 973 Pgno iPtrMap, ret; 974 assert( sqlite3_mutex_held(pBt->mutex) ); 975 if( pgno<2 ) return 0; 976 nPagesPerMapPage = (pBt->usableSize/5)+1; 977 iPtrMap = (pgno-2)/nPagesPerMapPage; 978 ret = (iPtrMap*nPagesPerMapPage) + 2; 979 if( ret==PENDING_BYTE_PAGE(pBt) ){ 980 ret++; 981 } 982 return ret; 983 } 984 985 /* 986 ** Write an entry into the pointer map. 987 ** 988 ** This routine updates the pointer map entry for page number 'key' 989 ** so that it maps to type 'eType' and parent page number 'pgno'. 990 ** 991 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is 992 ** a no-op. If an error occurs, the appropriate error code is written 993 ** into *pRC. 994 */ 995 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ 996 DbPage *pDbPage; /* The pointer map page */ 997 u8 *pPtrmap; /* The pointer map data */ 998 Pgno iPtrmap; /* The pointer map page number */ 999 int offset; /* Offset in pointer map page */ 1000 int rc; /* Return code from subfunctions */ 1001 1002 if( *pRC ) return; 1003 1004 assert( sqlite3_mutex_held(pBt->mutex) ); 1005 /* The super-journal page number must never be used as a pointer map page */ 1006 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); 1007 1008 assert( pBt->autoVacuum ); 1009 if( key==0 ){ 1010 *pRC = SQLITE_CORRUPT_BKPT; 1011 return; 1012 } 1013 iPtrmap = PTRMAP_PAGENO(pBt, key); 1014 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); 1015 if( rc!=SQLITE_OK ){ 1016 *pRC = rc; 1017 return; 1018 } 1019 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){ 1020 /* The first byte of the extra data is the MemPage.isInit byte. 1021 ** If that byte is set, it means this page is also being used 1022 ** as a btree page. */ 1023 *pRC = SQLITE_CORRUPT_BKPT; 1024 goto ptrmap_exit; 1025 } 1026 offset = PTRMAP_PTROFFSET(iPtrmap, key); 1027 if( offset<0 ){ 1028 *pRC = SQLITE_CORRUPT_BKPT; 1029 goto ptrmap_exit; 1030 } 1031 assert( offset <= (int)pBt->usableSize-5 ); 1032 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 1033 1034 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ 1035 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); 1036 *pRC= rc = sqlite3PagerWrite(pDbPage); 1037 if( rc==SQLITE_OK ){ 1038 pPtrmap[offset] = eType; 1039 put4byte(&pPtrmap[offset+1], parent); 1040 } 1041 } 1042 1043 ptrmap_exit: 1044 sqlite3PagerUnref(pDbPage); 1045 } 1046 1047 /* 1048 ** Read an entry from the pointer map. 1049 ** 1050 ** This routine retrieves the pointer map entry for page 'key', writing 1051 ** the type and parent page number to *pEType and *pPgno respectively. 1052 ** An error code is returned if something goes wrong, otherwise SQLITE_OK. 1053 */ 1054 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ 1055 DbPage *pDbPage; /* The pointer map page */ 1056 int iPtrmap; /* Pointer map page index */ 1057 u8 *pPtrmap; /* Pointer map page data */ 1058 int offset; /* Offset of entry in pointer map */ 1059 int rc; 1060 1061 assert( sqlite3_mutex_held(pBt->mutex) ); 1062 1063 iPtrmap = PTRMAP_PAGENO(pBt, key); 1064 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); 1065 if( rc!=0 ){ 1066 return rc; 1067 } 1068 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 1069 1070 offset = PTRMAP_PTROFFSET(iPtrmap, key); 1071 if( offset<0 ){ 1072 sqlite3PagerUnref(pDbPage); 1073 return SQLITE_CORRUPT_BKPT; 1074 } 1075 assert( offset <= (int)pBt->usableSize-5 ); 1076 assert( pEType!=0 ); 1077 *pEType = pPtrmap[offset]; 1078 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); 1079 1080 sqlite3PagerUnref(pDbPage); 1081 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap); 1082 return SQLITE_OK; 1083 } 1084 1085 #else /* if defined SQLITE_OMIT_AUTOVACUUM */ 1086 #define ptrmapPut(w,x,y,z,rc) 1087 #define ptrmapGet(w,x,y,z) SQLITE_OK 1088 #define ptrmapPutOvflPtr(x, y, z, rc) 1089 #endif 1090 1091 /* 1092 ** Given a btree page and a cell index (0 means the first cell on 1093 ** the page, 1 means the second cell, and so forth) return a pointer 1094 ** to the cell content. 1095 ** 1096 ** findCellPastPtr() does the same except it skips past the initial 1097 ** 4-byte child pointer found on interior pages, if there is one. 1098 ** 1099 ** This routine works only for pages that do not contain overflow cells. 1100 */ 1101 #define findCell(P,I) \ 1102 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 1103 #define findCellPastPtr(P,I) \ 1104 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 1105 1106 1107 /* 1108 ** This is common tail processing for btreeParseCellPtr() and 1109 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely 1110 ** on a single B-tree page. Make necessary adjustments to the CellInfo 1111 ** structure. 1112 */ 1113 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( 1114 MemPage *pPage, /* Page containing the cell */ 1115 u8 *pCell, /* Pointer to the cell text. */ 1116 CellInfo *pInfo /* Fill in this structure */ 1117 ){ 1118 /* If the payload will not fit completely on the local page, we have 1119 ** to decide how much to store locally and how much to spill onto 1120 ** overflow pages. The strategy is to minimize the amount of unused 1121 ** space on overflow pages while keeping the amount of local storage 1122 ** in between minLocal and maxLocal. 1123 ** 1124 ** Warning: changing the way overflow payload is distributed in any 1125 ** way will result in an incompatible file format. 1126 */ 1127 int minLocal; /* Minimum amount of payload held locally */ 1128 int maxLocal; /* Maximum amount of payload held locally */ 1129 int surplus; /* Overflow payload available for local storage */ 1130 1131 minLocal = pPage->minLocal; 1132 maxLocal = pPage->maxLocal; 1133 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); 1134 testcase( surplus==maxLocal ); 1135 testcase( surplus==maxLocal+1 ); 1136 if( surplus <= maxLocal ){ 1137 pInfo->nLocal = (u16)surplus; 1138 }else{ 1139 pInfo->nLocal = (u16)minLocal; 1140 } 1141 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; 1142 } 1143 1144 /* 1145 ** Given a record with nPayload bytes of payload stored within btree 1146 ** page pPage, return the number of bytes of payload stored locally. 1147 */ 1148 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){ 1149 int maxLocal; /* Maximum amount of payload held locally */ 1150 maxLocal = pPage->maxLocal; 1151 if( nPayload<=maxLocal ){ 1152 return nPayload; 1153 }else{ 1154 int minLocal; /* Minimum amount of payload held locally */ 1155 int surplus; /* Overflow payload available for local storage */ 1156 minLocal = pPage->minLocal; 1157 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4); 1158 return ( surplus <= maxLocal ) ? surplus : minLocal; 1159 } 1160 } 1161 1162 /* 1163 ** The following routines are implementations of the MemPage.xParseCell() 1164 ** method. 1165 ** 1166 ** Parse a cell content block and fill in the CellInfo structure. 1167 ** 1168 ** btreeParseCellPtr() => table btree leaf nodes 1169 ** btreeParseCellNoPayload() => table btree internal nodes 1170 ** btreeParseCellPtrIndex() => index btree nodes 1171 ** 1172 ** There is also a wrapper function btreeParseCell() that works for 1173 ** all MemPage types and that references the cell by index rather than 1174 ** by pointer. 1175 */ 1176 static void btreeParseCellPtrNoPayload( 1177 MemPage *pPage, /* Page containing the cell */ 1178 u8 *pCell, /* Pointer to the cell text. */ 1179 CellInfo *pInfo /* Fill in this structure */ 1180 ){ 1181 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1182 assert( pPage->leaf==0 ); 1183 assert( pPage->childPtrSize==4 ); 1184 #ifndef SQLITE_DEBUG 1185 UNUSED_PARAMETER(pPage); 1186 #endif 1187 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); 1188 pInfo->nPayload = 0; 1189 pInfo->nLocal = 0; 1190 pInfo->pPayload = 0; 1191 return; 1192 } 1193 static void btreeParseCellPtr( 1194 MemPage *pPage, /* Page containing the cell */ 1195 u8 *pCell, /* Pointer to the cell text. */ 1196 CellInfo *pInfo /* Fill in this structure */ 1197 ){ 1198 u8 *pIter; /* For scanning through pCell */ 1199 u32 nPayload; /* Number of bytes of cell payload */ 1200 u64 iKey; /* Extracted Key value */ 1201 1202 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1203 assert( pPage->leaf==0 || pPage->leaf==1 ); 1204 assert( pPage->intKeyLeaf ); 1205 assert( pPage->childPtrSize==0 ); 1206 pIter = pCell; 1207 1208 /* The next block of code is equivalent to: 1209 ** 1210 ** pIter += getVarint32(pIter, nPayload); 1211 ** 1212 ** The code is inlined to avoid a function call. 1213 */ 1214 nPayload = *pIter; 1215 if( nPayload>=0x80 ){ 1216 u8 *pEnd = &pIter[8]; 1217 nPayload &= 0x7f; 1218 do{ 1219 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1220 }while( (*pIter)>=0x80 && pIter<pEnd ); 1221 } 1222 pIter++; 1223 1224 /* The next block of code is equivalent to: 1225 ** 1226 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); 1227 ** 1228 ** The code is inlined to avoid a function call. 1229 */ 1230 iKey = *pIter; 1231 if( iKey>=0x80 ){ 1232 u8 *pEnd = &pIter[7]; 1233 iKey &= 0x7f; 1234 while(1){ 1235 iKey = (iKey<<7) | (*++pIter & 0x7f); 1236 if( (*pIter)<0x80 ) break; 1237 if( pIter>=pEnd ){ 1238 iKey = (iKey<<8) | *++pIter; 1239 break; 1240 } 1241 } 1242 } 1243 pIter++; 1244 1245 pInfo->nKey = *(i64*)&iKey; 1246 pInfo->nPayload = nPayload; 1247 pInfo->pPayload = pIter; 1248 testcase( nPayload==pPage->maxLocal ); 1249 testcase( nPayload==pPage->maxLocal+1 ); 1250 if( nPayload<=pPage->maxLocal ){ 1251 /* This is the (easy) common case where the entire payload fits 1252 ** on the local page. No overflow is required. 1253 */ 1254 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1255 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1256 pInfo->nLocal = (u16)nPayload; 1257 }else{ 1258 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1259 } 1260 } 1261 static void btreeParseCellPtrIndex( 1262 MemPage *pPage, /* Page containing the cell */ 1263 u8 *pCell, /* Pointer to the cell text. */ 1264 CellInfo *pInfo /* Fill in this structure */ 1265 ){ 1266 u8 *pIter; /* For scanning through pCell */ 1267 u32 nPayload; /* Number of bytes of cell payload */ 1268 1269 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1270 assert( pPage->leaf==0 || pPage->leaf==1 ); 1271 assert( pPage->intKeyLeaf==0 ); 1272 pIter = pCell + pPage->childPtrSize; 1273 nPayload = *pIter; 1274 if( nPayload>=0x80 ){ 1275 u8 *pEnd = &pIter[8]; 1276 nPayload &= 0x7f; 1277 do{ 1278 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1279 }while( *(pIter)>=0x80 && pIter<pEnd ); 1280 } 1281 pIter++; 1282 pInfo->nKey = nPayload; 1283 pInfo->nPayload = nPayload; 1284 pInfo->pPayload = pIter; 1285 testcase( nPayload==pPage->maxLocal ); 1286 testcase( nPayload==pPage->maxLocal+1 ); 1287 if( nPayload<=pPage->maxLocal ){ 1288 /* This is the (easy) common case where the entire payload fits 1289 ** on the local page. No overflow is required. 1290 */ 1291 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1292 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1293 pInfo->nLocal = (u16)nPayload; 1294 }else{ 1295 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1296 } 1297 } 1298 static void btreeParseCell( 1299 MemPage *pPage, /* Page containing the cell */ 1300 int iCell, /* The cell index. First cell is 0 */ 1301 CellInfo *pInfo /* Fill in this structure */ 1302 ){ 1303 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); 1304 } 1305 1306 /* 1307 ** The following routines are implementations of the MemPage.xCellSize 1308 ** method. 1309 ** 1310 ** Compute the total number of bytes that a Cell needs in the cell 1311 ** data area of the btree-page. The return number includes the cell 1312 ** data header and the local payload, but not any overflow page or 1313 ** the space used by the cell pointer. 1314 ** 1315 ** cellSizePtrNoPayload() => table internal nodes 1316 ** cellSizePtr() => all index nodes & table leaf nodes 1317 */ 1318 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ 1319 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ 1320 u8 *pEnd; /* End mark for a varint */ 1321 u32 nSize; /* Size value to return */ 1322 1323 #ifdef SQLITE_DEBUG 1324 /* The value returned by this function should always be the same as 1325 ** the (CellInfo.nSize) value found by doing a full parse of the 1326 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1327 ** this function verifies that this invariant is not violated. */ 1328 CellInfo debuginfo; 1329 pPage->xParseCell(pPage, pCell, &debuginfo); 1330 #endif 1331 1332 nSize = *pIter; 1333 if( nSize>=0x80 ){ 1334 pEnd = &pIter[8]; 1335 nSize &= 0x7f; 1336 do{ 1337 nSize = (nSize<<7) | (*++pIter & 0x7f); 1338 }while( *(pIter)>=0x80 && pIter<pEnd ); 1339 } 1340 pIter++; 1341 if( pPage->intKey ){ 1342 /* pIter now points at the 64-bit integer key value, a variable length 1343 ** integer. The following block moves pIter to point at the first byte 1344 ** past the end of the key value. */ 1345 pEnd = &pIter[9]; 1346 while( (*pIter++)&0x80 && pIter<pEnd ); 1347 } 1348 testcase( nSize==pPage->maxLocal ); 1349 testcase( nSize==pPage->maxLocal+1 ); 1350 if( nSize<=pPage->maxLocal ){ 1351 nSize += (u32)(pIter - pCell); 1352 if( nSize<4 ) nSize = 4; 1353 }else{ 1354 int minLocal = pPage->minLocal; 1355 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); 1356 testcase( nSize==pPage->maxLocal ); 1357 testcase( nSize==pPage->maxLocal+1 ); 1358 if( nSize>pPage->maxLocal ){ 1359 nSize = minLocal; 1360 } 1361 nSize += 4 + (u16)(pIter - pCell); 1362 } 1363 assert( nSize==debuginfo.nSize || CORRUPT_DB ); 1364 return (u16)nSize; 1365 } 1366 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ 1367 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ 1368 u8 *pEnd; /* End mark for a varint */ 1369 1370 #ifdef SQLITE_DEBUG 1371 /* The value returned by this function should always be the same as 1372 ** the (CellInfo.nSize) value found by doing a full parse of the 1373 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1374 ** this function verifies that this invariant is not violated. */ 1375 CellInfo debuginfo; 1376 pPage->xParseCell(pPage, pCell, &debuginfo); 1377 #else 1378 UNUSED_PARAMETER(pPage); 1379 #endif 1380 1381 assert( pPage->childPtrSize==4 ); 1382 pEnd = pIter + 9; 1383 while( (*pIter++)&0x80 && pIter<pEnd ); 1384 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB ); 1385 return (u16)(pIter - pCell); 1386 } 1387 1388 1389 #ifdef SQLITE_DEBUG 1390 /* This variation on cellSizePtr() is used inside of assert() statements 1391 ** only. */ 1392 static u16 cellSize(MemPage *pPage, int iCell){ 1393 return pPage->xCellSize(pPage, findCell(pPage, iCell)); 1394 } 1395 #endif 1396 1397 #ifndef SQLITE_OMIT_AUTOVACUUM 1398 /* 1399 ** The cell pCell is currently part of page pSrc but will ultimately be part 1400 ** of pPage. (pSrc and pPager are often the same.) If pCell contains a 1401 ** pointer to an overflow page, insert an entry into the pointer-map for 1402 ** the overflow page that will be valid after pCell has been moved to pPage. 1403 */ 1404 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){ 1405 CellInfo info; 1406 if( *pRC ) return; 1407 assert( pCell!=0 ); 1408 pPage->xParseCell(pPage, pCell, &info); 1409 if( info.nLocal<info.nPayload ){ 1410 Pgno ovfl; 1411 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){ 1412 testcase( pSrc!=pPage ); 1413 *pRC = SQLITE_CORRUPT_BKPT; 1414 return; 1415 } 1416 ovfl = get4byte(&pCell[info.nSize-4]); 1417 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); 1418 } 1419 } 1420 #endif 1421 1422 1423 /* 1424 ** Defragment the page given. This routine reorganizes cells within the 1425 ** page so that there are no free-blocks on the free-block list. 1426 ** 1427 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be 1428 ** present in the page after this routine returns. 1429 ** 1430 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a 1431 ** b-tree page so that there are no freeblocks or fragment bytes, all 1432 ** unused bytes are contained in the unallocated space region, and all 1433 ** cells are packed tightly at the end of the page. 1434 */ 1435 static int defragmentPage(MemPage *pPage, int nMaxFrag){ 1436 int i; /* Loop counter */ 1437 int pc; /* Address of the i-th cell */ 1438 int hdr; /* Offset to the page header */ 1439 int size; /* Size of a cell */ 1440 int usableSize; /* Number of usable bytes on a page */ 1441 int cellOffset; /* Offset to the cell pointer array */ 1442 int cbrk; /* Offset to the cell content area */ 1443 int nCell; /* Number of cells on the page */ 1444 unsigned char *data; /* The page data */ 1445 unsigned char *temp; /* Temp area for cell content */ 1446 unsigned char *src; /* Source of content */ 1447 int iCellFirst; /* First allowable cell index */ 1448 int iCellLast; /* Last possible cell index */ 1449 int iCellStart; /* First cell offset in input */ 1450 1451 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1452 assert( pPage->pBt!=0 ); 1453 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); 1454 assert( pPage->nOverflow==0 ); 1455 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1456 temp = 0; 1457 src = data = pPage->aData; 1458 hdr = pPage->hdrOffset; 1459 cellOffset = pPage->cellOffset; 1460 nCell = pPage->nCell; 1461 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB ); 1462 iCellFirst = cellOffset + 2*nCell; 1463 usableSize = pPage->pBt->usableSize; 1464 1465 /* This block handles pages with two or fewer free blocks and nMaxFrag 1466 ** or fewer fragmented bytes. In this case it is faster to move the 1467 ** two (or one) blocks of cells using memmove() and add the required 1468 ** offsets to each pointer in the cell-pointer array than it is to 1469 ** reconstruct the entire page. */ 1470 if( (int)data[hdr+7]<=nMaxFrag ){ 1471 int iFree = get2byte(&data[hdr+1]); 1472 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); 1473 if( iFree ){ 1474 int iFree2 = get2byte(&data[iFree]); 1475 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); 1476 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){ 1477 u8 *pEnd = &data[cellOffset + nCell*2]; 1478 u8 *pAddr; 1479 int sz2 = 0; 1480 int sz = get2byte(&data[iFree+2]); 1481 int top = get2byte(&data[hdr+5]); 1482 if( top>=iFree ){ 1483 return SQLITE_CORRUPT_PAGE(pPage); 1484 } 1485 if( iFree2 ){ 1486 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage); 1487 sz2 = get2byte(&data[iFree2+2]); 1488 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage); 1489 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); 1490 sz += sz2; 1491 }else if( iFree+sz>usableSize ){ 1492 return SQLITE_CORRUPT_PAGE(pPage); 1493 } 1494 1495 cbrk = top+sz; 1496 assert( cbrk+(iFree-top) <= usableSize ); 1497 memmove(&data[cbrk], &data[top], iFree-top); 1498 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){ 1499 pc = get2byte(pAddr); 1500 if( pc<iFree ){ put2byte(pAddr, pc+sz); } 1501 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); } 1502 } 1503 goto defragment_out; 1504 } 1505 } 1506 } 1507 1508 cbrk = usableSize; 1509 iCellLast = usableSize - 4; 1510 iCellStart = get2byte(&data[hdr+5]); 1511 for(i=0; i<nCell; i++){ 1512 u8 *pAddr; /* The i-th cell pointer */ 1513 pAddr = &data[cellOffset + i*2]; 1514 pc = get2byte(pAddr); 1515 testcase( pc==iCellFirst ); 1516 testcase( pc==iCellLast ); 1517 /* These conditions have already been verified in btreeInitPage() 1518 ** if PRAGMA cell_size_check=ON. 1519 */ 1520 if( pc<iCellStart || pc>iCellLast ){ 1521 return SQLITE_CORRUPT_PAGE(pPage); 1522 } 1523 assert( pc>=iCellStart && pc<=iCellLast ); 1524 size = pPage->xCellSize(pPage, &src[pc]); 1525 cbrk -= size; 1526 if( cbrk<iCellStart || pc+size>usableSize ){ 1527 return SQLITE_CORRUPT_PAGE(pPage); 1528 } 1529 assert( cbrk+size<=usableSize && cbrk>=iCellStart ); 1530 testcase( cbrk+size==usableSize ); 1531 testcase( pc+size==usableSize ); 1532 put2byte(pAddr, cbrk); 1533 if( temp==0 ){ 1534 if( cbrk==pc ) continue; 1535 temp = sqlite3PagerTempSpace(pPage->pBt->pPager); 1536 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart); 1537 src = temp; 1538 } 1539 memcpy(&data[cbrk], &src[pc], size); 1540 } 1541 data[hdr+7] = 0; 1542 1543 defragment_out: 1544 assert( pPage->nFree>=0 ); 1545 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ 1546 return SQLITE_CORRUPT_PAGE(pPage); 1547 } 1548 assert( cbrk>=iCellFirst ); 1549 put2byte(&data[hdr+5], cbrk); 1550 data[hdr+1] = 0; 1551 data[hdr+2] = 0; 1552 memset(&data[iCellFirst], 0, cbrk-iCellFirst); 1553 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1554 return SQLITE_OK; 1555 } 1556 1557 /* 1558 ** Search the free-list on page pPg for space to store a cell nByte bytes in 1559 ** size. If one can be found, return a pointer to the space and remove it 1560 ** from the free-list. 1561 ** 1562 ** If no suitable space can be found on the free-list, return NULL. 1563 ** 1564 ** This function may detect corruption within pPg. If corruption is 1565 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. 1566 ** 1567 ** Slots on the free list that are between 1 and 3 bytes larger than nByte 1568 ** will be ignored if adding the extra space to the fragmentation count 1569 ** causes the fragmentation count to exceed 60. 1570 */ 1571 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ 1572 const int hdr = pPg->hdrOffset; /* Offset to page header */ 1573 u8 * const aData = pPg->aData; /* Page data */ 1574 int iAddr = hdr + 1; /* Address of ptr to pc */ 1575 int pc = get2byte(&aData[iAddr]); /* Address of a free slot */ 1576 int x; /* Excess size of the slot */ 1577 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */ 1578 int size; /* Size of the free slot */ 1579 1580 assert( pc>0 ); 1581 while( pc<=maxPC ){ 1582 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each 1583 ** freeblock form a big-endian integer which is the size of the freeblock 1584 ** in bytes, including the 4-byte header. */ 1585 size = get2byte(&aData[pc+2]); 1586 if( (x = size - nByte)>=0 ){ 1587 testcase( x==4 ); 1588 testcase( x==3 ); 1589 if( x<4 ){ 1590 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total 1591 ** number of bytes in fragments may not exceed 60. */ 1592 if( aData[hdr+7]>57 ) return 0; 1593 1594 /* Remove the slot from the free-list. Update the number of 1595 ** fragmented bytes within the page. */ 1596 memcpy(&aData[iAddr], &aData[pc], 2); 1597 aData[hdr+7] += (u8)x; 1598 }else if( x+pc > maxPC ){ 1599 /* This slot extends off the end of the usable part of the page */ 1600 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1601 return 0; 1602 }else{ 1603 /* The slot remains on the free-list. Reduce its size to account 1604 ** for the portion used by the new allocation. */ 1605 put2byte(&aData[pc+2], x); 1606 } 1607 return &aData[pc + x]; 1608 } 1609 iAddr = pc; 1610 pc = get2byte(&aData[pc]); 1611 if( pc<=iAddr+size ){ 1612 if( pc ){ 1613 /* The next slot in the chain is not past the end of the current slot */ 1614 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1615 } 1616 return 0; 1617 } 1618 } 1619 if( pc>maxPC+nByte-4 ){ 1620 /* The free slot chain extends off the end of the page */ 1621 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1622 } 1623 return 0; 1624 } 1625 1626 /* 1627 ** Allocate nByte bytes of space from within the B-Tree page passed 1628 ** as the first argument. Write into *pIdx the index into pPage->aData[] 1629 ** of the first byte of allocated space. Return either SQLITE_OK or 1630 ** an error code (usually SQLITE_CORRUPT). 1631 ** 1632 ** The caller guarantees that there is sufficient space to make the 1633 ** allocation. This routine might need to defragment in order to bring 1634 ** all the space together, however. This routine will avoid using 1635 ** the first two bytes past the cell pointer area since presumably this 1636 ** allocation is being made in order to insert a new cell, so we will 1637 ** also end up needing a new cell pointer. 1638 */ 1639 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ 1640 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ 1641 u8 * const data = pPage->aData; /* Local cache of pPage->aData */ 1642 int top; /* First byte of cell content area */ 1643 int rc = SQLITE_OK; /* Integer return code */ 1644 int gap; /* First byte of gap between cell pointers and cell content */ 1645 1646 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1647 assert( pPage->pBt ); 1648 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1649 assert( nByte>=0 ); /* Minimum cell size is 4 */ 1650 assert( pPage->nFree>=nByte ); 1651 assert( pPage->nOverflow==0 ); 1652 assert( nByte < (int)(pPage->pBt->usableSize-8) ); 1653 1654 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); 1655 gap = pPage->cellOffset + 2*pPage->nCell; 1656 assert( gap<=65536 ); 1657 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size 1658 ** and the reserved space is zero (the usual value for reserved space) 1659 ** then the cell content offset of an empty page wants to be 65536. 1660 ** However, that integer is too large to be stored in a 2-byte unsigned 1661 ** integer, so a value of 0 is used in its place. */ 1662 top = get2byte(&data[hdr+5]); 1663 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */ 1664 if( gap>top ){ 1665 if( top==0 && pPage->pBt->usableSize==65536 ){ 1666 top = 65536; 1667 }else{ 1668 return SQLITE_CORRUPT_PAGE(pPage); 1669 } 1670 } 1671 1672 /* If there is enough space between gap and top for one more cell pointer, 1673 ** and if the freelist is not empty, then search the 1674 ** freelist looking for a slot big enough to satisfy the request. 1675 */ 1676 testcase( gap+2==top ); 1677 testcase( gap+1==top ); 1678 testcase( gap==top ); 1679 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ 1680 u8 *pSpace = pageFindSlot(pPage, nByte, &rc); 1681 if( pSpace ){ 1682 int g2; 1683 assert( pSpace+nByte<=data+pPage->pBt->usableSize ); 1684 *pIdx = g2 = (int)(pSpace-data); 1685 if( g2<=gap ){ 1686 return SQLITE_CORRUPT_PAGE(pPage); 1687 }else{ 1688 return SQLITE_OK; 1689 } 1690 }else if( rc ){ 1691 return rc; 1692 } 1693 } 1694 1695 /* The request could not be fulfilled using a freelist slot. Check 1696 ** to see if defragmentation is necessary. 1697 */ 1698 testcase( gap+2+nByte==top ); 1699 if( gap+2+nByte>top ){ 1700 assert( pPage->nCell>0 || CORRUPT_DB ); 1701 assert( pPage->nFree>=0 ); 1702 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte))); 1703 if( rc ) return rc; 1704 top = get2byteNotZero(&data[hdr+5]); 1705 assert( gap+2+nByte<=top ); 1706 } 1707 1708 1709 /* Allocate memory from the gap in between the cell pointer array 1710 ** and the cell content area. The btreeComputeFreeSpace() call has already 1711 ** validated the freelist. Given that the freelist is valid, there 1712 ** is no way that the allocation can extend off the end of the page. 1713 ** The assert() below verifies the previous sentence. 1714 */ 1715 top -= nByte; 1716 put2byte(&data[hdr+5], top); 1717 assert( top+nByte <= (int)pPage->pBt->usableSize ); 1718 *pIdx = top; 1719 return SQLITE_OK; 1720 } 1721 1722 /* 1723 ** Return a section of the pPage->aData to the freelist. 1724 ** The first byte of the new free block is pPage->aData[iStart] 1725 ** and the size of the block is iSize bytes. 1726 ** 1727 ** Adjacent freeblocks are coalesced. 1728 ** 1729 ** Even though the freeblock list was checked by btreeComputeFreeSpace(), 1730 ** that routine will not detect overlap between cells or freeblocks. Nor 1731 ** does it detect cells or freeblocks that encrouch into the reserved bytes 1732 ** at the end of the page. So do additional corruption checks inside this 1733 ** routine and return SQLITE_CORRUPT if any problems are found. 1734 */ 1735 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ 1736 u16 iPtr; /* Address of ptr to next freeblock */ 1737 u16 iFreeBlk; /* Address of the next freeblock */ 1738 u8 hdr; /* Page header size. 0 or 100 */ 1739 u8 nFrag = 0; /* Reduction in fragmentation */ 1740 u16 iOrigSize = iSize; /* Original value of iSize */ 1741 u16 x; /* Offset to cell content area */ 1742 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ 1743 unsigned char *data = pPage->aData; /* Page content */ 1744 1745 assert( pPage->pBt!=0 ); 1746 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1747 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); 1748 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); 1749 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1750 assert( iSize>=4 ); /* Minimum cell size is 4 */ 1751 assert( iStart<=pPage->pBt->usableSize-4 ); 1752 1753 /* The list of freeblocks must be in ascending order. Find the 1754 ** spot on the list where iStart should be inserted. 1755 */ 1756 hdr = pPage->hdrOffset; 1757 iPtr = hdr + 1; 1758 if( data[iPtr+1]==0 && data[iPtr]==0 ){ 1759 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ 1760 }else{ 1761 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){ 1762 if( iFreeBlk<iPtr+4 ){ 1763 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */ 1764 return SQLITE_CORRUPT_PAGE(pPage); 1765 } 1766 iPtr = iFreeBlk; 1767 } 1768 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ 1769 return SQLITE_CORRUPT_PAGE(pPage); 1770 } 1771 assert( iFreeBlk>iPtr || iFreeBlk==0 ); 1772 1773 /* At this point: 1774 ** iFreeBlk: First freeblock after iStart, or zero if none 1775 ** iPtr: The address of a pointer to iFreeBlk 1776 ** 1777 ** Check to see if iFreeBlk should be coalesced onto the end of iStart. 1778 */ 1779 if( iFreeBlk && iEnd+3>=iFreeBlk ){ 1780 nFrag = iFreeBlk - iEnd; 1781 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage); 1782 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); 1783 if( iEnd > pPage->pBt->usableSize ){ 1784 return SQLITE_CORRUPT_PAGE(pPage); 1785 } 1786 iSize = iEnd - iStart; 1787 iFreeBlk = get2byte(&data[iFreeBlk]); 1788 } 1789 1790 /* If iPtr is another freeblock (that is, if iPtr is not the freelist 1791 ** pointer in the page header) then check to see if iStart should be 1792 ** coalesced onto the end of iPtr. 1793 */ 1794 if( iPtr>hdr+1 ){ 1795 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); 1796 if( iPtrEnd+3>=iStart ){ 1797 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage); 1798 nFrag += iStart - iPtrEnd; 1799 iSize = iEnd - iPtr; 1800 iStart = iPtr; 1801 } 1802 } 1803 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage); 1804 data[hdr+7] -= nFrag; 1805 } 1806 x = get2byte(&data[hdr+5]); 1807 if( iStart<=x ){ 1808 /* The new freeblock is at the beginning of the cell content area, 1809 ** so just extend the cell content area rather than create another 1810 ** freelist entry */ 1811 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage); 1812 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage); 1813 put2byte(&data[hdr+1], iFreeBlk); 1814 put2byte(&data[hdr+5], iEnd); 1815 }else{ 1816 /* Insert the new freeblock into the freelist */ 1817 put2byte(&data[iPtr], iStart); 1818 } 1819 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){ 1820 /* Overwrite deleted information with zeros when the secure_delete 1821 ** option is enabled */ 1822 memset(&data[iStart], 0, iSize); 1823 } 1824 put2byte(&data[iStart], iFreeBlk); 1825 put2byte(&data[iStart+2], iSize); 1826 pPage->nFree += iOrigSize; 1827 return SQLITE_OK; 1828 } 1829 1830 /* 1831 ** Decode the flags byte (the first byte of the header) for a page 1832 ** and initialize fields of the MemPage structure accordingly. 1833 ** 1834 ** Only the following combinations are supported. Anything different 1835 ** indicates a corrupt database files: 1836 ** 1837 ** PTF_ZERODATA 1838 ** PTF_ZERODATA | PTF_LEAF 1839 ** PTF_LEAFDATA | PTF_INTKEY 1840 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF 1841 */ 1842 static int decodeFlags(MemPage *pPage, int flagByte){ 1843 BtShared *pBt; /* A copy of pPage->pBt */ 1844 1845 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); 1846 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1847 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); 1848 flagByte &= ~PTF_LEAF; 1849 pPage->childPtrSize = 4-4*pPage->leaf; 1850 pPage->xCellSize = cellSizePtr; 1851 pBt = pPage->pBt; 1852 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ 1853 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an 1854 ** interior table b-tree page. */ 1855 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); 1856 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a 1857 ** leaf table b-tree page. */ 1858 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); 1859 pPage->intKey = 1; 1860 if( pPage->leaf ){ 1861 pPage->intKeyLeaf = 1; 1862 pPage->xParseCell = btreeParseCellPtr; 1863 }else{ 1864 pPage->intKeyLeaf = 0; 1865 pPage->xCellSize = cellSizePtrNoPayload; 1866 pPage->xParseCell = btreeParseCellPtrNoPayload; 1867 } 1868 pPage->maxLocal = pBt->maxLeaf; 1869 pPage->minLocal = pBt->minLeaf; 1870 }else if( flagByte==PTF_ZERODATA ){ 1871 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an 1872 ** interior index b-tree page. */ 1873 assert( (PTF_ZERODATA)==2 ); 1874 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a 1875 ** leaf index b-tree page. */ 1876 assert( (PTF_ZERODATA|PTF_LEAF)==10 ); 1877 pPage->intKey = 0; 1878 pPage->intKeyLeaf = 0; 1879 pPage->xParseCell = btreeParseCellPtrIndex; 1880 pPage->maxLocal = pBt->maxLocal; 1881 pPage->minLocal = pBt->minLocal; 1882 }else{ 1883 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is 1884 ** an error. */ 1885 return SQLITE_CORRUPT_PAGE(pPage); 1886 } 1887 pPage->max1bytePayload = pBt->max1bytePayload; 1888 return SQLITE_OK; 1889 } 1890 1891 /* 1892 ** Compute the amount of freespace on the page. In other words, fill 1893 ** in the pPage->nFree field. 1894 */ 1895 static int btreeComputeFreeSpace(MemPage *pPage){ 1896 int pc; /* Address of a freeblock within pPage->aData[] */ 1897 u8 hdr; /* Offset to beginning of page header */ 1898 u8 *data; /* Equal to pPage->aData */ 1899 int usableSize; /* Amount of usable space on each page */ 1900 int nFree; /* Number of unused bytes on the page */ 1901 int top; /* First byte of the cell content area */ 1902 int iCellFirst; /* First allowable cell or freeblock offset */ 1903 int iCellLast; /* Last possible cell or freeblock offset */ 1904 1905 assert( pPage->pBt!=0 ); 1906 assert( pPage->pBt->db!=0 ); 1907 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1908 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); 1909 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); 1910 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); 1911 assert( pPage->isInit==1 ); 1912 assert( pPage->nFree<0 ); 1913 1914 usableSize = pPage->pBt->usableSize; 1915 hdr = pPage->hdrOffset; 1916 data = pPage->aData; 1917 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates 1918 ** the start of the cell content area. A zero value for this integer is 1919 ** interpreted as 65536. */ 1920 top = get2byteNotZero(&data[hdr+5]); 1921 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell; 1922 iCellLast = usableSize - 4; 1923 1924 /* Compute the total free space on the page 1925 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the 1926 ** start of the first freeblock on the page, or is zero if there are no 1927 ** freeblocks. */ 1928 pc = get2byte(&data[hdr+1]); 1929 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ 1930 if( pc>0 ){ 1931 u32 next, size; 1932 if( pc<top ){ 1933 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will 1934 ** always be at least one cell before the first freeblock. 1935 */ 1936 return SQLITE_CORRUPT_PAGE(pPage); 1937 } 1938 while( 1 ){ 1939 if( pc>iCellLast ){ 1940 /* Freeblock off the end of the page */ 1941 return SQLITE_CORRUPT_PAGE(pPage); 1942 } 1943 next = get2byte(&data[pc]); 1944 size = get2byte(&data[pc+2]); 1945 nFree = nFree + size; 1946 if( next<=pc+size+3 ) break; 1947 pc = next; 1948 } 1949 if( next>0 ){ 1950 /* Freeblock not in ascending order */ 1951 return SQLITE_CORRUPT_PAGE(pPage); 1952 } 1953 if( pc+size>(unsigned int)usableSize ){ 1954 /* Last freeblock extends past page end */ 1955 return SQLITE_CORRUPT_PAGE(pPage); 1956 } 1957 } 1958 1959 /* At this point, nFree contains the sum of the offset to the start 1960 ** of the cell-content area plus the number of free bytes within 1961 ** the cell-content area. If this is greater than the usable-size 1962 ** of the page, then the page must be corrupted. This check also 1963 ** serves to verify that the offset to the start of the cell-content 1964 ** area, according to the page header, lies within the page. 1965 */ 1966 if( nFree>usableSize || nFree<iCellFirst ){ 1967 return SQLITE_CORRUPT_PAGE(pPage); 1968 } 1969 pPage->nFree = (u16)(nFree - iCellFirst); 1970 return SQLITE_OK; 1971 } 1972 1973 /* 1974 ** Do additional sanity check after btreeInitPage() if 1975 ** PRAGMA cell_size_check=ON 1976 */ 1977 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){ 1978 int iCellFirst; /* First allowable cell or freeblock offset */ 1979 int iCellLast; /* Last possible cell or freeblock offset */ 1980 int i; /* Index into the cell pointer array */ 1981 int sz; /* Size of a cell */ 1982 int pc; /* Address of a freeblock within pPage->aData[] */ 1983 u8 *data; /* Equal to pPage->aData */ 1984 int usableSize; /* Maximum usable space on the page */ 1985 int cellOffset; /* Start of cell content area */ 1986 1987 iCellFirst = pPage->cellOffset + 2*pPage->nCell; 1988 usableSize = pPage->pBt->usableSize; 1989 iCellLast = usableSize - 4; 1990 data = pPage->aData; 1991 cellOffset = pPage->cellOffset; 1992 if( !pPage->leaf ) iCellLast--; 1993 for(i=0; i<pPage->nCell; i++){ 1994 pc = get2byteAligned(&data[cellOffset+i*2]); 1995 testcase( pc==iCellFirst ); 1996 testcase( pc==iCellLast ); 1997 if( pc<iCellFirst || pc>iCellLast ){ 1998 return SQLITE_CORRUPT_PAGE(pPage); 1999 } 2000 sz = pPage->xCellSize(pPage, &data[pc]); 2001 testcase( pc+sz==usableSize ); 2002 if( pc+sz>usableSize ){ 2003 return SQLITE_CORRUPT_PAGE(pPage); 2004 } 2005 } 2006 return SQLITE_OK; 2007 } 2008 2009 /* 2010 ** Initialize the auxiliary information for a disk block. 2011 ** 2012 ** Return SQLITE_OK on success. If we see that the page does 2013 ** not contain a well-formed database page, then return 2014 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not 2015 ** guarantee that the page is well-formed. It only shows that 2016 ** we failed to detect any corruption. 2017 */ 2018 static int btreeInitPage(MemPage *pPage){ 2019 u8 *data; /* Equal to pPage->aData */ 2020 BtShared *pBt; /* The main btree structure */ 2021 2022 assert( pPage->pBt!=0 ); 2023 assert( pPage->pBt->db!=0 ); 2024 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2025 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); 2026 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); 2027 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); 2028 assert( pPage->isInit==0 ); 2029 2030 pBt = pPage->pBt; 2031 data = pPage->aData + pPage->hdrOffset; 2032 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating 2033 ** the b-tree page type. */ 2034 if( decodeFlags(pPage, data[0]) ){ 2035 return SQLITE_CORRUPT_PAGE(pPage); 2036 } 2037 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 2038 pPage->maskPage = (u16)(pBt->pageSize - 1); 2039 pPage->nOverflow = 0; 2040 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize; 2041 pPage->aCellIdx = data + pPage->childPtrSize + 8; 2042 pPage->aDataEnd = pPage->aData + pBt->usableSize; 2043 pPage->aDataOfst = pPage->aData + pPage->childPtrSize; 2044 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 2045 ** number of cells on the page. */ 2046 pPage->nCell = get2byte(&data[3]); 2047 if( pPage->nCell>MX_CELL(pBt) ){ 2048 /* To many cells for a single page. The page must be corrupt */ 2049 return SQLITE_CORRUPT_PAGE(pPage); 2050 } 2051 testcase( pPage->nCell==MX_CELL(pBt) ); 2052 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only 2053 ** possible for a root page of a table that contains no rows) then the 2054 ** offset to the cell content area will equal the page size minus the 2055 ** bytes of reserved space. */ 2056 assert( pPage->nCell>0 2057 || get2byteNotZero(&data[5])==(int)pBt->usableSize 2058 || CORRUPT_DB ); 2059 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */ 2060 pPage->isInit = 1; 2061 if( pBt->db->flags & SQLITE_CellSizeCk ){ 2062 return btreeCellSizeCheck(pPage); 2063 } 2064 return SQLITE_OK; 2065 } 2066 2067 /* 2068 ** Set up a raw page so that it looks like a database page holding 2069 ** no entries. 2070 */ 2071 static void zeroPage(MemPage *pPage, int flags){ 2072 unsigned char *data = pPage->aData; 2073 BtShared *pBt = pPage->pBt; 2074 u8 hdr = pPage->hdrOffset; 2075 u16 first; 2076 2077 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); 2078 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2079 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); 2080 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 2081 assert( sqlite3_mutex_held(pBt->mutex) ); 2082 if( pBt->btsFlags & BTS_FAST_SECURE ){ 2083 memset(&data[hdr], 0, pBt->usableSize - hdr); 2084 } 2085 data[hdr] = (char)flags; 2086 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); 2087 memset(&data[hdr+1], 0, 4); 2088 data[hdr+7] = 0; 2089 put2byte(&data[hdr+5], pBt->usableSize); 2090 pPage->nFree = (u16)(pBt->usableSize - first); 2091 decodeFlags(pPage, flags); 2092 pPage->cellOffset = first; 2093 pPage->aDataEnd = &data[pBt->usableSize]; 2094 pPage->aCellIdx = &data[first]; 2095 pPage->aDataOfst = &data[pPage->childPtrSize]; 2096 pPage->nOverflow = 0; 2097 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 2098 pPage->maskPage = (u16)(pBt->pageSize - 1); 2099 pPage->nCell = 0; 2100 pPage->isInit = 1; 2101 } 2102 2103 2104 /* 2105 ** Convert a DbPage obtained from the pager into a MemPage used by 2106 ** the btree layer. 2107 */ 2108 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ 2109 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); 2110 if( pgno!=pPage->pgno ){ 2111 pPage->aData = sqlite3PagerGetData(pDbPage); 2112 pPage->pDbPage = pDbPage; 2113 pPage->pBt = pBt; 2114 pPage->pgno = pgno; 2115 pPage->hdrOffset = pgno==1 ? 100 : 0; 2116 } 2117 assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); 2118 return pPage; 2119 } 2120 2121 /* 2122 ** Get a page from the pager. Initialize the MemPage.pBt and 2123 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). 2124 ** 2125 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care 2126 ** about the content of the page at this time. So do not go to the disk 2127 ** to fetch the content. Just fill in the content with zeros for now. 2128 ** If in the future we call sqlite3PagerWrite() on this page, that 2129 ** means we have started to be concerned about content and the disk 2130 ** read should occur at that point. 2131 */ 2132 static int btreeGetPage( 2133 BtShared *pBt, /* The btree */ 2134 Pgno pgno, /* Number of the page to fetch */ 2135 MemPage **ppPage, /* Return the page in this parameter */ 2136 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 2137 ){ 2138 int rc; 2139 DbPage *pDbPage; 2140 2141 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); 2142 assert( sqlite3_mutex_held(pBt->mutex) ); 2143 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); 2144 if( rc ) return rc; 2145 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); 2146 return SQLITE_OK; 2147 } 2148 2149 /* 2150 ** Retrieve a page from the pager cache. If the requested page is not 2151 ** already in the pager cache return NULL. Initialize the MemPage.pBt and 2152 ** MemPage.aData elements if needed. 2153 */ 2154 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ 2155 DbPage *pDbPage; 2156 assert( sqlite3_mutex_held(pBt->mutex) ); 2157 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); 2158 if( pDbPage ){ 2159 return btreePageFromDbPage(pDbPage, pgno, pBt); 2160 } 2161 return 0; 2162 } 2163 2164 /* 2165 ** Return the size of the database file in pages. If there is any kind of 2166 ** error, return ((unsigned int)-1). 2167 */ 2168 static Pgno btreePagecount(BtShared *pBt){ 2169 return pBt->nPage; 2170 } 2171 Pgno sqlite3BtreeLastPage(Btree *p){ 2172 assert( sqlite3BtreeHoldsMutex(p) ); 2173 return btreePagecount(p->pBt); 2174 } 2175 2176 /* 2177 ** Get a page from the pager and initialize it. 2178 ** 2179 ** If pCur!=0 then the page is being fetched as part of a moveToChild() 2180 ** call. Do additional sanity checking on the page in this case. 2181 ** And if the fetch fails, this routine must decrement pCur->iPage. 2182 ** 2183 ** The page is fetched as read-write unless pCur is not NULL and is 2184 ** a read-only cursor. 2185 ** 2186 ** If an error occurs, then *ppPage is undefined. It 2187 ** may remain unchanged, or it may be set to an invalid value. 2188 */ 2189 static int getAndInitPage( 2190 BtShared *pBt, /* The database file */ 2191 Pgno pgno, /* Number of the page to get */ 2192 MemPage **ppPage, /* Write the page pointer here */ 2193 BtCursor *pCur, /* Cursor to receive the page, or NULL */ 2194 int bReadOnly /* True for a read-only page */ 2195 ){ 2196 int rc; 2197 DbPage *pDbPage; 2198 assert( sqlite3_mutex_held(pBt->mutex) ); 2199 assert( pCur==0 || ppPage==&pCur->pPage ); 2200 assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); 2201 assert( pCur==0 || pCur->iPage>0 ); 2202 2203 if( pgno>btreePagecount(pBt) ){ 2204 rc = SQLITE_CORRUPT_BKPT; 2205 goto getAndInitPage_error1; 2206 } 2207 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); 2208 if( rc ){ 2209 goto getAndInitPage_error1; 2210 } 2211 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); 2212 if( (*ppPage)->isInit==0 ){ 2213 btreePageFromDbPage(pDbPage, pgno, pBt); 2214 rc = btreeInitPage(*ppPage); 2215 if( rc!=SQLITE_OK ){ 2216 goto getAndInitPage_error2; 2217 } 2218 } 2219 assert( (*ppPage)->pgno==pgno ); 2220 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); 2221 2222 /* If obtaining a child page for a cursor, we must verify that the page is 2223 ** compatible with the root page. */ 2224 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ 2225 rc = SQLITE_CORRUPT_PGNO(pgno); 2226 goto getAndInitPage_error2; 2227 } 2228 return SQLITE_OK; 2229 2230 getAndInitPage_error2: 2231 releasePage(*ppPage); 2232 getAndInitPage_error1: 2233 if( pCur ){ 2234 pCur->iPage--; 2235 pCur->pPage = pCur->apPage[pCur->iPage]; 2236 } 2237 testcase( pgno==0 ); 2238 assert( pgno!=0 || rc==SQLITE_CORRUPT ); 2239 return rc; 2240 } 2241 2242 /* 2243 ** Release a MemPage. This should be called once for each prior 2244 ** call to btreeGetPage. 2245 ** 2246 ** Page1 is a special case and must be released using releasePageOne(). 2247 */ 2248 static void releasePageNotNull(MemPage *pPage){ 2249 assert( pPage->aData ); 2250 assert( pPage->pBt ); 2251 assert( pPage->pDbPage!=0 ); 2252 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2253 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); 2254 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2255 sqlite3PagerUnrefNotNull(pPage->pDbPage); 2256 } 2257 static void releasePage(MemPage *pPage){ 2258 if( pPage ) releasePageNotNull(pPage); 2259 } 2260 static void releasePageOne(MemPage *pPage){ 2261 assert( pPage!=0 ); 2262 assert( pPage->aData ); 2263 assert( pPage->pBt ); 2264 assert( pPage->pDbPage!=0 ); 2265 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2266 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); 2267 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2268 sqlite3PagerUnrefPageOne(pPage->pDbPage); 2269 } 2270 2271 /* 2272 ** Get an unused page. 2273 ** 2274 ** This works just like btreeGetPage() with the addition: 2275 ** 2276 ** * If the page is already in use for some other purpose, immediately 2277 ** release it and return an SQLITE_CURRUPT error. 2278 ** * Make sure the isInit flag is clear 2279 */ 2280 static int btreeGetUnusedPage( 2281 BtShared *pBt, /* The btree */ 2282 Pgno pgno, /* Number of the page to fetch */ 2283 MemPage **ppPage, /* Return the page in this parameter */ 2284 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 2285 ){ 2286 int rc = btreeGetPage(pBt, pgno, ppPage, flags); 2287 if( rc==SQLITE_OK ){ 2288 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ 2289 releasePage(*ppPage); 2290 *ppPage = 0; 2291 return SQLITE_CORRUPT_BKPT; 2292 } 2293 (*ppPage)->isInit = 0; 2294 }else{ 2295 *ppPage = 0; 2296 } 2297 return rc; 2298 } 2299 2300 2301 /* 2302 ** During a rollback, when the pager reloads information into the cache 2303 ** so that the cache is restored to its original state at the start of 2304 ** the transaction, for each page restored this routine is called. 2305 ** 2306 ** This routine needs to reset the extra data section at the end of the 2307 ** page to agree with the restored data. 2308 */ 2309 static void pageReinit(DbPage *pData){ 2310 MemPage *pPage; 2311 pPage = (MemPage *)sqlite3PagerGetExtra(pData); 2312 assert( sqlite3PagerPageRefcount(pData)>0 ); 2313 if( pPage->isInit ){ 2314 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2315 pPage->isInit = 0; 2316 if( sqlite3PagerPageRefcount(pData)>1 ){ 2317 /* pPage might not be a btree page; it might be an overflow page 2318 ** or ptrmap page or a free page. In those cases, the following 2319 ** call to btreeInitPage() will likely return SQLITE_CORRUPT. 2320 ** But no harm is done by this. And it is very important that 2321 ** btreeInitPage() be called on every btree page so we make 2322 ** the call for every page that comes in for re-initing. */ 2323 btreeInitPage(pPage); 2324 } 2325 } 2326 } 2327 2328 /* 2329 ** Invoke the busy handler for a btree. 2330 */ 2331 static int btreeInvokeBusyHandler(void *pArg){ 2332 BtShared *pBt = (BtShared*)pArg; 2333 assert( pBt->db ); 2334 assert( sqlite3_mutex_held(pBt->db->mutex) ); 2335 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); 2336 } 2337 2338 /* 2339 ** Open a database file. 2340 ** 2341 ** zFilename is the name of the database file. If zFilename is NULL 2342 ** then an ephemeral database is created. The ephemeral database might 2343 ** be exclusively in memory, or it might use a disk-based memory cache. 2344 ** Either way, the ephemeral database will be automatically deleted 2345 ** when sqlite3BtreeClose() is called. 2346 ** 2347 ** If zFilename is ":memory:" then an in-memory database is created 2348 ** that is automatically destroyed when it is closed. 2349 ** 2350 ** The "flags" parameter is a bitmask that might contain bits like 2351 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. 2352 ** 2353 ** If the database is already opened in the same database connection 2354 ** and we are in shared cache mode, then the open will fail with an 2355 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared 2356 ** objects in the same database connection since doing so will lead 2357 ** to problems with locking. 2358 */ 2359 int sqlite3BtreeOpen( 2360 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ 2361 const char *zFilename, /* Name of the file containing the BTree database */ 2362 sqlite3 *db, /* Associated database handle */ 2363 Btree **ppBtree, /* Pointer to new Btree object written here */ 2364 int flags, /* Options */ 2365 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ 2366 ){ 2367 BtShared *pBt = 0; /* Shared part of btree structure */ 2368 Btree *p; /* Handle to return */ 2369 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ 2370 int rc = SQLITE_OK; /* Result code from this function */ 2371 u8 nReserve; /* Byte of unused space on each page */ 2372 unsigned char zDbHeader[100]; /* Database header content */ 2373 2374 /* True if opening an ephemeral, temporary database */ 2375 const int isTempDb = zFilename==0 || zFilename[0]==0; 2376 2377 /* Set the variable isMemdb to true for an in-memory database, or 2378 ** false for a file-based database. 2379 */ 2380 #ifdef SQLITE_OMIT_MEMORYDB 2381 const int isMemdb = 0; 2382 #else 2383 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) 2384 || (isTempDb && sqlite3TempInMemory(db)) 2385 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; 2386 #endif 2387 2388 assert( db!=0 ); 2389 assert( pVfs!=0 ); 2390 assert( sqlite3_mutex_held(db->mutex) ); 2391 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ 2392 2393 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ 2394 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); 2395 2396 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ 2397 assert( (flags & BTREE_SINGLE)==0 || isTempDb ); 2398 2399 if( isMemdb ){ 2400 flags |= BTREE_MEMORY; 2401 } 2402 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ 2403 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; 2404 } 2405 p = sqlite3MallocZero(sizeof(Btree)); 2406 if( !p ){ 2407 return SQLITE_NOMEM_BKPT; 2408 } 2409 p->inTrans = TRANS_NONE; 2410 p->db = db; 2411 #ifndef SQLITE_OMIT_SHARED_CACHE 2412 p->lock.pBtree = p; 2413 p->lock.iTable = 1; 2414 #endif 2415 2416 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2417 /* 2418 ** If this Btree is a candidate for shared cache, try to find an 2419 ** existing BtShared object that we can share with 2420 */ 2421 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ 2422 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ 2423 int nFilename = sqlite3Strlen30(zFilename)+1; 2424 int nFullPathname = pVfs->mxPathname+1; 2425 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); 2426 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2427 2428 p->sharable = 1; 2429 if( !zFullPathname ){ 2430 sqlite3_free(p); 2431 return SQLITE_NOMEM_BKPT; 2432 } 2433 if( isMemdb ){ 2434 memcpy(zFullPathname, zFilename, nFilename); 2435 }else{ 2436 rc = sqlite3OsFullPathname(pVfs, zFilename, 2437 nFullPathname, zFullPathname); 2438 if( rc ){ 2439 if( rc==SQLITE_OK_SYMLINK ){ 2440 rc = SQLITE_OK; 2441 }else{ 2442 sqlite3_free(zFullPathname); 2443 sqlite3_free(p); 2444 return rc; 2445 } 2446 } 2447 } 2448 #if SQLITE_THREADSAFE 2449 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); 2450 sqlite3_mutex_enter(mutexOpen); 2451 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); 2452 sqlite3_mutex_enter(mutexShared); 2453 #endif 2454 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ 2455 assert( pBt->nRef>0 ); 2456 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) 2457 && sqlite3PagerVfs(pBt->pPager)==pVfs ){ 2458 int iDb; 2459 for(iDb=db->nDb-1; iDb>=0; iDb--){ 2460 Btree *pExisting = db->aDb[iDb].pBt; 2461 if( pExisting && pExisting->pBt==pBt ){ 2462 sqlite3_mutex_leave(mutexShared); 2463 sqlite3_mutex_leave(mutexOpen); 2464 sqlite3_free(zFullPathname); 2465 sqlite3_free(p); 2466 return SQLITE_CONSTRAINT; 2467 } 2468 } 2469 p->pBt = pBt; 2470 pBt->nRef++; 2471 break; 2472 } 2473 } 2474 sqlite3_mutex_leave(mutexShared); 2475 sqlite3_free(zFullPathname); 2476 } 2477 #ifdef SQLITE_DEBUG 2478 else{ 2479 /* In debug mode, we mark all persistent databases as sharable 2480 ** even when they are not. This exercises the locking code and 2481 ** gives more opportunity for asserts(sqlite3_mutex_held()) 2482 ** statements to find locking problems. 2483 */ 2484 p->sharable = 1; 2485 } 2486 #endif 2487 } 2488 #endif 2489 if( pBt==0 ){ 2490 /* 2491 ** The following asserts make sure that structures used by the btree are 2492 ** the right size. This is to guard against size changes that result 2493 ** when compiling on a different architecture. 2494 */ 2495 assert( sizeof(i64)==8 ); 2496 assert( sizeof(u64)==8 ); 2497 assert( sizeof(u32)==4 ); 2498 assert( sizeof(u16)==2 ); 2499 assert( sizeof(Pgno)==4 ); 2500 2501 pBt = sqlite3MallocZero( sizeof(*pBt) ); 2502 if( pBt==0 ){ 2503 rc = SQLITE_NOMEM_BKPT; 2504 goto btree_open_out; 2505 } 2506 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, 2507 sizeof(MemPage), flags, vfsFlags, pageReinit); 2508 if( rc==SQLITE_OK ){ 2509 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); 2510 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); 2511 } 2512 if( rc!=SQLITE_OK ){ 2513 goto btree_open_out; 2514 } 2515 pBt->openFlags = (u8)flags; 2516 pBt->db = db; 2517 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt); 2518 p->pBt = pBt; 2519 2520 pBt->pCursor = 0; 2521 pBt->pPage1 = 0; 2522 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; 2523 #if defined(SQLITE_SECURE_DELETE) 2524 pBt->btsFlags |= BTS_SECURE_DELETE; 2525 #elif defined(SQLITE_FAST_SECURE_DELETE) 2526 pBt->btsFlags |= BTS_OVERWRITE; 2527 #endif 2528 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 2529 ** determined by the 2-byte integer located at an offset of 16 bytes from 2530 ** the beginning of the database file. */ 2531 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); 2532 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE 2533 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ 2534 pBt->pageSize = 0; 2535 #ifndef SQLITE_OMIT_AUTOVACUUM 2536 /* If the magic name ":memory:" will create an in-memory database, then 2537 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if 2538 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if 2539 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a 2540 ** regular file-name. In this case the auto-vacuum applies as per normal. 2541 */ 2542 if( zFilename && !isMemdb ){ 2543 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); 2544 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); 2545 } 2546 #endif 2547 nReserve = 0; 2548 }else{ 2549 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is 2550 ** determined by the one-byte unsigned integer found at an offset of 20 2551 ** into the database file header. */ 2552 nReserve = zDbHeader[20]; 2553 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2554 #ifndef SQLITE_OMIT_AUTOVACUUM 2555 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); 2556 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); 2557 #endif 2558 } 2559 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2560 if( rc ) goto btree_open_out; 2561 pBt->usableSize = pBt->pageSize - nReserve; 2562 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ 2563 2564 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2565 /* Add the new BtShared object to the linked list sharable BtShareds. 2566 */ 2567 pBt->nRef = 1; 2568 if( p->sharable ){ 2569 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2570 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);) 2571 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ 2572 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); 2573 if( pBt->mutex==0 ){ 2574 rc = SQLITE_NOMEM_BKPT; 2575 goto btree_open_out; 2576 } 2577 } 2578 sqlite3_mutex_enter(mutexShared); 2579 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); 2580 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; 2581 sqlite3_mutex_leave(mutexShared); 2582 } 2583 #endif 2584 } 2585 2586 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2587 /* If the new Btree uses a sharable pBtShared, then link the new 2588 ** Btree into the list of all sharable Btrees for the same connection. 2589 ** The list is kept in ascending order by pBt address. 2590 */ 2591 if( p->sharable ){ 2592 int i; 2593 Btree *pSib; 2594 for(i=0; i<db->nDb; i++){ 2595 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ 2596 while( pSib->pPrev ){ pSib = pSib->pPrev; } 2597 if( (uptr)p->pBt<(uptr)pSib->pBt ){ 2598 p->pNext = pSib; 2599 p->pPrev = 0; 2600 pSib->pPrev = p; 2601 }else{ 2602 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ 2603 pSib = pSib->pNext; 2604 } 2605 p->pNext = pSib->pNext; 2606 p->pPrev = pSib; 2607 if( p->pNext ){ 2608 p->pNext->pPrev = p; 2609 } 2610 pSib->pNext = p; 2611 } 2612 break; 2613 } 2614 } 2615 } 2616 #endif 2617 *ppBtree = p; 2618 2619 btree_open_out: 2620 if( rc!=SQLITE_OK ){ 2621 if( pBt && pBt->pPager ){ 2622 sqlite3PagerClose(pBt->pPager, 0); 2623 } 2624 sqlite3_free(pBt); 2625 sqlite3_free(p); 2626 *ppBtree = 0; 2627 }else{ 2628 sqlite3_file *pFile; 2629 2630 /* If the B-Tree was successfully opened, set the pager-cache size to the 2631 ** default value. Except, when opening on an existing shared pager-cache, 2632 ** do not change the pager-cache size. 2633 */ 2634 if( sqlite3BtreeSchema(p, 0, 0)==0 ){ 2635 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE); 2636 } 2637 2638 pFile = sqlite3PagerFile(pBt->pPager); 2639 if( pFile->pMethods ){ 2640 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db); 2641 } 2642 } 2643 if( mutexOpen ){ 2644 assert( sqlite3_mutex_held(mutexOpen) ); 2645 sqlite3_mutex_leave(mutexOpen); 2646 } 2647 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); 2648 return rc; 2649 } 2650 2651 /* 2652 ** Decrement the BtShared.nRef counter. When it reaches zero, 2653 ** remove the BtShared structure from the sharing list. Return 2654 ** true if the BtShared.nRef counter reaches zero and return 2655 ** false if it is still positive. 2656 */ 2657 static int removeFromSharingList(BtShared *pBt){ 2658 #ifndef SQLITE_OMIT_SHARED_CACHE 2659 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) 2660 BtShared *pList; 2661 int removed = 0; 2662 2663 assert( sqlite3_mutex_notheld(pBt->mutex) ); 2664 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); ) 2665 sqlite3_mutex_enter(pMainMtx); 2666 pBt->nRef--; 2667 if( pBt->nRef<=0 ){ 2668 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ 2669 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; 2670 }else{ 2671 pList = GLOBAL(BtShared*,sqlite3SharedCacheList); 2672 while( ALWAYS(pList) && pList->pNext!=pBt ){ 2673 pList=pList->pNext; 2674 } 2675 if( ALWAYS(pList) ){ 2676 pList->pNext = pBt->pNext; 2677 } 2678 } 2679 if( SQLITE_THREADSAFE ){ 2680 sqlite3_mutex_free(pBt->mutex); 2681 } 2682 removed = 1; 2683 } 2684 sqlite3_mutex_leave(pMainMtx); 2685 return removed; 2686 #else 2687 return 1; 2688 #endif 2689 } 2690 2691 /* 2692 ** Make sure pBt->pTmpSpace points to an allocation of 2693 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child 2694 ** pointer. 2695 */ 2696 static void allocateTempSpace(BtShared *pBt){ 2697 if( !pBt->pTmpSpace ){ 2698 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); 2699 2700 /* One of the uses of pBt->pTmpSpace is to format cells before 2701 ** inserting them into a leaf page (function fillInCell()). If 2702 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes 2703 ** by the various routines that manipulate binary cells. Which 2704 ** can mean that fillInCell() only initializes the first 2 or 3 2705 ** bytes of pTmpSpace, but that the first 4 bytes are copied from 2706 ** it into a database page. This is not actually a problem, but it 2707 ** does cause a valgrind error when the 1 or 2 bytes of unitialized 2708 ** data is passed to system call write(). So to avoid this error, 2709 ** zero the first 4 bytes of temp space here. 2710 ** 2711 ** Also: Provide four bytes of initialized space before the 2712 ** beginning of pTmpSpace as an area available to prepend the 2713 ** left-child pointer to the beginning of a cell. 2714 */ 2715 if( pBt->pTmpSpace ){ 2716 memset(pBt->pTmpSpace, 0, 8); 2717 pBt->pTmpSpace += 4; 2718 } 2719 } 2720 } 2721 2722 /* 2723 ** Free the pBt->pTmpSpace allocation 2724 */ 2725 static void freeTempSpace(BtShared *pBt){ 2726 if( pBt->pTmpSpace ){ 2727 pBt->pTmpSpace -= 4; 2728 sqlite3PageFree(pBt->pTmpSpace); 2729 pBt->pTmpSpace = 0; 2730 } 2731 } 2732 2733 /* 2734 ** Close an open database and invalidate all cursors. 2735 */ 2736 int sqlite3BtreeClose(Btree *p){ 2737 BtShared *pBt = p->pBt; 2738 2739 /* Close all cursors opened via this handle. */ 2740 assert( sqlite3_mutex_held(p->db->mutex) ); 2741 sqlite3BtreeEnter(p); 2742 2743 /* Verify that no other cursors have this Btree open */ 2744 #ifdef SQLITE_DEBUG 2745 { 2746 BtCursor *pCur = pBt->pCursor; 2747 while( pCur ){ 2748 BtCursor *pTmp = pCur; 2749 pCur = pCur->pNext; 2750 assert( pTmp->pBtree!=p ); 2751 2752 } 2753 } 2754 #endif 2755 2756 /* Rollback any active transaction and free the handle structure. 2757 ** The call to sqlite3BtreeRollback() drops any table-locks held by 2758 ** this handle. 2759 */ 2760 sqlite3BtreeRollback(p, SQLITE_OK, 0); 2761 sqlite3BtreeLeave(p); 2762 2763 /* If there are still other outstanding references to the shared-btree 2764 ** structure, return now. The remainder of this procedure cleans 2765 ** up the shared-btree. 2766 */ 2767 assert( p->wantToLock==0 && p->locked==0 ); 2768 if( !p->sharable || removeFromSharingList(pBt) ){ 2769 /* The pBt is no longer on the sharing list, so we can access 2770 ** it without having to hold the mutex. 2771 ** 2772 ** Clean out and delete the BtShared object. 2773 */ 2774 assert( !pBt->pCursor ); 2775 sqlite3PagerClose(pBt->pPager, p->db); 2776 if( pBt->xFreeSchema && pBt->pSchema ){ 2777 pBt->xFreeSchema(pBt->pSchema); 2778 } 2779 sqlite3DbFree(0, pBt->pSchema); 2780 freeTempSpace(pBt); 2781 sqlite3_free(pBt); 2782 } 2783 2784 #ifndef SQLITE_OMIT_SHARED_CACHE 2785 assert( p->wantToLock==0 ); 2786 assert( p->locked==0 ); 2787 if( p->pPrev ) p->pPrev->pNext = p->pNext; 2788 if( p->pNext ) p->pNext->pPrev = p->pPrev; 2789 #endif 2790 2791 sqlite3_free(p); 2792 return SQLITE_OK; 2793 } 2794 2795 /* 2796 ** Change the "soft" limit on the number of pages in the cache. 2797 ** Unused and unmodified pages will be recycled when the number of 2798 ** pages in the cache exceeds this soft limit. But the size of the 2799 ** cache is allowed to grow larger than this limit if it contains 2800 ** dirty pages or pages still in active use. 2801 */ 2802 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ 2803 BtShared *pBt = p->pBt; 2804 assert( sqlite3_mutex_held(p->db->mutex) ); 2805 sqlite3BtreeEnter(p); 2806 sqlite3PagerSetCachesize(pBt->pPager, mxPage); 2807 sqlite3BtreeLeave(p); 2808 return SQLITE_OK; 2809 } 2810 2811 /* 2812 ** Change the "spill" limit on the number of pages in the cache. 2813 ** If the number of pages exceeds this limit during a write transaction, 2814 ** the pager might attempt to "spill" pages to the journal early in 2815 ** order to free up memory. 2816 ** 2817 ** The value returned is the current spill size. If zero is passed 2818 ** as an argument, no changes are made to the spill size setting, so 2819 ** using mxPage of 0 is a way to query the current spill size. 2820 */ 2821 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ 2822 BtShared *pBt = p->pBt; 2823 int res; 2824 assert( sqlite3_mutex_held(p->db->mutex) ); 2825 sqlite3BtreeEnter(p); 2826 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); 2827 sqlite3BtreeLeave(p); 2828 return res; 2829 } 2830 2831 #if SQLITE_MAX_MMAP_SIZE>0 2832 /* 2833 ** Change the limit on the amount of the database file that may be 2834 ** memory mapped. 2835 */ 2836 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ 2837 BtShared *pBt = p->pBt; 2838 assert( sqlite3_mutex_held(p->db->mutex) ); 2839 sqlite3BtreeEnter(p); 2840 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); 2841 sqlite3BtreeLeave(p); 2842 return SQLITE_OK; 2843 } 2844 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ 2845 2846 /* 2847 ** Change the way data is synced to disk in order to increase or decrease 2848 ** how well the database resists damage due to OS crashes and power 2849 ** failures. Level 1 is the same as asynchronous (no syncs() occur and 2850 ** there is a high probability of damage) Level 2 is the default. There 2851 ** is a very low but non-zero probability of damage. Level 3 reduces the 2852 ** probability of damage to near zero but with a write performance reduction. 2853 */ 2854 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 2855 int sqlite3BtreeSetPagerFlags( 2856 Btree *p, /* The btree to set the safety level on */ 2857 unsigned pgFlags /* Various PAGER_* flags */ 2858 ){ 2859 BtShared *pBt = p->pBt; 2860 assert( sqlite3_mutex_held(p->db->mutex) ); 2861 sqlite3BtreeEnter(p); 2862 sqlite3PagerSetFlags(pBt->pPager, pgFlags); 2863 sqlite3BtreeLeave(p); 2864 return SQLITE_OK; 2865 } 2866 #endif 2867 2868 /* 2869 ** Change the default pages size and the number of reserved bytes per page. 2870 ** Or, if the page size has already been fixed, return SQLITE_READONLY 2871 ** without changing anything. 2872 ** 2873 ** The page size must be a power of 2 between 512 and 65536. If the page 2874 ** size supplied does not meet this constraint then the page size is not 2875 ** changed. 2876 ** 2877 ** Page sizes are constrained to be a power of two so that the region 2878 ** of the database file used for locking (beginning at PENDING_BYTE, 2879 ** the first byte past the 1GB boundary, 0x40000000) needs to occur 2880 ** at the beginning of a page. 2881 ** 2882 ** If parameter nReserve is less than zero, then the number of reserved 2883 ** bytes per page is left unchanged. 2884 ** 2885 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size 2886 ** and autovacuum mode can no longer be changed. 2887 */ 2888 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ 2889 int rc = SQLITE_OK; 2890 int x; 2891 BtShared *pBt = p->pBt; 2892 assert( nReserve>=0 && nReserve<=255 ); 2893 sqlite3BtreeEnter(p); 2894 pBt->nReserveWanted = nReserve; 2895 x = pBt->pageSize - pBt->usableSize; 2896 if( nReserve<x ) nReserve = x; 2897 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ 2898 sqlite3BtreeLeave(p); 2899 return SQLITE_READONLY; 2900 } 2901 assert( nReserve>=0 && nReserve<=255 ); 2902 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && 2903 ((pageSize-1)&pageSize)==0 ){ 2904 assert( (pageSize & 7)==0 ); 2905 assert( !pBt->pCursor ); 2906 if( nReserve>32 && pageSize==512 ) pageSize = 1024; 2907 pBt->pageSize = (u32)pageSize; 2908 freeTempSpace(pBt); 2909 } 2910 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2911 pBt->usableSize = pBt->pageSize - (u16)nReserve; 2912 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2913 sqlite3BtreeLeave(p); 2914 return rc; 2915 } 2916 2917 /* 2918 ** Return the currently defined page size 2919 */ 2920 int sqlite3BtreeGetPageSize(Btree *p){ 2921 return p->pBt->pageSize; 2922 } 2923 2924 /* 2925 ** This function is similar to sqlite3BtreeGetReserve(), except that it 2926 ** may only be called if it is guaranteed that the b-tree mutex is already 2927 ** held. 2928 ** 2929 ** This is useful in one special case in the backup API code where it is 2930 ** known that the shared b-tree mutex is held, but the mutex on the 2931 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() 2932 ** were to be called, it might collide with some other operation on the 2933 ** database handle that owns *p, causing undefined behavior. 2934 */ 2935 int sqlite3BtreeGetReserveNoMutex(Btree *p){ 2936 int n; 2937 assert( sqlite3_mutex_held(p->pBt->mutex) ); 2938 n = p->pBt->pageSize - p->pBt->usableSize; 2939 return n; 2940 } 2941 2942 /* 2943 ** Return the number of bytes of space at the end of every page that 2944 ** are intentually left unused. This is the "reserved" space that is 2945 ** sometimes used by extensions. 2946 ** 2947 ** The value returned is the larger of the current reserve size and 2948 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES. 2949 ** The amount of reserve can only grow - never shrink. 2950 */ 2951 int sqlite3BtreeGetRequestedReserve(Btree *p){ 2952 int n1, n2; 2953 sqlite3BtreeEnter(p); 2954 n1 = (int)p->pBt->nReserveWanted; 2955 n2 = sqlite3BtreeGetReserveNoMutex(p); 2956 sqlite3BtreeLeave(p); 2957 return n1>n2 ? n1 : n2; 2958 } 2959 2960 2961 /* 2962 ** Set the maximum page count for a database if mxPage is positive. 2963 ** No changes are made if mxPage is 0 or negative. 2964 ** Regardless of the value of mxPage, return the maximum page count. 2965 */ 2966 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){ 2967 Pgno n; 2968 sqlite3BtreeEnter(p); 2969 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); 2970 sqlite3BtreeLeave(p); 2971 return n; 2972 } 2973 2974 /* 2975 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags: 2976 ** 2977 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared 2978 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared 2979 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set 2980 ** newFlag==(-1) No changes 2981 ** 2982 ** This routine acts as a query if newFlag is less than zero 2983 ** 2984 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but 2985 ** freelist leaf pages are not written back to the database. Thus in-page 2986 ** deleted content is cleared, but freelist deleted content is not. 2987 ** 2988 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition 2989 ** that freelist leaf pages are written back into the database, increasing 2990 ** the amount of disk I/O. 2991 */ 2992 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ 2993 int b; 2994 if( p==0 ) return 0; 2995 sqlite3BtreeEnter(p); 2996 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 ); 2997 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) ); 2998 if( newFlag>=0 ){ 2999 p->pBt->btsFlags &= ~BTS_FAST_SECURE; 3000 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag; 3001 } 3002 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE; 3003 sqlite3BtreeLeave(p); 3004 return b; 3005 } 3006 3007 /* 3008 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' 3009 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it 3010 ** is disabled. The default value for the auto-vacuum property is 3011 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. 3012 */ 3013 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ 3014 #ifdef SQLITE_OMIT_AUTOVACUUM 3015 return SQLITE_READONLY; 3016 #else 3017 BtShared *pBt = p->pBt; 3018 int rc = SQLITE_OK; 3019 u8 av = (u8)autoVacuum; 3020 3021 sqlite3BtreeEnter(p); 3022 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ 3023 rc = SQLITE_READONLY; 3024 }else{ 3025 pBt->autoVacuum = av ?1:0; 3026 pBt->incrVacuum = av==2 ?1:0; 3027 } 3028 sqlite3BtreeLeave(p); 3029 return rc; 3030 #endif 3031 } 3032 3033 /* 3034 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 3035 ** enabled 1 is returned. Otherwise 0. 3036 */ 3037 int sqlite3BtreeGetAutoVacuum(Btree *p){ 3038 #ifdef SQLITE_OMIT_AUTOVACUUM 3039 return BTREE_AUTOVACUUM_NONE; 3040 #else 3041 int rc; 3042 sqlite3BtreeEnter(p); 3043 rc = ( 3044 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: 3045 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: 3046 BTREE_AUTOVACUUM_INCR 3047 ); 3048 sqlite3BtreeLeave(p); 3049 return rc; 3050 #endif 3051 } 3052 3053 /* 3054 ** If the user has not set the safety-level for this database connection 3055 ** using "PRAGMA synchronous", and if the safety-level is not already 3056 ** set to the value passed to this function as the second parameter, 3057 ** set it so. 3058 */ 3059 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \ 3060 && !defined(SQLITE_OMIT_WAL) 3061 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){ 3062 sqlite3 *db; 3063 Db *pDb; 3064 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ 3065 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } 3066 if( pDb->bSyncSet==0 3067 && pDb->safety_level!=safety_level 3068 && pDb!=&db->aDb[1] 3069 ){ 3070 pDb->safety_level = safety_level; 3071 sqlite3PagerSetFlags(pBt->pPager, 3072 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); 3073 } 3074 } 3075 } 3076 #else 3077 # define setDefaultSyncFlag(pBt,safety_level) 3078 #endif 3079 3080 /* Forward declaration */ 3081 static int newDatabase(BtShared*); 3082 3083 3084 /* 3085 ** Get a reference to pPage1 of the database file. This will 3086 ** also acquire a readlock on that file. 3087 ** 3088 ** SQLITE_OK is returned on success. If the file is not a 3089 ** well-formed database file, then SQLITE_CORRUPT is returned. 3090 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM 3091 ** is returned if we run out of memory. 3092 */ 3093 static int lockBtree(BtShared *pBt){ 3094 int rc; /* Result code from subfunctions */ 3095 MemPage *pPage1; /* Page 1 of the database file */ 3096 u32 nPage; /* Number of pages in the database */ 3097 u32 nPageFile = 0; /* Number of pages in the database file */ 3098 u32 nPageHeader; /* Number of pages in the database according to hdr */ 3099 3100 assert( sqlite3_mutex_held(pBt->mutex) ); 3101 assert( pBt->pPage1==0 ); 3102 rc = sqlite3PagerSharedLock(pBt->pPager); 3103 if( rc!=SQLITE_OK ) return rc; 3104 rc = btreeGetPage(pBt, 1, &pPage1, 0); 3105 if( rc!=SQLITE_OK ) return rc; 3106 3107 /* Do some checking to help insure the file we opened really is 3108 ** a valid database file. 3109 */ 3110 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); 3111 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile); 3112 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ 3113 nPage = nPageFile; 3114 } 3115 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){ 3116 nPage = 0; 3117 } 3118 if( nPage>0 ){ 3119 u32 pageSize; 3120 u32 usableSize; 3121 u8 *page1 = pPage1->aData; 3122 rc = SQLITE_NOTADB; 3123 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins 3124 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d 3125 ** 61 74 20 33 00. */ 3126 if( memcmp(page1, zMagicHeader, 16)!=0 ){ 3127 goto page1_init_failed; 3128 } 3129 3130 #ifdef SQLITE_OMIT_WAL 3131 if( page1[18]>1 ){ 3132 pBt->btsFlags |= BTS_READ_ONLY; 3133 } 3134 if( page1[19]>1 ){ 3135 goto page1_init_failed; 3136 } 3137 #else 3138 if( page1[18]>2 ){ 3139 pBt->btsFlags |= BTS_READ_ONLY; 3140 } 3141 if( page1[19]>2 ){ 3142 goto page1_init_failed; 3143 } 3144 3145 /* If the read version is set to 2, this database should be accessed 3146 ** in WAL mode. If the log is not already open, open it now. Then 3147 ** return SQLITE_OK and return without populating BtShared.pPage1. 3148 ** The caller detects this and calls this function again. This is 3149 ** required as the version of page 1 currently in the page1 buffer 3150 ** may not be the latest version - there may be a newer one in the log 3151 ** file. 3152 */ 3153 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ 3154 int isOpen = 0; 3155 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); 3156 if( rc!=SQLITE_OK ){ 3157 goto page1_init_failed; 3158 }else{ 3159 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1); 3160 if( isOpen==0 ){ 3161 releasePageOne(pPage1); 3162 return SQLITE_OK; 3163 } 3164 } 3165 rc = SQLITE_NOTADB; 3166 }else{ 3167 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1); 3168 } 3169 #endif 3170 3171 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload 3172 ** fractions and the leaf payload fraction values must be 64, 32, and 32. 3173 ** 3174 ** The original design allowed these amounts to vary, but as of 3175 ** version 3.6.0, we require them to be fixed. 3176 */ 3177 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ 3178 goto page1_init_failed; 3179 } 3180 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 3181 ** determined by the 2-byte integer located at an offset of 16 bytes from 3182 ** the beginning of the database file. */ 3183 pageSize = (page1[16]<<8) | (page1[17]<<16); 3184 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two 3185 ** between 512 and 65536 inclusive. */ 3186 if( ((pageSize-1)&pageSize)!=0 3187 || pageSize>SQLITE_MAX_PAGE_SIZE 3188 || pageSize<=256 3189 ){ 3190 goto page1_init_failed; 3191 } 3192 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 3193 assert( (pageSize & 7)==0 ); 3194 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte 3195 ** integer at offset 20 is the number of bytes of space at the end of 3196 ** each page to reserve for extensions. 3197 ** 3198 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is 3199 ** determined by the one-byte unsigned integer found at an offset of 20 3200 ** into the database file header. */ 3201 usableSize = pageSize - page1[20]; 3202 if( (u32)pageSize!=pBt->pageSize ){ 3203 /* After reading the first page of the database assuming a page size 3204 ** of BtShared.pageSize, we have discovered that the page-size is 3205 ** actually pageSize. Unlock the database, leave pBt->pPage1 at 3206 ** zero and return SQLITE_OK. The caller will call this function 3207 ** again with the correct page-size. 3208 */ 3209 releasePageOne(pPage1); 3210 pBt->usableSize = usableSize; 3211 pBt->pageSize = pageSize; 3212 freeTempSpace(pBt); 3213 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, 3214 pageSize-usableSize); 3215 return rc; 3216 } 3217 if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){ 3218 rc = SQLITE_CORRUPT_BKPT; 3219 goto page1_init_failed; 3220 } 3221 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to 3222 ** be less than 480. In other words, if the page size is 512, then the 3223 ** reserved space size cannot exceed 32. */ 3224 if( usableSize<480 ){ 3225 goto page1_init_failed; 3226 } 3227 pBt->pageSize = pageSize; 3228 pBt->usableSize = usableSize; 3229 #ifndef SQLITE_OMIT_AUTOVACUUM 3230 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); 3231 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); 3232 #endif 3233 } 3234 3235 /* maxLocal is the maximum amount of payload to store locally for 3236 ** a cell. Make sure it is small enough so that at least minFanout 3237 ** cells can will fit on one page. We assume a 10-byte page header. 3238 ** Besides the payload, the cell must store: 3239 ** 2-byte pointer to the cell 3240 ** 4-byte child pointer 3241 ** 9-byte nKey value 3242 ** 4-byte nData value 3243 ** 4-byte overflow page pointer 3244 ** So a cell consists of a 2-byte pointer, a header which is as much as 3245 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow 3246 ** page pointer. 3247 */ 3248 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); 3249 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); 3250 pBt->maxLeaf = (u16)(pBt->usableSize - 35); 3251 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); 3252 if( pBt->maxLocal>127 ){ 3253 pBt->max1bytePayload = 127; 3254 }else{ 3255 pBt->max1bytePayload = (u8)pBt->maxLocal; 3256 } 3257 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); 3258 pBt->pPage1 = pPage1; 3259 pBt->nPage = nPage; 3260 return SQLITE_OK; 3261 3262 page1_init_failed: 3263 releasePageOne(pPage1); 3264 pBt->pPage1 = 0; 3265 return rc; 3266 } 3267 3268 #ifndef NDEBUG 3269 /* 3270 ** Return the number of cursors open on pBt. This is for use 3271 ** in assert() expressions, so it is only compiled if NDEBUG is not 3272 ** defined. 3273 ** 3274 ** Only write cursors are counted if wrOnly is true. If wrOnly is 3275 ** false then all cursors are counted. 3276 ** 3277 ** For the purposes of this routine, a cursor is any cursor that 3278 ** is capable of reading or writing to the database. Cursors that 3279 ** have been tripped into the CURSOR_FAULT state are not counted. 3280 */ 3281 static int countValidCursors(BtShared *pBt, int wrOnly){ 3282 BtCursor *pCur; 3283 int r = 0; 3284 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ 3285 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) 3286 && pCur->eState!=CURSOR_FAULT ) r++; 3287 } 3288 return r; 3289 } 3290 #endif 3291 3292 /* 3293 ** If there are no outstanding cursors and we are not in the middle 3294 ** of a transaction but there is a read lock on the database, then 3295 ** this routine unrefs the first page of the database file which 3296 ** has the effect of releasing the read lock. 3297 ** 3298 ** If there is a transaction in progress, this routine is a no-op. 3299 */ 3300 static void unlockBtreeIfUnused(BtShared *pBt){ 3301 assert( sqlite3_mutex_held(pBt->mutex) ); 3302 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); 3303 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ 3304 MemPage *pPage1 = pBt->pPage1; 3305 assert( pPage1->aData ); 3306 assert( sqlite3PagerRefcount(pBt->pPager)==1 ); 3307 pBt->pPage1 = 0; 3308 releasePageOne(pPage1); 3309 } 3310 } 3311 3312 /* 3313 ** If pBt points to an empty file then convert that empty file 3314 ** into a new empty database by initializing the first page of 3315 ** the database. 3316 */ 3317 static int newDatabase(BtShared *pBt){ 3318 MemPage *pP1; 3319 unsigned char *data; 3320 int rc; 3321 3322 assert( sqlite3_mutex_held(pBt->mutex) ); 3323 if( pBt->nPage>0 ){ 3324 return SQLITE_OK; 3325 } 3326 pP1 = pBt->pPage1; 3327 assert( pP1!=0 ); 3328 data = pP1->aData; 3329 rc = sqlite3PagerWrite(pP1->pDbPage); 3330 if( rc ) return rc; 3331 memcpy(data, zMagicHeader, sizeof(zMagicHeader)); 3332 assert( sizeof(zMagicHeader)==16 ); 3333 data[16] = (u8)((pBt->pageSize>>8)&0xff); 3334 data[17] = (u8)((pBt->pageSize>>16)&0xff); 3335 data[18] = 1; 3336 data[19] = 1; 3337 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); 3338 data[20] = (u8)(pBt->pageSize - pBt->usableSize); 3339 data[21] = 64; 3340 data[22] = 32; 3341 data[23] = 32; 3342 memset(&data[24], 0, 100-24); 3343 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); 3344 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 3345 #ifndef SQLITE_OMIT_AUTOVACUUM 3346 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); 3347 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); 3348 put4byte(&data[36 + 4*4], pBt->autoVacuum); 3349 put4byte(&data[36 + 7*4], pBt->incrVacuum); 3350 #endif 3351 pBt->nPage = 1; 3352 data[31] = 1; 3353 return SQLITE_OK; 3354 } 3355 3356 /* 3357 ** Initialize the first page of the database file (creating a database 3358 ** consisting of a single page and no schema objects). Return SQLITE_OK 3359 ** if successful, or an SQLite error code otherwise. 3360 */ 3361 int sqlite3BtreeNewDb(Btree *p){ 3362 int rc; 3363 sqlite3BtreeEnter(p); 3364 p->pBt->nPage = 0; 3365 rc = newDatabase(p->pBt); 3366 sqlite3BtreeLeave(p); 3367 return rc; 3368 } 3369 3370 /* 3371 ** Attempt to start a new transaction. A write-transaction 3372 ** is started if the second argument is nonzero, otherwise a read- 3373 ** transaction. If the second argument is 2 or more and exclusive 3374 ** transaction is started, meaning that no other process is allowed 3375 ** to access the database. A preexisting transaction may not be 3376 ** upgraded to exclusive by calling this routine a second time - the 3377 ** exclusivity flag only works for a new transaction. 3378 ** 3379 ** A write-transaction must be started before attempting any 3380 ** changes to the database. None of the following routines 3381 ** will work unless a transaction is started first: 3382 ** 3383 ** sqlite3BtreeCreateTable() 3384 ** sqlite3BtreeCreateIndex() 3385 ** sqlite3BtreeClearTable() 3386 ** sqlite3BtreeDropTable() 3387 ** sqlite3BtreeInsert() 3388 ** sqlite3BtreeDelete() 3389 ** sqlite3BtreeUpdateMeta() 3390 ** 3391 ** If an initial attempt to acquire the lock fails because of lock contention 3392 ** and the database was previously unlocked, then invoke the busy handler 3393 ** if there is one. But if there was previously a read-lock, do not 3394 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is 3395 ** returned when there is already a read-lock in order to avoid a deadlock. 3396 ** 3397 ** Suppose there are two processes A and B. A has a read lock and B has 3398 ** a reserved lock. B tries to promote to exclusive but is blocked because 3399 ** of A's read lock. A tries to promote to reserved but is blocked by B. 3400 ** One or the other of the two processes must give way or there can be 3401 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback 3402 ** when A already has a read lock, we encourage A to give up and let B 3403 ** proceed. 3404 */ 3405 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){ 3406 BtShared *pBt = p->pBt; 3407 Pager *pPager = pBt->pPager; 3408 int rc = SQLITE_OK; 3409 3410 sqlite3BtreeEnter(p); 3411 btreeIntegrity(p); 3412 3413 /* If the btree is already in a write-transaction, or it 3414 ** is already in a read-transaction and a read-transaction 3415 ** is requested, this is a no-op. 3416 */ 3417 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ 3418 goto trans_begun; 3419 } 3420 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); 3421 3422 if( (p->db->flags & SQLITE_ResetDatabase) 3423 && sqlite3PagerIsreadonly(pPager)==0 3424 ){ 3425 pBt->btsFlags &= ~BTS_READ_ONLY; 3426 } 3427 3428 /* Write transactions are not possible on a read-only database */ 3429 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ 3430 rc = SQLITE_READONLY; 3431 goto trans_begun; 3432 } 3433 3434 #ifndef SQLITE_OMIT_SHARED_CACHE 3435 { 3436 sqlite3 *pBlock = 0; 3437 /* If another database handle has already opened a write transaction 3438 ** on this shared-btree structure and a second write transaction is 3439 ** requested, return SQLITE_LOCKED. 3440 */ 3441 if( (wrflag && pBt->inTransaction==TRANS_WRITE) 3442 || (pBt->btsFlags & BTS_PENDING)!=0 3443 ){ 3444 pBlock = pBt->pWriter->db; 3445 }else if( wrflag>1 ){ 3446 BtLock *pIter; 3447 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 3448 if( pIter->pBtree!=p ){ 3449 pBlock = pIter->pBtree->db; 3450 break; 3451 } 3452 } 3453 } 3454 if( pBlock ){ 3455 sqlite3ConnectionBlocked(p->db, pBlock); 3456 rc = SQLITE_LOCKED_SHAREDCACHE; 3457 goto trans_begun; 3458 } 3459 } 3460 #endif 3461 3462 /* Any read-only or read-write transaction implies a read-lock on 3463 ** page 1. So if some other shared-cache client already has a write-lock 3464 ** on page 1, the transaction cannot be opened. */ 3465 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); 3466 if( SQLITE_OK!=rc ) goto trans_begun; 3467 3468 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; 3469 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; 3470 do { 3471 sqlite3PagerWalDb(pPager, p->db); 3472 3473 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 3474 /* If transitioning from no transaction directly to a write transaction, 3475 ** block for the WRITER lock first if possible. */ 3476 if( pBt->pPage1==0 && wrflag ){ 3477 assert( pBt->inTransaction==TRANS_NONE ); 3478 rc = sqlite3PagerWalWriteLock(pPager, 1); 3479 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break; 3480 } 3481 #endif 3482 3483 /* Call lockBtree() until either pBt->pPage1 is populated or 3484 ** lockBtree() returns something other than SQLITE_OK. lockBtree() 3485 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after 3486 ** reading page 1 it discovers that the page-size of the database 3487 ** file is not pBt->pageSize. In this case lockBtree() will update 3488 ** pBt->pageSize to the page-size of the file on disk. 3489 */ 3490 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); 3491 3492 if( rc==SQLITE_OK && wrflag ){ 3493 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ 3494 rc = SQLITE_READONLY; 3495 }else{ 3496 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db)); 3497 if( rc==SQLITE_OK ){ 3498 rc = newDatabase(pBt); 3499 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){ 3500 /* if there was no transaction opened when this function was 3501 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error 3502 ** code to SQLITE_BUSY. */ 3503 rc = SQLITE_BUSY; 3504 } 3505 } 3506 } 3507 3508 if( rc!=SQLITE_OK ){ 3509 (void)sqlite3PagerWalWriteLock(pPager, 0); 3510 unlockBtreeIfUnused(pBt); 3511 } 3512 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && 3513 btreeInvokeBusyHandler(pBt) ); 3514 sqlite3PagerWalDb(pPager, 0); 3515 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 3516 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY; 3517 #endif 3518 3519 if( rc==SQLITE_OK ){ 3520 if( p->inTrans==TRANS_NONE ){ 3521 pBt->nTransaction++; 3522 #ifndef SQLITE_OMIT_SHARED_CACHE 3523 if( p->sharable ){ 3524 assert( p->lock.pBtree==p && p->lock.iTable==1 ); 3525 p->lock.eLock = READ_LOCK; 3526 p->lock.pNext = pBt->pLock; 3527 pBt->pLock = &p->lock; 3528 } 3529 #endif 3530 } 3531 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); 3532 if( p->inTrans>pBt->inTransaction ){ 3533 pBt->inTransaction = p->inTrans; 3534 } 3535 if( wrflag ){ 3536 MemPage *pPage1 = pBt->pPage1; 3537 #ifndef SQLITE_OMIT_SHARED_CACHE 3538 assert( !pBt->pWriter ); 3539 pBt->pWriter = p; 3540 pBt->btsFlags &= ~BTS_EXCLUSIVE; 3541 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; 3542 #endif 3543 3544 /* If the db-size header field is incorrect (as it may be if an old 3545 ** client has been writing the database file), update it now. Doing 3546 ** this sooner rather than later means the database size can safely 3547 ** re-read the database size from page 1 if a savepoint or transaction 3548 ** rollback occurs within the transaction. 3549 */ 3550 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ 3551 rc = sqlite3PagerWrite(pPage1->pDbPage); 3552 if( rc==SQLITE_OK ){ 3553 put4byte(&pPage1->aData[28], pBt->nPage); 3554 } 3555 } 3556 } 3557 } 3558 3559 trans_begun: 3560 if( rc==SQLITE_OK ){ 3561 if( pSchemaVersion ){ 3562 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]); 3563 } 3564 if( wrflag ){ 3565 /* This call makes sure that the pager has the correct number of 3566 ** open savepoints. If the second parameter is greater than 0 and 3567 ** the sub-journal is not already open, then it will be opened here. 3568 */ 3569 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint); 3570 } 3571 } 3572 3573 btreeIntegrity(p); 3574 sqlite3BtreeLeave(p); 3575 return rc; 3576 } 3577 3578 #ifndef SQLITE_OMIT_AUTOVACUUM 3579 3580 /* 3581 ** Set the pointer-map entries for all children of page pPage. Also, if 3582 ** pPage contains cells that point to overflow pages, set the pointer 3583 ** map entries for the overflow pages as well. 3584 */ 3585 static int setChildPtrmaps(MemPage *pPage){ 3586 int i; /* Counter variable */ 3587 int nCell; /* Number of cells in page pPage */ 3588 int rc; /* Return code */ 3589 BtShared *pBt = pPage->pBt; 3590 Pgno pgno = pPage->pgno; 3591 3592 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3593 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); 3594 if( rc!=SQLITE_OK ) return rc; 3595 nCell = pPage->nCell; 3596 3597 for(i=0; i<nCell; i++){ 3598 u8 *pCell = findCell(pPage, i); 3599 3600 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc); 3601 3602 if( !pPage->leaf ){ 3603 Pgno childPgno = get4byte(pCell); 3604 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3605 } 3606 } 3607 3608 if( !pPage->leaf ){ 3609 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 3610 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3611 } 3612 3613 return rc; 3614 } 3615 3616 /* 3617 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so 3618 ** that it points to iTo. Parameter eType describes the type of pointer to 3619 ** be modified, as follows: 3620 ** 3621 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child 3622 ** page of pPage. 3623 ** 3624 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow 3625 ** page pointed to by one of the cells on pPage. 3626 ** 3627 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next 3628 ** overflow page in the list. 3629 */ 3630 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ 3631 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3632 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 3633 if( eType==PTRMAP_OVERFLOW2 ){ 3634 /* The pointer is always the first 4 bytes of the page in this case. */ 3635 if( get4byte(pPage->aData)!=iFrom ){ 3636 return SQLITE_CORRUPT_PAGE(pPage); 3637 } 3638 put4byte(pPage->aData, iTo); 3639 }else{ 3640 int i; 3641 int nCell; 3642 int rc; 3643 3644 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); 3645 if( rc ) return rc; 3646 nCell = pPage->nCell; 3647 3648 for(i=0; i<nCell; i++){ 3649 u8 *pCell = findCell(pPage, i); 3650 if( eType==PTRMAP_OVERFLOW1 ){ 3651 CellInfo info; 3652 pPage->xParseCell(pPage, pCell, &info); 3653 if( info.nLocal<info.nPayload ){ 3654 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){ 3655 return SQLITE_CORRUPT_PAGE(pPage); 3656 } 3657 if( iFrom==get4byte(pCell+info.nSize-4) ){ 3658 put4byte(pCell+info.nSize-4, iTo); 3659 break; 3660 } 3661 } 3662 }else{ 3663 if( get4byte(pCell)==iFrom ){ 3664 put4byte(pCell, iTo); 3665 break; 3666 } 3667 } 3668 } 3669 3670 if( i==nCell ){ 3671 if( eType!=PTRMAP_BTREE || 3672 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ 3673 return SQLITE_CORRUPT_PAGE(pPage); 3674 } 3675 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); 3676 } 3677 } 3678 return SQLITE_OK; 3679 } 3680 3681 3682 /* 3683 ** Move the open database page pDbPage to location iFreePage in the 3684 ** database. The pDbPage reference remains valid. 3685 ** 3686 ** The isCommit flag indicates that there is no need to remember that 3687 ** the journal needs to be sync()ed before database page pDbPage->pgno 3688 ** can be written to. The caller has already promised not to write to that 3689 ** page. 3690 */ 3691 static int relocatePage( 3692 BtShared *pBt, /* Btree */ 3693 MemPage *pDbPage, /* Open page to move */ 3694 u8 eType, /* Pointer map 'type' entry for pDbPage */ 3695 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ 3696 Pgno iFreePage, /* The location to move pDbPage to */ 3697 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ 3698 ){ 3699 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ 3700 Pgno iDbPage = pDbPage->pgno; 3701 Pager *pPager = pBt->pPager; 3702 int rc; 3703 3704 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 3705 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); 3706 assert( sqlite3_mutex_held(pBt->mutex) ); 3707 assert( pDbPage->pBt==pBt ); 3708 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT; 3709 3710 /* Move page iDbPage from its current location to page number iFreePage */ 3711 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 3712 iDbPage, iFreePage, iPtrPage, eType)); 3713 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); 3714 if( rc!=SQLITE_OK ){ 3715 return rc; 3716 } 3717 pDbPage->pgno = iFreePage; 3718 3719 /* If pDbPage was a btree-page, then it may have child pages and/or cells 3720 ** that point to overflow pages. The pointer map entries for all these 3721 ** pages need to be changed. 3722 ** 3723 ** If pDbPage is an overflow page, then the first 4 bytes may store a 3724 ** pointer to a subsequent overflow page. If this is the case, then 3725 ** the pointer map needs to be updated for the subsequent overflow page. 3726 */ 3727 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ 3728 rc = setChildPtrmaps(pDbPage); 3729 if( rc!=SQLITE_OK ){ 3730 return rc; 3731 } 3732 }else{ 3733 Pgno nextOvfl = get4byte(pDbPage->aData); 3734 if( nextOvfl!=0 ){ 3735 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); 3736 if( rc!=SQLITE_OK ){ 3737 return rc; 3738 } 3739 } 3740 } 3741 3742 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so 3743 ** that it points at iFreePage. Also fix the pointer map entry for 3744 ** iPtrPage. 3745 */ 3746 if( eType!=PTRMAP_ROOTPAGE ){ 3747 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); 3748 if( rc!=SQLITE_OK ){ 3749 return rc; 3750 } 3751 rc = sqlite3PagerWrite(pPtrPage->pDbPage); 3752 if( rc!=SQLITE_OK ){ 3753 releasePage(pPtrPage); 3754 return rc; 3755 } 3756 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); 3757 releasePage(pPtrPage); 3758 if( rc==SQLITE_OK ){ 3759 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); 3760 } 3761 } 3762 return rc; 3763 } 3764 3765 /* Forward declaration required by incrVacuumStep(). */ 3766 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); 3767 3768 /* 3769 ** Perform a single step of an incremental-vacuum. If successful, return 3770 ** SQLITE_OK. If there is no work to do (and therefore no point in 3771 ** calling this function again), return SQLITE_DONE. Or, if an error 3772 ** occurs, return some other error code. 3773 ** 3774 ** More specifically, this function attempts to re-organize the database so 3775 ** that the last page of the file currently in use is no longer in use. 3776 ** 3777 ** Parameter nFin is the number of pages that this database would contain 3778 ** were this function called until it returns SQLITE_DONE. 3779 ** 3780 ** If the bCommit parameter is non-zero, this function assumes that the 3781 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 3782 ** or an error. bCommit is passed true for an auto-vacuum-on-commit 3783 ** operation, or false for an incremental vacuum. 3784 */ 3785 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ 3786 Pgno nFreeList; /* Number of pages still on the free-list */ 3787 int rc; 3788 3789 assert( sqlite3_mutex_held(pBt->mutex) ); 3790 assert( iLastPg>nFin ); 3791 3792 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ 3793 u8 eType; 3794 Pgno iPtrPage; 3795 3796 nFreeList = get4byte(&pBt->pPage1->aData[36]); 3797 if( nFreeList==0 ){ 3798 return SQLITE_DONE; 3799 } 3800 3801 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); 3802 if( rc!=SQLITE_OK ){ 3803 return rc; 3804 } 3805 if( eType==PTRMAP_ROOTPAGE ){ 3806 return SQLITE_CORRUPT_BKPT; 3807 } 3808 3809 if( eType==PTRMAP_FREEPAGE ){ 3810 if( bCommit==0 ){ 3811 /* Remove the page from the files free-list. This is not required 3812 ** if bCommit is non-zero. In that case, the free-list will be 3813 ** truncated to zero after this function returns, so it doesn't 3814 ** matter if it still contains some garbage entries. 3815 */ 3816 Pgno iFreePg; 3817 MemPage *pFreePg; 3818 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); 3819 if( rc!=SQLITE_OK ){ 3820 return rc; 3821 } 3822 assert( iFreePg==iLastPg ); 3823 releasePage(pFreePg); 3824 } 3825 } else { 3826 Pgno iFreePg; /* Index of free page to move pLastPg to */ 3827 MemPage *pLastPg; 3828 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ 3829 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ 3830 3831 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); 3832 if( rc!=SQLITE_OK ){ 3833 return rc; 3834 } 3835 3836 /* If bCommit is zero, this loop runs exactly once and page pLastPg 3837 ** is swapped with the first free page pulled off the free list. 3838 ** 3839 ** On the other hand, if bCommit is greater than zero, then keep 3840 ** looping until a free-page located within the first nFin pages 3841 ** of the file is found. 3842 */ 3843 if( bCommit==0 ){ 3844 eMode = BTALLOC_LE; 3845 iNear = nFin; 3846 } 3847 do { 3848 MemPage *pFreePg; 3849 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); 3850 if( rc!=SQLITE_OK ){ 3851 releasePage(pLastPg); 3852 return rc; 3853 } 3854 releasePage(pFreePg); 3855 }while( bCommit && iFreePg>nFin ); 3856 assert( iFreePg<iLastPg ); 3857 3858 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); 3859 releasePage(pLastPg); 3860 if( rc!=SQLITE_OK ){ 3861 return rc; 3862 } 3863 } 3864 } 3865 3866 if( bCommit==0 ){ 3867 do { 3868 iLastPg--; 3869 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) ); 3870 pBt->bDoTruncate = 1; 3871 pBt->nPage = iLastPg; 3872 } 3873 return SQLITE_OK; 3874 } 3875 3876 /* 3877 ** The database opened by the first argument is an auto-vacuum database 3878 ** nOrig pages in size containing nFree free pages. Return the expected 3879 ** size of the database in pages following an auto-vacuum operation. 3880 */ 3881 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ 3882 int nEntry; /* Number of entries on one ptrmap page */ 3883 Pgno nPtrmap; /* Number of PtrMap pages to be freed */ 3884 Pgno nFin; /* Return value */ 3885 3886 nEntry = pBt->usableSize/5; 3887 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; 3888 nFin = nOrig - nFree - nPtrmap; 3889 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ 3890 nFin--; 3891 } 3892 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ 3893 nFin--; 3894 } 3895 3896 return nFin; 3897 } 3898 3899 /* 3900 ** A write-transaction must be opened before calling this function. 3901 ** It performs a single unit of work towards an incremental vacuum. 3902 ** 3903 ** If the incremental vacuum is finished after this function has run, 3904 ** SQLITE_DONE is returned. If it is not finished, but no error occurred, 3905 ** SQLITE_OK is returned. Otherwise an SQLite error code. 3906 */ 3907 int sqlite3BtreeIncrVacuum(Btree *p){ 3908 int rc; 3909 BtShared *pBt = p->pBt; 3910 3911 sqlite3BtreeEnter(p); 3912 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); 3913 if( !pBt->autoVacuum ){ 3914 rc = SQLITE_DONE; 3915 }else{ 3916 Pgno nOrig = btreePagecount(pBt); 3917 Pgno nFree = get4byte(&pBt->pPage1->aData[36]); 3918 Pgno nFin = finalDbSize(pBt, nOrig, nFree); 3919 3920 if( nOrig<nFin || nFree>=nOrig ){ 3921 rc = SQLITE_CORRUPT_BKPT; 3922 }else if( nFree>0 ){ 3923 rc = saveAllCursors(pBt, 0, 0); 3924 if( rc==SQLITE_OK ){ 3925 invalidateAllOverflowCache(pBt); 3926 rc = incrVacuumStep(pBt, nFin, nOrig, 0); 3927 } 3928 if( rc==SQLITE_OK ){ 3929 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3930 put4byte(&pBt->pPage1->aData[28], pBt->nPage); 3931 } 3932 }else{ 3933 rc = SQLITE_DONE; 3934 } 3935 } 3936 sqlite3BtreeLeave(p); 3937 return rc; 3938 } 3939 3940 /* 3941 ** This routine is called prior to sqlite3PagerCommit when a transaction 3942 ** is committed for an auto-vacuum database. 3943 ** 3944 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages 3945 ** the database file should be truncated to during the commit process. 3946 ** i.e. the database has been reorganized so that only the first *pnTrunc 3947 ** pages are in use. 3948 */ 3949 static int autoVacuumCommit(BtShared *pBt){ 3950 int rc = SQLITE_OK; 3951 Pager *pPager = pBt->pPager; 3952 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) 3953 3954 assert( sqlite3_mutex_held(pBt->mutex) ); 3955 invalidateAllOverflowCache(pBt); 3956 assert(pBt->autoVacuum); 3957 if( !pBt->incrVacuum ){ 3958 Pgno nFin; /* Number of pages in database after autovacuuming */ 3959 Pgno nFree; /* Number of pages on the freelist initially */ 3960 Pgno iFree; /* The next page to be freed */ 3961 Pgno nOrig; /* Database size before freeing */ 3962 3963 nOrig = btreePagecount(pBt); 3964 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ 3965 /* It is not possible to create a database for which the final page 3966 ** is either a pointer-map page or the pending-byte page. If one 3967 ** is encountered, this indicates corruption. 3968 */ 3969 return SQLITE_CORRUPT_BKPT; 3970 } 3971 3972 nFree = get4byte(&pBt->pPage1->aData[36]); 3973 nFin = finalDbSize(pBt, nOrig, nFree); 3974 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; 3975 if( nFin<nOrig ){ 3976 rc = saveAllCursors(pBt, 0, 0); 3977 } 3978 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ 3979 rc = incrVacuumStep(pBt, nFin, iFree, 1); 3980 } 3981 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ 3982 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3983 put4byte(&pBt->pPage1->aData[32], 0); 3984 put4byte(&pBt->pPage1->aData[36], 0); 3985 put4byte(&pBt->pPage1->aData[28], nFin); 3986 pBt->bDoTruncate = 1; 3987 pBt->nPage = nFin; 3988 } 3989 if( rc!=SQLITE_OK ){ 3990 sqlite3PagerRollback(pPager); 3991 } 3992 } 3993 3994 assert( nRef>=sqlite3PagerRefcount(pPager) ); 3995 return rc; 3996 } 3997 3998 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ 3999 # define setChildPtrmaps(x) SQLITE_OK 4000 #endif 4001 4002 /* 4003 ** This routine does the first phase of a two-phase commit. This routine 4004 ** causes a rollback journal to be created (if it does not already exist) 4005 ** and populated with enough information so that if a power loss occurs 4006 ** the database can be restored to its original state by playing back 4007 ** the journal. Then the contents of the journal are flushed out to 4008 ** the disk. After the journal is safely on oxide, the changes to the 4009 ** database are written into the database file and flushed to oxide. 4010 ** At the end of this call, the rollback journal still exists on the 4011 ** disk and we are still holding all locks, so the transaction has not 4012 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the 4013 ** commit process. 4014 ** 4015 ** This call is a no-op if no write-transaction is currently active on pBt. 4016 ** 4017 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to 4018 ** the name of a super-journal file that should be written into the 4019 ** individual journal file, or is NULL, indicating no super-journal file 4020 ** (single database transaction). 4021 ** 4022 ** When this is called, the super-journal should already have been 4023 ** created, populated with this journal pointer and synced to disk. 4024 ** 4025 ** Once this is routine has returned, the only thing required to commit 4026 ** the write-transaction for this database file is to delete the journal. 4027 */ 4028 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){ 4029 int rc = SQLITE_OK; 4030 if( p->inTrans==TRANS_WRITE ){ 4031 BtShared *pBt = p->pBt; 4032 sqlite3BtreeEnter(p); 4033 #ifndef SQLITE_OMIT_AUTOVACUUM 4034 if( pBt->autoVacuum ){ 4035 rc = autoVacuumCommit(pBt); 4036 if( rc!=SQLITE_OK ){ 4037 sqlite3BtreeLeave(p); 4038 return rc; 4039 } 4040 } 4041 if( pBt->bDoTruncate ){ 4042 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); 4043 } 4044 #endif 4045 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0); 4046 sqlite3BtreeLeave(p); 4047 } 4048 return rc; 4049 } 4050 4051 /* 4052 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() 4053 ** at the conclusion of a transaction. 4054 */ 4055 static void btreeEndTransaction(Btree *p){ 4056 BtShared *pBt = p->pBt; 4057 sqlite3 *db = p->db; 4058 assert( sqlite3BtreeHoldsMutex(p) ); 4059 4060 #ifndef SQLITE_OMIT_AUTOVACUUM 4061 pBt->bDoTruncate = 0; 4062 #endif 4063 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ 4064 /* If there are other active statements that belong to this database 4065 ** handle, downgrade to a read-only transaction. The other statements 4066 ** may still be reading from the database. */ 4067 downgradeAllSharedCacheTableLocks(p); 4068 p->inTrans = TRANS_READ; 4069 }else{ 4070 /* If the handle had any kind of transaction open, decrement the 4071 ** transaction count of the shared btree. If the transaction count 4072 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() 4073 ** call below will unlock the pager. */ 4074 if( p->inTrans!=TRANS_NONE ){ 4075 clearAllSharedCacheTableLocks(p); 4076 pBt->nTransaction--; 4077 if( 0==pBt->nTransaction ){ 4078 pBt->inTransaction = TRANS_NONE; 4079 } 4080 } 4081 4082 /* Set the current transaction state to TRANS_NONE and unlock the 4083 ** pager if this call closed the only read or write transaction. */ 4084 p->inTrans = TRANS_NONE; 4085 unlockBtreeIfUnused(pBt); 4086 } 4087 4088 btreeIntegrity(p); 4089 } 4090 4091 /* 4092 ** Commit the transaction currently in progress. 4093 ** 4094 ** This routine implements the second phase of a 2-phase commit. The 4095 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should 4096 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() 4097 ** routine did all the work of writing information out to disk and flushing the 4098 ** contents so that they are written onto the disk platter. All this 4099 ** routine has to do is delete or truncate or zero the header in the 4100 ** the rollback journal (which causes the transaction to commit) and 4101 ** drop locks. 4102 ** 4103 ** Normally, if an error occurs while the pager layer is attempting to 4104 ** finalize the underlying journal file, this function returns an error and 4105 ** the upper layer will attempt a rollback. However, if the second argument 4106 ** is non-zero then this b-tree transaction is part of a multi-file 4107 ** transaction. In this case, the transaction has already been committed 4108 ** (by deleting a super-journal file) and the caller will ignore this 4109 ** functions return code. So, even if an error occurs in the pager layer, 4110 ** reset the b-tree objects internal state to indicate that the write 4111 ** transaction has been closed. This is quite safe, as the pager will have 4112 ** transitioned to the error state. 4113 ** 4114 ** This will release the write lock on the database file. If there 4115 ** are no active cursors, it also releases the read lock. 4116 */ 4117 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ 4118 4119 if( p->inTrans==TRANS_NONE ) return SQLITE_OK; 4120 sqlite3BtreeEnter(p); 4121 btreeIntegrity(p); 4122 4123 /* If the handle has a write-transaction open, commit the shared-btrees 4124 ** transaction and set the shared state to TRANS_READ. 4125 */ 4126 if( p->inTrans==TRANS_WRITE ){ 4127 int rc; 4128 BtShared *pBt = p->pBt; 4129 assert( pBt->inTransaction==TRANS_WRITE ); 4130 assert( pBt->nTransaction>0 ); 4131 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); 4132 if( rc!=SQLITE_OK && bCleanup==0 ){ 4133 sqlite3BtreeLeave(p); 4134 return rc; 4135 } 4136 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */ 4137 pBt->inTransaction = TRANS_READ; 4138 btreeClearHasContent(pBt); 4139 } 4140 4141 btreeEndTransaction(p); 4142 sqlite3BtreeLeave(p); 4143 return SQLITE_OK; 4144 } 4145 4146 /* 4147 ** Do both phases of a commit. 4148 */ 4149 int sqlite3BtreeCommit(Btree *p){ 4150 int rc; 4151 sqlite3BtreeEnter(p); 4152 rc = sqlite3BtreeCommitPhaseOne(p, 0); 4153 if( rc==SQLITE_OK ){ 4154 rc = sqlite3BtreeCommitPhaseTwo(p, 0); 4155 } 4156 sqlite3BtreeLeave(p); 4157 return rc; 4158 } 4159 4160 /* 4161 ** This routine sets the state to CURSOR_FAULT and the error 4162 ** code to errCode for every cursor on any BtShared that pBtree 4163 ** references. Or if the writeOnly flag is set to 1, then only 4164 ** trip write cursors and leave read cursors unchanged. 4165 ** 4166 ** Every cursor is a candidate to be tripped, including cursors 4167 ** that belong to other database connections that happen to be 4168 ** sharing the cache with pBtree. 4169 ** 4170 ** This routine gets called when a rollback occurs. If the writeOnly 4171 ** flag is true, then only write-cursors need be tripped - read-only 4172 ** cursors save their current positions so that they may continue 4173 ** following the rollback. Or, if writeOnly is false, all cursors are 4174 ** tripped. In general, writeOnly is false if the transaction being 4175 ** rolled back modified the database schema. In this case b-tree root 4176 ** pages may be moved or deleted from the database altogether, making 4177 ** it unsafe for read cursors to continue. 4178 ** 4179 ** If the writeOnly flag is true and an error is encountered while 4180 ** saving the current position of a read-only cursor, all cursors, 4181 ** including all read-cursors are tripped. 4182 ** 4183 ** SQLITE_OK is returned if successful, or if an error occurs while 4184 ** saving a cursor position, an SQLite error code. 4185 */ 4186 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ 4187 BtCursor *p; 4188 int rc = SQLITE_OK; 4189 4190 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); 4191 if( pBtree ){ 4192 sqlite3BtreeEnter(pBtree); 4193 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 4194 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ 4195 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 4196 rc = saveCursorPosition(p); 4197 if( rc!=SQLITE_OK ){ 4198 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); 4199 break; 4200 } 4201 } 4202 }else{ 4203 sqlite3BtreeClearCursor(p); 4204 p->eState = CURSOR_FAULT; 4205 p->skipNext = errCode; 4206 } 4207 btreeReleaseAllCursorPages(p); 4208 } 4209 sqlite3BtreeLeave(pBtree); 4210 } 4211 return rc; 4212 } 4213 4214 /* 4215 ** Set the pBt->nPage field correctly, according to the current 4216 ** state of the database. Assume pBt->pPage1 is valid. 4217 */ 4218 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){ 4219 int nPage = get4byte(&pPage1->aData[28]); 4220 testcase( nPage==0 ); 4221 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); 4222 testcase( pBt->nPage!=nPage ); 4223 pBt->nPage = nPage; 4224 } 4225 4226 /* 4227 ** Rollback the transaction in progress. 4228 ** 4229 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). 4230 ** Only write cursors are tripped if writeOnly is true but all cursors are 4231 ** tripped if writeOnly is false. Any attempt to use 4232 ** a tripped cursor will result in an error. 4233 ** 4234 ** This will release the write lock on the database file. If there 4235 ** are no active cursors, it also releases the read lock. 4236 */ 4237 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ 4238 int rc; 4239 BtShared *pBt = p->pBt; 4240 MemPage *pPage1; 4241 4242 assert( writeOnly==1 || writeOnly==0 ); 4243 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); 4244 sqlite3BtreeEnter(p); 4245 if( tripCode==SQLITE_OK ){ 4246 rc = tripCode = saveAllCursors(pBt, 0, 0); 4247 if( rc ) writeOnly = 0; 4248 }else{ 4249 rc = SQLITE_OK; 4250 } 4251 if( tripCode ){ 4252 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); 4253 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); 4254 if( rc2!=SQLITE_OK ) rc = rc2; 4255 } 4256 btreeIntegrity(p); 4257 4258 if( p->inTrans==TRANS_WRITE ){ 4259 int rc2; 4260 4261 assert( TRANS_WRITE==pBt->inTransaction ); 4262 rc2 = sqlite3PagerRollback(pBt->pPager); 4263 if( rc2!=SQLITE_OK ){ 4264 rc = rc2; 4265 } 4266 4267 /* The rollback may have destroyed the pPage1->aData value. So 4268 ** call btreeGetPage() on page 1 again to make 4269 ** sure pPage1->aData is set correctly. */ 4270 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ 4271 btreeSetNPage(pBt, pPage1); 4272 releasePageOne(pPage1); 4273 } 4274 assert( countValidCursors(pBt, 1)==0 ); 4275 pBt->inTransaction = TRANS_READ; 4276 btreeClearHasContent(pBt); 4277 } 4278 4279 btreeEndTransaction(p); 4280 sqlite3BtreeLeave(p); 4281 return rc; 4282 } 4283 4284 /* 4285 ** Start a statement subtransaction. The subtransaction can be rolled 4286 ** back independently of the main transaction. You must start a transaction 4287 ** before starting a subtransaction. The subtransaction is ended automatically 4288 ** if the main transaction commits or rolls back. 4289 ** 4290 ** Statement subtransactions are used around individual SQL statements 4291 ** that are contained within a BEGIN...COMMIT block. If a constraint 4292 ** error occurs within the statement, the effect of that one statement 4293 ** can be rolled back without having to rollback the entire transaction. 4294 ** 4295 ** A statement sub-transaction is implemented as an anonymous savepoint. The 4296 ** value passed as the second parameter is the total number of savepoints, 4297 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there 4298 ** are no active savepoints and no other statement-transactions open, 4299 ** iStatement is 1. This anonymous savepoint can be released or rolled back 4300 ** using the sqlite3BtreeSavepoint() function. 4301 */ 4302 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ 4303 int rc; 4304 BtShared *pBt = p->pBt; 4305 sqlite3BtreeEnter(p); 4306 assert( p->inTrans==TRANS_WRITE ); 4307 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 4308 assert( iStatement>0 ); 4309 assert( iStatement>p->db->nSavepoint ); 4310 assert( pBt->inTransaction==TRANS_WRITE ); 4311 /* At the pager level, a statement transaction is a savepoint with 4312 ** an index greater than all savepoints created explicitly using 4313 ** SQL statements. It is illegal to open, release or rollback any 4314 ** such savepoints while the statement transaction savepoint is active. 4315 */ 4316 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); 4317 sqlite3BtreeLeave(p); 4318 return rc; 4319 } 4320 4321 /* 4322 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK 4323 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the 4324 ** savepoint identified by parameter iSavepoint, depending on the value 4325 ** of op. 4326 ** 4327 ** Normally, iSavepoint is greater than or equal to zero. However, if op is 4328 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 4329 ** contents of the entire transaction are rolled back. This is different 4330 ** from a normal transaction rollback, as no locks are released and the 4331 ** transaction remains open. 4332 */ 4333 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ 4334 int rc = SQLITE_OK; 4335 if( p && p->inTrans==TRANS_WRITE ){ 4336 BtShared *pBt = p->pBt; 4337 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); 4338 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); 4339 sqlite3BtreeEnter(p); 4340 if( op==SAVEPOINT_ROLLBACK ){ 4341 rc = saveAllCursors(pBt, 0, 0); 4342 } 4343 if( rc==SQLITE_OK ){ 4344 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); 4345 } 4346 if( rc==SQLITE_OK ){ 4347 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ 4348 pBt->nPage = 0; 4349 } 4350 rc = newDatabase(pBt); 4351 btreeSetNPage(pBt, pBt->pPage1); 4352 4353 /* pBt->nPage might be zero if the database was corrupt when 4354 ** the transaction was started. Otherwise, it must be at least 1. */ 4355 assert( CORRUPT_DB || pBt->nPage>0 ); 4356 } 4357 sqlite3BtreeLeave(p); 4358 } 4359 return rc; 4360 } 4361 4362 /* 4363 ** Create a new cursor for the BTree whose root is on the page 4364 ** iTable. If a read-only cursor is requested, it is assumed that 4365 ** the caller already has at least a read-only transaction open 4366 ** on the database already. If a write-cursor is requested, then 4367 ** the caller is assumed to have an open write transaction. 4368 ** 4369 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only 4370 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor 4371 ** can be used for reading or for writing if other conditions for writing 4372 ** are also met. These are the conditions that must be met in order 4373 ** for writing to be allowed: 4374 ** 4375 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR 4376 ** 4377 ** 2: Other database connections that share the same pager cache 4378 ** but which are not in the READ_UNCOMMITTED state may not have 4379 ** cursors open with wrFlag==0 on the same table. Otherwise 4380 ** the changes made by this write cursor would be visible to 4381 ** the read cursors in the other database connection. 4382 ** 4383 ** 3: The database must be writable (not on read-only media) 4384 ** 4385 ** 4: There must be an active transaction. 4386 ** 4387 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR 4388 ** is set. If FORDELETE is set, that is a hint to the implementation that 4389 ** this cursor will only be used to seek to and delete entries of an index 4390 ** as part of a larger DELETE statement. The FORDELETE hint is not used by 4391 ** this implementation. But in a hypothetical alternative storage engine 4392 ** in which index entries are automatically deleted when corresponding table 4393 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE 4394 ** operations on this cursor can be no-ops and all READ operations can 4395 ** return a null row (2-bytes: 0x01 0x00). 4396 ** 4397 ** No checking is done to make sure that page iTable really is the 4398 ** root page of a b-tree. If it is not, then the cursor acquired 4399 ** will not work correctly. 4400 ** 4401 ** It is assumed that the sqlite3BtreeCursorZero() has been called 4402 ** on pCur to initialize the memory space prior to invoking this routine. 4403 */ 4404 static int btreeCursor( 4405 Btree *p, /* The btree */ 4406 Pgno iTable, /* Root page of table to open */ 4407 int wrFlag, /* 1 to write. 0 read-only */ 4408 struct KeyInfo *pKeyInfo, /* First arg to comparison function */ 4409 BtCursor *pCur /* Space for new cursor */ 4410 ){ 4411 BtShared *pBt = p->pBt; /* Shared b-tree handle */ 4412 BtCursor *pX; /* Looping over other all cursors */ 4413 4414 assert( sqlite3BtreeHoldsMutex(p) ); 4415 assert( wrFlag==0 4416 || wrFlag==BTREE_WRCSR 4417 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 4418 ); 4419 4420 /* The following assert statements verify that if this is a sharable 4421 ** b-tree database, the connection is holding the required table locks, 4422 ** and that no other connection has any open cursor that conflicts with 4423 ** this lock. The iTable<1 term disables the check for corrupt schemas. */ 4424 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) 4425 || iTable<1 ); 4426 assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); 4427 4428 /* Assert that the caller has opened the required transaction. */ 4429 assert( p->inTrans>TRANS_NONE ); 4430 assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); 4431 assert( pBt->pPage1 && pBt->pPage1->aData ); 4432 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); 4433 4434 if( wrFlag ){ 4435 allocateTempSpace(pBt); 4436 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; 4437 } 4438 if( iTable<=1 ){ 4439 if( iTable<1 ){ 4440 return SQLITE_CORRUPT_BKPT; 4441 }else if( btreePagecount(pBt)==0 ){ 4442 assert( wrFlag==0 ); 4443 iTable = 0; 4444 } 4445 } 4446 4447 /* Now that no other errors can occur, finish filling in the BtCursor 4448 ** variables and link the cursor into the BtShared list. */ 4449 pCur->pgnoRoot = iTable; 4450 pCur->iPage = -1; 4451 pCur->pKeyInfo = pKeyInfo; 4452 pCur->pBtree = p; 4453 pCur->pBt = pBt; 4454 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0; 4455 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; 4456 /* If there are two or more cursors on the same btree, then all such 4457 ** cursors *must* have the BTCF_Multiple flag set. */ 4458 for(pX=pBt->pCursor; pX; pX=pX->pNext){ 4459 if( pX->pgnoRoot==iTable ){ 4460 pX->curFlags |= BTCF_Multiple; 4461 pCur->curFlags |= BTCF_Multiple; 4462 } 4463 } 4464 pCur->pNext = pBt->pCursor; 4465 pBt->pCursor = pCur; 4466 pCur->eState = CURSOR_INVALID; 4467 return SQLITE_OK; 4468 } 4469 static int btreeCursorWithLock( 4470 Btree *p, /* The btree */ 4471 Pgno iTable, /* Root page of table to open */ 4472 int wrFlag, /* 1 to write. 0 read-only */ 4473 struct KeyInfo *pKeyInfo, /* First arg to comparison function */ 4474 BtCursor *pCur /* Space for new cursor */ 4475 ){ 4476 int rc; 4477 sqlite3BtreeEnter(p); 4478 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); 4479 sqlite3BtreeLeave(p); 4480 return rc; 4481 } 4482 int sqlite3BtreeCursor( 4483 Btree *p, /* The btree */ 4484 Pgno iTable, /* Root page of table to open */ 4485 int wrFlag, /* 1 to write. 0 read-only */ 4486 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ 4487 BtCursor *pCur /* Write new cursor here */ 4488 ){ 4489 if( p->sharable ){ 4490 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur); 4491 }else{ 4492 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); 4493 } 4494 } 4495 4496 /* 4497 ** Return the size of a BtCursor object in bytes. 4498 ** 4499 ** This interfaces is needed so that users of cursors can preallocate 4500 ** sufficient storage to hold a cursor. The BtCursor object is opaque 4501 ** to users so they cannot do the sizeof() themselves - they must call 4502 ** this routine. 4503 */ 4504 int sqlite3BtreeCursorSize(void){ 4505 return ROUND8(sizeof(BtCursor)); 4506 } 4507 4508 /* 4509 ** Initialize memory that will be converted into a BtCursor object. 4510 ** 4511 ** The simple approach here would be to memset() the entire object 4512 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays 4513 ** do not need to be zeroed and they are large, so we can save a lot 4514 ** of run-time by skipping the initialization of those elements. 4515 */ 4516 void sqlite3BtreeCursorZero(BtCursor *p){ 4517 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT)); 4518 } 4519 4520 /* 4521 ** Close a cursor. The read lock on the database file is released 4522 ** when the last cursor is closed. 4523 */ 4524 int sqlite3BtreeCloseCursor(BtCursor *pCur){ 4525 Btree *pBtree = pCur->pBtree; 4526 if( pBtree ){ 4527 BtShared *pBt = pCur->pBt; 4528 sqlite3BtreeEnter(pBtree); 4529 assert( pBt->pCursor!=0 ); 4530 if( pBt->pCursor==pCur ){ 4531 pBt->pCursor = pCur->pNext; 4532 }else{ 4533 BtCursor *pPrev = pBt->pCursor; 4534 do{ 4535 if( pPrev->pNext==pCur ){ 4536 pPrev->pNext = pCur->pNext; 4537 break; 4538 } 4539 pPrev = pPrev->pNext; 4540 }while( ALWAYS(pPrev) ); 4541 } 4542 btreeReleaseAllCursorPages(pCur); 4543 unlockBtreeIfUnused(pBt); 4544 sqlite3_free(pCur->aOverflow); 4545 sqlite3_free(pCur->pKey); 4546 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){ 4547 /* Since the BtShared is not sharable, there is no need to 4548 ** worry about the missing sqlite3BtreeLeave() call here. */ 4549 assert( pBtree->sharable==0 ); 4550 sqlite3BtreeClose(pBtree); 4551 }else{ 4552 sqlite3BtreeLeave(pBtree); 4553 } 4554 pCur->pBtree = 0; 4555 } 4556 return SQLITE_OK; 4557 } 4558 4559 /* 4560 ** Make sure the BtCursor* given in the argument has a valid 4561 ** BtCursor.info structure. If it is not already valid, call 4562 ** btreeParseCell() to fill it in. 4563 ** 4564 ** BtCursor.info is a cache of the information in the current cell. 4565 ** Using this cache reduces the number of calls to btreeParseCell(). 4566 */ 4567 #ifndef NDEBUG 4568 static int cellInfoEqual(CellInfo *a, CellInfo *b){ 4569 if( a->nKey!=b->nKey ) return 0; 4570 if( a->pPayload!=b->pPayload ) return 0; 4571 if( a->nPayload!=b->nPayload ) return 0; 4572 if( a->nLocal!=b->nLocal ) return 0; 4573 if( a->nSize!=b->nSize ) return 0; 4574 return 1; 4575 } 4576 static void assertCellInfo(BtCursor *pCur){ 4577 CellInfo info; 4578 memset(&info, 0, sizeof(info)); 4579 btreeParseCell(pCur->pPage, pCur->ix, &info); 4580 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) ); 4581 } 4582 #else 4583 #define assertCellInfo(x) 4584 #endif 4585 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ 4586 if( pCur->info.nSize==0 ){ 4587 pCur->curFlags |= BTCF_ValidNKey; 4588 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info); 4589 }else{ 4590 assertCellInfo(pCur); 4591 } 4592 } 4593 4594 #ifndef NDEBUG /* The next routine used only within assert() statements */ 4595 /* 4596 ** Return true if the given BtCursor is valid. A valid cursor is one 4597 ** that is currently pointing to a row in a (non-empty) table. 4598 ** This is a verification routine is used only within assert() statements. 4599 */ 4600 int sqlite3BtreeCursorIsValid(BtCursor *pCur){ 4601 return pCur && pCur->eState==CURSOR_VALID; 4602 } 4603 #endif /* NDEBUG */ 4604 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){ 4605 assert( pCur!=0 ); 4606 return pCur->eState==CURSOR_VALID; 4607 } 4608 4609 /* 4610 ** Return the value of the integer key or "rowid" for a table btree. 4611 ** This routine is only valid for a cursor that is pointing into a 4612 ** ordinary table btree. If the cursor points to an index btree or 4613 ** is invalid, the result of this routine is undefined. 4614 */ 4615 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ 4616 assert( cursorHoldsMutex(pCur) ); 4617 assert( pCur->eState==CURSOR_VALID ); 4618 assert( pCur->curIntKey ); 4619 getCellInfo(pCur); 4620 return pCur->info.nKey; 4621 } 4622 4623 /* 4624 ** Pin or unpin a cursor. 4625 */ 4626 void sqlite3BtreeCursorPin(BtCursor *pCur){ 4627 assert( (pCur->curFlags & BTCF_Pinned)==0 ); 4628 pCur->curFlags |= BTCF_Pinned; 4629 } 4630 void sqlite3BtreeCursorUnpin(BtCursor *pCur){ 4631 assert( (pCur->curFlags & BTCF_Pinned)!=0 ); 4632 pCur->curFlags &= ~BTCF_Pinned; 4633 } 4634 4635 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 4636 /* 4637 ** Return the offset into the database file for the start of the 4638 ** payload to which the cursor is pointing. 4639 */ 4640 i64 sqlite3BtreeOffset(BtCursor *pCur){ 4641 assert( cursorHoldsMutex(pCur) ); 4642 assert( pCur->eState==CURSOR_VALID ); 4643 getCellInfo(pCur); 4644 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) + 4645 (i64)(pCur->info.pPayload - pCur->pPage->aData); 4646 } 4647 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ 4648 4649 /* 4650 ** Return the number of bytes of payload for the entry that pCur is 4651 ** currently pointing to. For table btrees, this will be the amount 4652 ** of data. For index btrees, this will be the size of the key. 4653 ** 4654 ** The caller must guarantee that the cursor is pointing to a non-NULL 4655 ** valid entry. In other words, the calling procedure must guarantee 4656 ** that the cursor has Cursor.eState==CURSOR_VALID. 4657 */ 4658 u32 sqlite3BtreePayloadSize(BtCursor *pCur){ 4659 assert( cursorHoldsMutex(pCur) ); 4660 assert( pCur->eState==CURSOR_VALID ); 4661 getCellInfo(pCur); 4662 return pCur->info.nPayload; 4663 } 4664 4665 /* 4666 ** Return an upper bound on the size of any record for the table 4667 ** that the cursor is pointing into. 4668 ** 4669 ** This is an optimization. Everything will still work if this 4670 ** routine always returns 2147483647 (which is the largest record 4671 ** that SQLite can handle) or more. But returning a smaller value might 4672 ** prevent large memory allocations when trying to interpret a 4673 ** corrupt datrabase. 4674 ** 4675 ** The current implementation merely returns the size of the underlying 4676 ** database file. 4677 */ 4678 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){ 4679 assert( cursorHoldsMutex(pCur) ); 4680 assert( pCur->eState==CURSOR_VALID ); 4681 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage; 4682 } 4683 4684 /* 4685 ** Given the page number of an overflow page in the database (parameter 4686 ** ovfl), this function finds the page number of the next page in the 4687 ** linked list of overflow pages. If possible, it uses the auto-vacuum 4688 ** pointer-map data instead of reading the content of page ovfl to do so. 4689 ** 4690 ** If an error occurs an SQLite error code is returned. Otherwise: 4691 ** 4692 ** The page number of the next overflow page in the linked list is 4693 ** written to *pPgnoNext. If page ovfl is the last page in its linked 4694 ** list, *pPgnoNext is set to zero. 4695 ** 4696 ** If ppPage is not NULL, and a reference to the MemPage object corresponding 4697 ** to page number pOvfl was obtained, then *ppPage is set to point to that 4698 ** reference. It is the responsibility of the caller to call releasePage() 4699 ** on *ppPage to free the reference. In no reference was obtained (because 4700 ** the pointer-map was used to obtain the value for *pPgnoNext), then 4701 ** *ppPage is set to zero. 4702 */ 4703 static int getOverflowPage( 4704 BtShared *pBt, /* The database file */ 4705 Pgno ovfl, /* Current overflow page number */ 4706 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ 4707 Pgno *pPgnoNext /* OUT: Next overflow page number */ 4708 ){ 4709 Pgno next = 0; 4710 MemPage *pPage = 0; 4711 int rc = SQLITE_OK; 4712 4713 assert( sqlite3_mutex_held(pBt->mutex) ); 4714 assert(pPgnoNext); 4715 4716 #ifndef SQLITE_OMIT_AUTOVACUUM 4717 /* Try to find the next page in the overflow list using the 4718 ** autovacuum pointer-map pages. Guess that the next page in 4719 ** the overflow list is page number (ovfl+1). If that guess turns 4720 ** out to be wrong, fall back to loading the data of page 4721 ** number ovfl to determine the next page number. 4722 */ 4723 if( pBt->autoVacuum ){ 4724 Pgno pgno; 4725 Pgno iGuess = ovfl+1; 4726 u8 eType; 4727 4728 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ 4729 iGuess++; 4730 } 4731 4732 if( iGuess<=btreePagecount(pBt) ){ 4733 rc = ptrmapGet(pBt, iGuess, &eType, &pgno); 4734 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ 4735 next = iGuess; 4736 rc = SQLITE_DONE; 4737 } 4738 } 4739 } 4740 #endif 4741 4742 assert( next==0 || rc==SQLITE_DONE ); 4743 if( rc==SQLITE_OK ){ 4744 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); 4745 assert( rc==SQLITE_OK || pPage==0 ); 4746 if( rc==SQLITE_OK ){ 4747 next = get4byte(pPage->aData); 4748 } 4749 } 4750 4751 *pPgnoNext = next; 4752 if( ppPage ){ 4753 *ppPage = pPage; 4754 }else{ 4755 releasePage(pPage); 4756 } 4757 return (rc==SQLITE_DONE ? SQLITE_OK : rc); 4758 } 4759 4760 /* 4761 ** Copy data from a buffer to a page, or from a page to a buffer. 4762 ** 4763 ** pPayload is a pointer to data stored on database page pDbPage. 4764 ** If argument eOp is false, then nByte bytes of data are copied 4765 ** from pPayload to the buffer pointed at by pBuf. If eOp is true, 4766 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes 4767 ** of data are copied from the buffer pBuf to pPayload. 4768 ** 4769 ** SQLITE_OK is returned on success, otherwise an error code. 4770 */ 4771 static int copyPayload( 4772 void *pPayload, /* Pointer to page data */ 4773 void *pBuf, /* Pointer to buffer */ 4774 int nByte, /* Number of bytes to copy */ 4775 int eOp, /* 0 -> copy from page, 1 -> copy to page */ 4776 DbPage *pDbPage /* Page containing pPayload */ 4777 ){ 4778 if( eOp ){ 4779 /* Copy data from buffer to page (a write operation) */ 4780 int rc = sqlite3PagerWrite(pDbPage); 4781 if( rc!=SQLITE_OK ){ 4782 return rc; 4783 } 4784 memcpy(pPayload, pBuf, nByte); 4785 }else{ 4786 /* Copy data from page to buffer (a read operation) */ 4787 memcpy(pBuf, pPayload, nByte); 4788 } 4789 return SQLITE_OK; 4790 } 4791 4792 /* 4793 ** This function is used to read or overwrite payload information 4794 ** for the entry that the pCur cursor is pointing to. The eOp 4795 ** argument is interpreted as follows: 4796 ** 4797 ** 0: The operation is a read. Populate the overflow cache. 4798 ** 1: The operation is a write. Populate the overflow cache. 4799 ** 4800 ** A total of "amt" bytes are read or written beginning at "offset". 4801 ** Data is read to or from the buffer pBuf. 4802 ** 4803 ** The content being read or written might appear on the main page 4804 ** or be scattered out on multiple overflow pages. 4805 ** 4806 ** If the current cursor entry uses one or more overflow pages 4807 ** this function may allocate space for and lazily populate 4808 ** the overflow page-list cache array (BtCursor.aOverflow). 4809 ** Subsequent calls use this cache to make seeking to the supplied offset 4810 ** more efficient. 4811 ** 4812 ** Once an overflow page-list cache has been allocated, it must be 4813 ** invalidated if some other cursor writes to the same table, or if 4814 ** the cursor is moved to a different row. Additionally, in auto-vacuum 4815 ** mode, the following events may invalidate an overflow page-list cache. 4816 ** 4817 ** * An incremental vacuum, 4818 ** * A commit in auto_vacuum="full" mode, 4819 ** * Creating a table (may require moving an overflow page). 4820 */ 4821 static int accessPayload( 4822 BtCursor *pCur, /* Cursor pointing to entry to read from */ 4823 u32 offset, /* Begin reading this far into payload */ 4824 u32 amt, /* Read this many bytes */ 4825 unsigned char *pBuf, /* Write the bytes into this buffer */ 4826 int eOp /* zero to read. non-zero to write. */ 4827 ){ 4828 unsigned char *aPayload; 4829 int rc = SQLITE_OK; 4830 int iIdx = 0; 4831 MemPage *pPage = pCur->pPage; /* Btree page of current entry */ 4832 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ 4833 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4834 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ 4835 #endif 4836 4837 assert( pPage ); 4838 assert( eOp==0 || eOp==1 ); 4839 assert( pCur->eState==CURSOR_VALID ); 4840 assert( pCur->ix<pPage->nCell ); 4841 assert( cursorHoldsMutex(pCur) ); 4842 4843 getCellInfo(pCur); 4844 aPayload = pCur->info.pPayload; 4845 assert( offset+amt <= pCur->info.nPayload ); 4846 4847 assert( aPayload > pPage->aData ); 4848 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ 4849 /* Trying to read or write past the end of the data is an error. The 4850 ** conditional above is really: 4851 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] 4852 ** but is recast into its current form to avoid integer overflow problems 4853 */ 4854 return SQLITE_CORRUPT_PAGE(pPage); 4855 } 4856 4857 /* Check if data must be read/written to/from the btree page itself. */ 4858 if( offset<pCur->info.nLocal ){ 4859 int a = amt; 4860 if( a+offset>pCur->info.nLocal ){ 4861 a = pCur->info.nLocal - offset; 4862 } 4863 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); 4864 offset = 0; 4865 pBuf += a; 4866 amt -= a; 4867 }else{ 4868 offset -= pCur->info.nLocal; 4869 } 4870 4871 4872 if( rc==SQLITE_OK && amt>0 ){ 4873 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ 4874 Pgno nextPage; 4875 4876 nextPage = get4byte(&aPayload[pCur->info.nLocal]); 4877 4878 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. 4879 ** 4880 ** The aOverflow[] array is sized at one entry for each overflow page 4881 ** in the overflow chain. The page number of the first overflow page is 4882 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array 4883 ** means "not yet known" (the cache is lazily populated). 4884 */ 4885 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ 4886 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; 4887 if( pCur->aOverflow==0 4888 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) 4889 ){ 4890 Pgno *aNew = (Pgno*)sqlite3Realloc( 4891 pCur->aOverflow, nOvfl*2*sizeof(Pgno) 4892 ); 4893 if( aNew==0 ){ 4894 return SQLITE_NOMEM_BKPT; 4895 }else{ 4896 pCur->aOverflow = aNew; 4897 } 4898 } 4899 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); 4900 pCur->curFlags |= BTCF_ValidOvfl; 4901 }else{ 4902 /* If the overflow page-list cache has been allocated and the 4903 ** entry for the first required overflow page is valid, skip 4904 ** directly to it. 4905 */ 4906 if( pCur->aOverflow[offset/ovflSize] ){ 4907 iIdx = (offset/ovflSize); 4908 nextPage = pCur->aOverflow[iIdx]; 4909 offset = (offset%ovflSize); 4910 } 4911 } 4912 4913 assert( rc==SQLITE_OK && amt>0 ); 4914 while( nextPage ){ 4915 /* If required, populate the overflow page-list cache. */ 4916 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT; 4917 assert( pCur->aOverflow[iIdx]==0 4918 || pCur->aOverflow[iIdx]==nextPage 4919 || CORRUPT_DB ); 4920 pCur->aOverflow[iIdx] = nextPage; 4921 4922 if( offset>=ovflSize ){ 4923 /* The only reason to read this page is to obtain the page 4924 ** number for the next page in the overflow chain. The page 4925 ** data is not required. So first try to lookup the overflow 4926 ** page-list cache, if any, then fall back to the getOverflowPage() 4927 ** function. 4928 */ 4929 assert( pCur->curFlags & BTCF_ValidOvfl ); 4930 assert( pCur->pBtree->db==pBt->db ); 4931 if( pCur->aOverflow[iIdx+1] ){ 4932 nextPage = pCur->aOverflow[iIdx+1]; 4933 }else{ 4934 rc = getOverflowPage(pBt, nextPage, 0, &nextPage); 4935 } 4936 offset -= ovflSize; 4937 }else{ 4938 /* Need to read this page properly. It contains some of the 4939 ** range of data that is being read (eOp==0) or written (eOp!=0). 4940 */ 4941 int a = amt; 4942 if( a + offset > ovflSize ){ 4943 a = ovflSize - offset; 4944 } 4945 4946 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4947 /* If all the following are true: 4948 ** 4949 ** 1) this is a read operation, and 4950 ** 2) data is required from the start of this overflow page, and 4951 ** 3) there are no dirty pages in the page-cache 4952 ** 4) the database is file-backed, and 4953 ** 5) the page is not in the WAL file 4954 ** 6) at least 4 bytes have already been read into the output buffer 4955 ** 4956 ** then data can be read directly from the database file into the 4957 ** output buffer, bypassing the page-cache altogether. This speeds 4958 ** up loading large records that span many overflow pages. 4959 */ 4960 if( eOp==0 /* (1) */ 4961 && offset==0 /* (2) */ 4962 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ 4963 && &pBuf[-4]>=pBufStart /* (6) */ 4964 ){ 4965 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); 4966 u8 aSave[4]; 4967 u8 *aWrite = &pBuf[-4]; 4968 assert( aWrite>=pBufStart ); /* due to (6) */ 4969 memcpy(aSave, aWrite, 4); 4970 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); 4971 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT; 4972 nextPage = get4byte(aWrite); 4973 memcpy(aWrite, aSave, 4); 4974 }else 4975 #endif 4976 4977 { 4978 DbPage *pDbPage; 4979 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, 4980 (eOp==0 ? PAGER_GET_READONLY : 0) 4981 ); 4982 if( rc==SQLITE_OK ){ 4983 aPayload = sqlite3PagerGetData(pDbPage); 4984 nextPage = get4byte(aPayload); 4985 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); 4986 sqlite3PagerUnref(pDbPage); 4987 offset = 0; 4988 } 4989 } 4990 amt -= a; 4991 if( amt==0 ) return rc; 4992 pBuf += a; 4993 } 4994 if( rc ) break; 4995 iIdx++; 4996 } 4997 } 4998 4999 if( rc==SQLITE_OK && amt>0 ){ 5000 /* Overflow chain ends prematurely */ 5001 return SQLITE_CORRUPT_PAGE(pPage); 5002 } 5003 return rc; 5004 } 5005 5006 /* 5007 ** Read part of the payload for the row at which that cursor pCur is currently 5008 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer 5009 ** begins at "offset". 5010 ** 5011 ** pCur can be pointing to either a table or an index b-tree. 5012 ** If pointing to a table btree, then the content section is read. If 5013 ** pCur is pointing to an index b-tree then the key section is read. 5014 ** 5015 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing 5016 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the 5017 ** cursor might be invalid or might need to be restored before being read. 5018 ** 5019 ** Return SQLITE_OK on success or an error code if anything goes 5020 ** wrong. An error is returned if "offset+amt" is larger than 5021 ** the available payload. 5022 */ 5023 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 5024 assert( cursorHoldsMutex(pCur) ); 5025 assert( pCur->eState==CURSOR_VALID ); 5026 assert( pCur->iPage>=0 && pCur->pPage ); 5027 assert( pCur->ix<pCur->pPage->nCell ); 5028 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); 5029 } 5030 5031 /* 5032 ** This variant of sqlite3BtreePayload() works even if the cursor has not 5033 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read() 5034 ** interface. 5035 */ 5036 #ifndef SQLITE_OMIT_INCRBLOB 5037 static SQLITE_NOINLINE int accessPayloadChecked( 5038 BtCursor *pCur, 5039 u32 offset, 5040 u32 amt, 5041 void *pBuf 5042 ){ 5043 int rc; 5044 if ( pCur->eState==CURSOR_INVALID ){ 5045 return SQLITE_ABORT; 5046 } 5047 assert( cursorOwnsBtShared(pCur) ); 5048 rc = btreeRestoreCursorPosition(pCur); 5049 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); 5050 } 5051 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 5052 if( pCur->eState==CURSOR_VALID ){ 5053 assert( cursorOwnsBtShared(pCur) ); 5054 return accessPayload(pCur, offset, amt, pBuf, 0); 5055 }else{ 5056 return accessPayloadChecked(pCur, offset, amt, pBuf); 5057 } 5058 } 5059 #endif /* SQLITE_OMIT_INCRBLOB */ 5060 5061 /* 5062 ** Return a pointer to payload information from the entry that the 5063 ** pCur cursor is pointing to. The pointer is to the beginning of 5064 ** the key if index btrees (pPage->intKey==0) and is the data for 5065 ** table btrees (pPage->intKey==1). The number of bytes of available 5066 ** key/data is written into *pAmt. If *pAmt==0, then the value 5067 ** returned will not be a valid pointer. 5068 ** 5069 ** This routine is an optimization. It is common for the entire key 5070 ** and data to fit on the local page and for there to be no overflow 5071 ** pages. When that is so, this routine can be used to access the 5072 ** key and data without making a copy. If the key and/or data spills 5073 ** onto overflow pages, then accessPayload() must be used to reassemble 5074 ** the key/data and copy it into a preallocated buffer. 5075 ** 5076 ** The pointer returned by this routine looks directly into the cached 5077 ** page of the database. The data might change or move the next time 5078 ** any btree routine is called. 5079 */ 5080 static const void *fetchPayload( 5081 BtCursor *pCur, /* Cursor pointing to entry to read from */ 5082 u32 *pAmt /* Write the number of available bytes here */ 5083 ){ 5084 int amt; 5085 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage); 5086 assert( pCur->eState==CURSOR_VALID ); 5087 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5088 assert( cursorOwnsBtShared(pCur) ); 5089 assert( pCur->ix<pCur->pPage->nCell ); 5090 assert( pCur->info.nSize>0 ); 5091 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB ); 5092 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB); 5093 amt = pCur->info.nLocal; 5094 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){ 5095 /* There is too little space on the page for the expected amount 5096 ** of local content. Database must be corrupt. */ 5097 assert( CORRUPT_DB ); 5098 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload)); 5099 } 5100 *pAmt = (u32)amt; 5101 return (void*)pCur->info.pPayload; 5102 } 5103 5104 5105 /* 5106 ** For the entry that cursor pCur is point to, return as 5107 ** many bytes of the key or data as are available on the local 5108 ** b-tree page. Write the number of available bytes into *pAmt. 5109 ** 5110 ** The pointer returned is ephemeral. The key/data may move 5111 ** or be destroyed on the next call to any Btree routine, 5112 ** including calls from other threads against the same cache. 5113 ** Hence, a mutex on the BtShared should be held prior to calling 5114 ** this routine. 5115 ** 5116 ** These routines is used to get quick access to key and data 5117 ** in the common case where no overflow pages are used. 5118 */ 5119 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ 5120 return fetchPayload(pCur, pAmt); 5121 } 5122 5123 5124 /* 5125 ** Move the cursor down to a new child page. The newPgno argument is the 5126 ** page number of the child page to move to. 5127 ** 5128 ** This function returns SQLITE_CORRUPT if the page-header flags field of 5129 ** the new child page does not match the flags field of the parent (i.e. 5130 ** if an intkey page appears to be the parent of a non-intkey page, or 5131 ** vice-versa). 5132 */ 5133 static int moveToChild(BtCursor *pCur, u32 newPgno){ 5134 BtShared *pBt = pCur->pBt; 5135 5136 assert( cursorOwnsBtShared(pCur) ); 5137 assert( pCur->eState==CURSOR_VALID ); 5138 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); 5139 assert( pCur->iPage>=0 ); 5140 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ 5141 return SQLITE_CORRUPT_BKPT; 5142 } 5143 pCur->info.nSize = 0; 5144 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5145 pCur->aiIdx[pCur->iPage] = pCur->ix; 5146 pCur->apPage[pCur->iPage] = pCur->pPage; 5147 pCur->ix = 0; 5148 pCur->iPage++; 5149 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags); 5150 } 5151 5152 #ifdef SQLITE_DEBUG 5153 /* 5154 ** Page pParent is an internal (non-leaf) tree page. This function 5155 ** asserts that page number iChild is the left-child if the iIdx'th 5156 ** cell in page pParent. Or, if iIdx is equal to the total number of 5157 ** cells in pParent, that page number iChild is the right-child of 5158 ** the page. 5159 */ 5160 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ 5161 if( CORRUPT_DB ) return; /* The conditions tested below might not be true 5162 ** in a corrupt database */ 5163 assert( iIdx<=pParent->nCell ); 5164 if( iIdx==pParent->nCell ){ 5165 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); 5166 }else{ 5167 assert( get4byte(findCell(pParent, iIdx))==iChild ); 5168 } 5169 } 5170 #else 5171 # define assertParentIndex(x,y,z) 5172 #endif 5173 5174 /* 5175 ** Move the cursor up to the parent page. 5176 ** 5177 ** pCur->idx is set to the cell index that contains the pointer 5178 ** to the page we are coming from. If we are coming from the 5179 ** right-most child page then pCur->idx is set to one more than 5180 ** the largest cell index. 5181 */ 5182 static void moveToParent(BtCursor *pCur){ 5183 MemPage *pLeaf; 5184 assert( cursorOwnsBtShared(pCur) ); 5185 assert( pCur->eState==CURSOR_VALID ); 5186 assert( pCur->iPage>0 ); 5187 assert( pCur->pPage ); 5188 assertParentIndex( 5189 pCur->apPage[pCur->iPage-1], 5190 pCur->aiIdx[pCur->iPage-1], 5191 pCur->pPage->pgno 5192 ); 5193 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); 5194 pCur->info.nSize = 0; 5195 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5196 pCur->ix = pCur->aiIdx[pCur->iPage-1]; 5197 pLeaf = pCur->pPage; 5198 pCur->pPage = pCur->apPage[--pCur->iPage]; 5199 releasePageNotNull(pLeaf); 5200 } 5201 5202 /* 5203 ** Move the cursor to point to the root page of its b-tree structure. 5204 ** 5205 ** If the table has a virtual root page, then the cursor is moved to point 5206 ** to the virtual root page instead of the actual root page. A table has a 5207 ** virtual root page when the actual root page contains no cells and a 5208 ** single child page. This can only happen with the table rooted at page 1. 5209 ** 5210 ** If the b-tree structure is empty, the cursor state is set to 5211 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise, 5212 ** the cursor is set to point to the first cell located on the root 5213 ** (or virtual root) page and the cursor state is set to CURSOR_VALID. 5214 ** 5215 ** If this function returns successfully, it may be assumed that the 5216 ** page-header flags indicate that the [virtual] root-page is the expected 5217 ** kind of b-tree page (i.e. if when opening the cursor the caller did not 5218 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, 5219 ** indicating a table b-tree, or if the caller did specify a KeyInfo 5220 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index 5221 ** b-tree). 5222 */ 5223 static int moveToRoot(BtCursor *pCur){ 5224 MemPage *pRoot; 5225 int rc = SQLITE_OK; 5226 5227 assert( cursorOwnsBtShared(pCur) ); 5228 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); 5229 assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); 5230 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); 5231 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 ); 5232 assert( pCur->pgnoRoot>0 || pCur->iPage<0 ); 5233 5234 if( pCur->iPage>=0 ){ 5235 if( pCur->iPage ){ 5236 releasePageNotNull(pCur->pPage); 5237 while( --pCur->iPage ){ 5238 releasePageNotNull(pCur->apPage[pCur->iPage]); 5239 } 5240 pCur->pPage = pCur->apPage[0]; 5241 goto skip_init; 5242 } 5243 }else if( pCur->pgnoRoot==0 ){ 5244 pCur->eState = CURSOR_INVALID; 5245 return SQLITE_EMPTY; 5246 }else{ 5247 assert( pCur->iPage==(-1) ); 5248 if( pCur->eState>=CURSOR_REQUIRESEEK ){ 5249 if( pCur->eState==CURSOR_FAULT ){ 5250 assert( pCur->skipNext!=SQLITE_OK ); 5251 return pCur->skipNext; 5252 } 5253 sqlite3BtreeClearCursor(pCur); 5254 } 5255 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage, 5256 0, pCur->curPagerFlags); 5257 if( rc!=SQLITE_OK ){ 5258 pCur->eState = CURSOR_INVALID; 5259 return rc; 5260 } 5261 pCur->iPage = 0; 5262 pCur->curIntKey = pCur->pPage->intKey; 5263 } 5264 pRoot = pCur->pPage; 5265 assert( pRoot->pgno==pCur->pgnoRoot ); 5266 5267 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor 5268 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is 5269 ** NULL, the caller expects a table b-tree. If this is not the case, 5270 ** return an SQLITE_CORRUPT error. 5271 ** 5272 ** Earlier versions of SQLite assumed that this test could not fail 5273 ** if the root page was already loaded when this function was called (i.e. 5274 ** if pCur->iPage>=0). But this is not so if the database is corrupted 5275 ** in such a way that page pRoot is linked into a second b-tree table 5276 ** (or the freelist). */ 5277 assert( pRoot->intKey==1 || pRoot->intKey==0 ); 5278 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ 5279 return SQLITE_CORRUPT_PAGE(pCur->pPage); 5280 } 5281 5282 skip_init: 5283 pCur->ix = 0; 5284 pCur->info.nSize = 0; 5285 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); 5286 5287 pRoot = pCur->pPage; 5288 if( pRoot->nCell>0 ){ 5289 pCur->eState = CURSOR_VALID; 5290 }else if( !pRoot->leaf ){ 5291 Pgno subpage; 5292 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; 5293 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); 5294 pCur->eState = CURSOR_VALID; 5295 rc = moveToChild(pCur, subpage); 5296 }else{ 5297 pCur->eState = CURSOR_INVALID; 5298 rc = SQLITE_EMPTY; 5299 } 5300 return rc; 5301 } 5302 5303 /* 5304 ** Move the cursor down to the left-most leaf entry beneath the 5305 ** entry to which it is currently pointing. 5306 ** 5307 ** The left-most leaf is the one with the smallest key - the first 5308 ** in ascending order. 5309 */ 5310 static int moveToLeftmost(BtCursor *pCur){ 5311 Pgno pgno; 5312 int rc = SQLITE_OK; 5313 MemPage *pPage; 5314 5315 assert( cursorOwnsBtShared(pCur) ); 5316 assert( pCur->eState==CURSOR_VALID ); 5317 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ 5318 assert( pCur->ix<pPage->nCell ); 5319 pgno = get4byte(findCell(pPage, pCur->ix)); 5320 rc = moveToChild(pCur, pgno); 5321 } 5322 return rc; 5323 } 5324 5325 /* 5326 ** Move the cursor down to the right-most leaf entry beneath the 5327 ** page to which it is currently pointing. Notice the difference 5328 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() 5329 ** finds the left-most entry beneath the *entry* whereas moveToRightmost() 5330 ** finds the right-most entry beneath the *page*. 5331 ** 5332 ** The right-most entry is the one with the largest key - the last 5333 ** key in ascending order. 5334 */ 5335 static int moveToRightmost(BtCursor *pCur){ 5336 Pgno pgno; 5337 int rc = SQLITE_OK; 5338 MemPage *pPage = 0; 5339 5340 assert( cursorOwnsBtShared(pCur) ); 5341 assert( pCur->eState==CURSOR_VALID ); 5342 while( !(pPage = pCur->pPage)->leaf ){ 5343 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5344 pCur->ix = pPage->nCell; 5345 rc = moveToChild(pCur, pgno); 5346 if( rc ) return rc; 5347 } 5348 pCur->ix = pPage->nCell-1; 5349 assert( pCur->info.nSize==0 ); 5350 assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); 5351 return SQLITE_OK; 5352 } 5353 5354 /* Move the cursor to the first entry in the table. Return SQLITE_OK 5355 ** on success. Set *pRes to 0 if the cursor actually points to something 5356 ** or set *pRes to 1 if the table is empty. 5357 */ 5358 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ 5359 int rc; 5360 5361 assert( cursorOwnsBtShared(pCur) ); 5362 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5363 rc = moveToRoot(pCur); 5364 if( rc==SQLITE_OK ){ 5365 assert( pCur->pPage->nCell>0 ); 5366 *pRes = 0; 5367 rc = moveToLeftmost(pCur); 5368 }else if( rc==SQLITE_EMPTY ){ 5369 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5370 *pRes = 1; 5371 rc = SQLITE_OK; 5372 } 5373 return rc; 5374 } 5375 5376 /* Move the cursor to the last entry in the table. Return SQLITE_OK 5377 ** on success. Set *pRes to 0 if the cursor actually points to something 5378 ** or set *pRes to 1 if the table is empty. 5379 */ 5380 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ 5381 int rc; 5382 5383 assert( cursorOwnsBtShared(pCur) ); 5384 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5385 5386 /* If the cursor already points to the last entry, this is a no-op. */ 5387 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ 5388 #ifdef SQLITE_DEBUG 5389 /* This block serves to assert() that the cursor really does point 5390 ** to the last entry in the b-tree. */ 5391 int ii; 5392 for(ii=0; ii<pCur->iPage; ii++){ 5393 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); 5394 } 5395 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB ); 5396 testcase( pCur->ix!=pCur->pPage->nCell-1 ); 5397 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */ 5398 assert( pCur->pPage->leaf ); 5399 #endif 5400 *pRes = 0; 5401 return SQLITE_OK; 5402 } 5403 5404 rc = moveToRoot(pCur); 5405 if( rc==SQLITE_OK ){ 5406 assert( pCur->eState==CURSOR_VALID ); 5407 *pRes = 0; 5408 rc = moveToRightmost(pCur); 5409 if( rc==SQLITE_OK ){ 5410 pCur->curFlags |= BTCF_AtLast; 5411 }else{ 5412 pCur->curFlags &= ~BTCF_AtLast; 5413 } 5414 }else if( rc==SQLITE_EMPTY ){ 5415 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5416 *pRes = 1; 5417 rc = SQLITE_OK; 5418 } 5419 return rc; 5420 } 5421 5422 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY) 5423 ** table near the key intKey. Return a success code. 5424 ** 5425 ** If an exact match is not found, then the cursor is always 5426 ** left pointing at a leaf page which would hold the entry if it 5427 ** were present. The cursor might point to an entry that comes 5428 ** before or after the key. 5429 ** 5430 ** An integer is written into *pRes which is the result of 5431 ** comparing the key with the entry to which the cursor is 5432 ** pointing. The meaning of the integer written into 5433 ** *pRes is as follows: 5434 ** 5435 ** *pRes<0 The cursor is left pointing at an entry that 5436 ** is smaller than intKey or if the table is empty 5437 ** and the cursor is therefore left point to nothing. 5438 ** 5439 ** *pRes==0 The cursor is left pointing at an entry that 5440 ** exactly matches intKey. 5441 ** 5442 ** *pRes>0 The cursor is left pointing at an entry that 5443 ** is larger than intKey. 5444 */ 5445 int sqlite3BtreeTableMoveto( 5446 BtCursor *pCur, /* The cursor to be moved */ 5447 i64 intKey, /* The table key */ 5448 int biasRight, /* If true, bias the search to the high end */ 5449 int *pRes /* Write search results here */ 5450 ){ 5451 int rc; 5452 5453 assert( cursorOwnsBtShared(pCur) ); 5454 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5455 assert( pRes ); 5456 assert( pCur->pKeyInfo==0 ); 5457 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 ); 5458 5459 /* If the cursor is already positioned at the point we are trying 5460 ** to move to, then just return without doing any work */ 5461 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){ 5462 if( pCur->info.nKey==intKey ){ 5463 *pRes = 0; 5464 return SQLITE_OK; 5465 } 5466 if( pCur->info.nKey<intKey ){ 5467 if( (pCur->curFlags & BTCF_AtLast)!=0 ){ 5468 *pRes = -1; 5469 return SQLITE_OK; 5470 } 5471 /* If the requested key is one more than the previous key, then 5472 ** try to get there using sqlite3BtreeNext() rather than a full 5473 ** binary search. This is an optimization only. The correct answer 5474 ** is still obtained without this case, only a little more slowely */ 5475 if( pCur->info.nKey+1==intKey ){ 5476 *pRes = 0; 5477 rc = sqlite3BtreeNext(pCur, 0); 5478 if( rc==SQLITE_OK ){ 5479 getCellInfo(pCur); 5480 if( pCur->info.nKey==intKey ){ 5481 return SQLITE_OK; 5482 } 5483 }else if( rc==SQLITE_DONE ){ 5484 rc = SQLITE_OK; 5485 }else{ 5486 return rc; 5487 } 5488 } 5489 } 5490 } 5491 5492 #ifdef SQLITE_DEBUG 5493 pCur->pBtree->nSeek++; /* Performance measurement during testing */ 5494 #endif 5495 5496 rc = moveToRoot(pCur); 5497 if( rc ){ 5498 if( rc==SQLITE_EMPTY ){ 5499 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5500 *pRes = -1; 5501 return SQLITE_OK; 5502 } 5503 return rc; 5504 } 5505 assert( pCur->pPage ); 5506 assert( pCur->pPage->isInit ); 5507 assert( pCur->eState==CURSOR_VALID ); 5508 assert( pCur->pPage->nCell > 0 ); 5509 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey ); 5510 assert( pCur->curIntKey ); 5511 5512 for(;;){ 5513 int lwr, upr, idx, c; 5514 Pgno chldPg; 5515 MemPage *pPage = pCur->pPage; 5516 u8 *pCell; /* Pointer to current cell in pPage */ 5517 5518 /* pPage->nCell must be greater than zero. If this is the root-page 5519 ** the cursor would have been INVALID above and this for(;;) loop 5520 ** not run. If this is not the root-page, then the moveToChild() routine 5521 ** would have already detected db corruption. Similarly, pPage must 5522 ** be the right kind (index or table) of b-tree page. Otherwise 5523 ** a moveToChild() or moveToRoot() call would have detected corruption. */ 5524 assert( pPage->nCell>0 ); 5525 assert( pPage->intKey ); 5526 lwr = 0; 5527 upr = pPage->nCell-1; 5528 assert( biasRight==0 || biasRight==1 ); 5529 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ 5530 pCur->ix = (u16)idx; 5531 for(;;){ 5532 i64 nCellKey; 5533 pCell = findCellPastPtr(pPage, idx); 5534 if( pPage->intKeyLeaf ){ 5535 while( 0x80 <= *(pCell++) ){ 5536 if( pCell>=pPage->aDataEnd ){ 5537 return SQLITE_CORRUPT_PAGE(pPage); 5538 } 5539 } 5540 } 5541 getVarint(pCell, (u64*)&nCellKey); 5542 if( nCellKey<intKey ){ 5543 lwr = idx+1; 5544 if( lwr>upr ){ c = -1; break; } 5545 }else if( nCellKey>intKey ){ 5546 upr = idx-1; 5547 if( lwr>upr ){ c = +1; break; } 5548 }else{ 5549 assert( nCellKey==intKey ); 5550 pCur->ix = (u16)idx; 5551 if( !pPage->leaf ){ 5552 lwr = idx; 5553 goto moveto_table_next_layer; 5554 }else{ 5555 pCur->curFlags |= BTCF_ValidNKey; 5556 pCur->info.nKey = nCellKey; 5557 pCur->info.nSize = 0; 5558 *pRes = 0; 5559 return SQLITE_OK; 5560 } 5561 } 5562 assert( lwr+upr>=0 ); 5563 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ 5564 } 5565 assert( lwr==upr+1 || !pPage->leaf ); 5566 assert( pPage->isInit ); 5567 if( pPage->leaf ){ 5568 assert( pCur->ix<pCur->pPage->nCell ); 5569 pCur->ix = (u16)idx; 5570 *pRes = c; 5571 rc = SQLITE_OK; 5572 goto moveto_table_finish; 5573 } 5574 moveto_table_next_layer: 5575 if( lwr>=pPage->nCell ){ 5576 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5577 }else{ 5578 chldPg = get4byte(findCell(pPage, lwr)); 5579 } 5580 pCur->ix = (u16)lwr; 5581 rc = moveToChild(pCur, chldPg); 5582 if( rc ) break; 5583 } 5584 moveto_table_finish: 5585 pCur->info.nSize = 0; 5586 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5587 return rc; 5588 } 5589 5590 /* Move the cursor so that it points to an entry in an index table 5591 ** near the key pIdxKey. Return a success code. 5592 ** 5593 ** If an exact match is not found, then the cursor is always 5594 ** left pointing at a leaf page which would hold the entry if it 5595 ** were present. The cursor might point to an entry that comes 5596 ** before or after the key. 5597 ** 5598 ** An integer is written into *pRes which is the result of 5599 ** comparing the key with the entry to which the cursor is 5600 ** pointing. The meaning of the integer written into 5601 ** *pRes is as follows: 5602 ** 5603 ** *pRes<0 The cursor is left pointing at an entry that 5604 ** is smaller than pIdxKey or if the table is empty 5605 ** and the cursor is therefore left point to nothing. 5606 ** 5607 ** *pRes==0 The cursor is left pointing at an entry that 5608 ** exactly matches pIdxKey. 5609 ** 5610 ** *pRes>0 The cursor is left pointing at an entry that 5611 ** is larger than pIdxKey. 5612 ** 5613 ** The pIdxKey->eqSeen field is set to 1 if there 5614 ** exists an entry in the table that exactly matches pIdxKey. 5615 */ 5616 int sqlite3BtreeIndexMoveto( 5617 BtCursor *pCur, /* The cursor to be moved */ 5618 UnpackedRecord *pIdxKey, /* Unpacked index key */ 5619 int *pRes /* Write search results here */ 5620 ){ 5621 int rc; 5622 RecordCompare xRecordCompare; 5623 5624 assert( cursorOwnsBtShared(pCur) ); 5625 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5626 assert( pRes ); 5627 assert( pCur->pKeyInfo!=0 ); 5628 5629 #ifdef SQLITE_DEBUG 5630 pCur->pBtree->nSeek++; /* Performance measurement during testing */ 5631 #endif 5632 5633 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); 5634 pIdxKey->errCode = 0; 5635 assert( pIdxKey->default_rc==1 5636 || pIdxKey->default_rc==0 5637 || pIdxKey->default_rc==-1 5638 ); 5639 5640 rc = moveToRoot(pCur); 5641 if( rc ){ 5642 if( rc==SQLITE_EMPTY ){ 5643 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5644 *pRes = -1; 5645 return SQLITE_OK; 5646 } 5647 return rc; 5648 } 5649 assert( pCur->pPage ); 5650 assert( pCur->pPage->isInit ); 5651 assert( pCur->eState==CURSOR_VALID ); 5652 assert( pCur->pPage->nCell > 0 ); 5653 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey ); 5654 assert( pCur->curIntKey || pIdxKey ); 5655 for(;;){ 5656 int lwr, upr, idx, c; 5657 Pgno chldPg; 5658 MemPage *pPage = pCur->pPage; 5659 u8 *pCell; /* Pointer to current cell in pPage */ 5660 5661 /* pPage->nCell must be greater than zero. If this is the root-page 5662 ** the cursor would have been INVALID above and this for(;;) loop 5663 ** not run. If this is not the root-page, then the moveToChild() routine 5664 ** would have already detected db corruption. Similarly, pPage must 5665 ** be the right kind (index or table) of b-tree page. Otherwise 5666 ** a moveToChild() or moveToRoot() call would have detected corruption. */ 5667 assert( pPage->nCell>0 ); 5668 assert( pPage->intKey==(pIdxKey==0) ); 5669 lwr = 0; 5670 upr = pPage->nCell-1; 5671 idx = upr>>1; /* idx = (lwr+upr)/2; */ 5672 pCur->ix = (u16)idx; 5673 for(;;){ 5674 int nCell; /* Size of the pCell cell in bytes */ 5675 pCell = findCellPastPtr(pPage, idx); 5676 5677 /* The maximum supported page-size is 65536 bytes. This means that 5678 ** the maximum number of record bytes stored on an index B-Tree 5679 ** page is less than 16384 bytes and may be stored as a 2-byte 5680 ** varint. This information is used to attempt to avoid parsing 5681 ** the entire cell by checking for the cases where the record is 5682 ** stored entirely within the b-tree page by inspecting the first 5683 ** 2 bytes of the cell. 5684 */ 5685 nCell = pCell[0]; 5686 if( nCell<=pPage->max1bytePayload ){ 5687 /* This branch runs if the record-size field of the cell is a 5688 ** single byte varint and the record fits entirely on the main 5689 ** b-tree page. */ 5690 testcase( pCell+nCell+1==pPage->aDataEnd ); 5691 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); 5692 }else if( !(pCell[1] & 0x80) 5693 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal 5694 ){ 5695 /* The record-size field is a 2 byte varint and the record 5696 ** fits entirely on the main b-tree page. */ 5697 testcase( pCell+nCell+2==pPage->aDataEnd ); 5698 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); 5699 }else{ 5700 /* The record flows over onto one or more overflow pages. In 5701 ** this case the whole cell needs to be parsed, a buffer allocated 5702 ** and accessPayload() used to retrieve the record into the 5703 ** buffer before VdbeRecordCompare() can be called. 5704 ** 5705 ** If the record is corrupt, the xRecordCompare routine may read 5706 ** up to two varints past the end of the buffer. An extra 18 5707 ** bytes of padding is allocated at the end of the buffer in 5708 ** case this happens. */ 5709 void *pCellKey; 5710 u8 * const pCellBody = pCell - pPage->childPtrSize; 5711 const int nOverrun = 18; /* Size of the overrun padding */ 5712 pPage->xParseCell(pPage, pCellBody, &pCur->info); 5713 nCell = (int)pCur->info.nKey; 5714 testcase( nCell<0 ); /* True if key size is 2^32 or more */ 5715 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ 5716 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ 5717 testcase( nCell==2 ); /* Minimum legal index key size */ 5718 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){ 5719 rc = SQLITE_CORRUPT_PAGE(pPage); 5720 goto moveto_index_finish; 5721 } 5722 pCellKey = sqlite3Malloc( nCell+nOverrun ); 5723 if( pCellKey==0 ){ 5724 rc = SQLITE_NOMEM_BKPT; 5725 goto moveto_index_finish; 5726 } 5727 pCur->ix = (u16)idx; 5728 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); 5729 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */ 5730 pCur->curFlags &= ~BTCF_ValidOvfl; 5731 if( rc ){ 5732 sqlite3_free(pCellKey); 5733 goto moveto_index_finish; 5734 } 5735 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); 5736 sqlite3_free(pCellKey); 5737 } 5738 assert( 5739 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) 5740 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) 5741 ); 5742 if( c<0 ){ 5743 lwr = idx+1; 5744 }else if( c>0 ){ 5745 upr = idx-1; 5746 }else{ 5747 assert( c==0 ); 5748 *pRes = 0; 5749 rc = SQLITE_OK; 5750 pCur->ix = (u16)idx; 5751 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT; 5752 goto moveto_index_finish; 5753 } 5754 if( lwr>upr ) break; 5755 assert( lwr+upr>=0 ); 5756 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ 5757 } 5758 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); 5759 assert( pPage->isInit ); 5760 if( pPage->leaf ){ 5761 assert( pCur->ix<pCur->pPage->nCell ); 5762 pCur->ix = (u16)idx; 5763 *pRes = c; 5764 rc = SQLITE_OK; 5765 goto moveto_index_finish; 5766 } 5767 if( lwr>=pPage->nCell ){ 5768 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5769 }else{ 5770 chldPg = get4byte(findCell(pPage, lwr)); 5771 } 5772 pCur->ix = (u16)lwr; 5773 rc = moveToChild(pCur, chldPg); 5774 if( rc ) break; 5775 } 5776 moveto_index_finish: 5777 pCur->info.nSize = 0; 5778 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5779 return rc; 5780 } 5781 5782 5783 /* 5784 ** Return TRUE if the cursor is not pointing at an entry of the table. 5785 ** 5786 ** TRUE will be returned after a call to sqlite3BtreeNext() moves 5787 ** past the last entry in the table or sqlite3BtreePrev() moves past 5788 ** the first entry. TRUE is also returned if the table is empty. 5789 */ 5790 int sqlite3BtreeEof(BtCursor *pCur){ 5791 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries 5792 ** have been deleted? This API will need to change to return an error code 5793 ** as well as the boolean result value. 5794 */ 5795 return (CURSOR_VALID!=pCur->eState); 5796 } 5797 5798 /* 5799 ** Return an estimate for the number of rows in the table that pCur is 5800 ** pointing to. Return a negative number if no estimate is currently 5801 ** available. 5802 */ 5803 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){ 5804 i64 n; 5805 u8 i; 5806 5807 assert( cursorOwnsBtShared(pCur) ); 5808 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5809 5810 /* Currently this interface is only called by the OP_IfSmaller 5811 ** opcode, and it that case the cursor will always be valid and 5812 ** will always point to a leaf node. */ 5813 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1; 5814 if( NEVER(pCur->pPage->leaf==0) ) return -1; 5815 5816 n = pCur->pPage->nCell; 5817 for(i=0; i<pCur->iPage; i++){ 5818 n *= pCur->apPage[i]->nCell; 5819 } 5820 return n; 5821 } 5822 5823 /* 5824 ** Advance the cursor to the next entry in the database. 5825 ** Return value: 5826 ** 5827 ** SQLITE_OK success 5828 ** SQLITE_DONE cursor is already pointing at the last element 5829 ** otherwise some kind of error occurred 5830 ** 5831 ** The main entry point is sqlite3BtreeNext(). That routine is optimized 5832 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx 5833 ** to the next cell on the current page. The (slower) btreeNext() helper 5834 ** routine is called when it is necessary to move to a different page or 5835 ** to restore the cursor. 5836 ** 5837 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the 5838 ** cursor corresponds to an SQL index and this routine could have been 5839 ** skipped if the SQL index had been a unique index. The F argument 5840 ** is a hint to the implement. SQLite btree implementation does not use 5841 ** this hint, but COMDB2 does. 5842 */ 5843 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){ 5844 int rc; 5845 int idx; 5846 MemPage *pPage; 5847 5848 assert( cursorOwnsBtShared(pCur) ); 5849 if( pCur->eState!=CURSOR_VALID ){ 5850 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5851 rc = restoreCursorPosition(pCur); 5852 if( rc!=SQLITE_OK ){ 5853 return rc; 5854 } 5855 if( CURSOR_INVALID==pCur->eState ){ 5856 return SQLITE_DONE; 5857 } 5858 if( pCur->eState==CURSOR_SKIPNEXT ){ 5859 pCur->eState = CURSOR_VALID; 5860 if( pCur->skipNext>0 ) return SQLITE_OK; 5861 } 5862 } 5863 5864 pPage = pCur->pPage; 5865 idx = ++pCur->ix; 5866 if( !pPage->isInit || sqlite3FaultSim(412) ){ 5867 /* The only known way for this to happen is for there to be a 5868 ** recursive SQL function that does a DELETE operation as part of a 5869 ** SELECT which deletes content out from under an active cursor 5870 ** in a corrupt database file where the table being DELETE-ed from 5871 ** has pages in common with the table being queried. See TH3 5872 ** module cov1/btree78.test testcase 220 (2018-06-08) for an 5873 ** example. */ 5874 return SQLITE_CORRUPT_BKPT; 5875 } 5876 5877 /* If the database file is corrupt, it is possible for the value of idx 5878 ** to be invalid here. This can only occur if a second cursor modifies 5879 ** the page while cursor pCur is holding a reference to it. Which can 5880 ** only happen if the database is corrupt in such a way as to link the 5881 ** page into more than one b-tree structure. 5882 ** 5883 ** Update 2019-12-23: appears to long longer be possible after the 5884 ** addition of anotherValidCursor() condition on balance_deeper(). */ 5885 harmless( idx>pPage->nCell ); 5886 5887 if( idx>=pPage->nCell ){ 5888 if( !pPage->leaf ){ 5889 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 5890 if( rc ) return rc; 5891 return moveToLeftmost(pCur); 5892 } 5893 do{ 5894 if( pCur->iPage==0 ){ 5895 pCur->eState = CURSOR_INVALID; 5896 return SQLITE_DONE; 5897 } 5898 moveToParent(pCur); 5899 pPage = pCur->pPage; 5900 }while( pCur->ix>=pPage->nCell ); 5901 if( pPage->intKey ){ 5902 return sqlite3BtreeNext(pCur, 0); 5903 }else{ 5904 return SQLITE_OK; 5905 } 5906 } 5907 if( pPage->leaf ){ 5908 return SQLITE_OK; 5909 }else{ 5910 return moveToLeftmost(pCur); 5911 } 5912 } 5913 int sqlite3BtreeNext(BtCursor *pCur, int flags){ 5914 MemPage *pPage; 5915 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ 5916 assert( cursorOwnsBtShared(pCur) ); 5917 assert( flags==0 || flags==1 ); 5918 pCur->info.nSize = 0; 5919 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5920 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur); 5921 pPage = pCur->pPage; 5922 if( (++pCur->ix)>=pPage->nCell ){ 5923 pCur->ix--; 5924 return btreeNext(pCur); 5925 } 5926 if( pPage->leaf ){ 5927 return SQLITE_OK; 5928 }else{ 5929 return moveToLeftmost(pCur); 5930 } 5931 } 5932 5933 /* 5934 ** Step the cursor to the back to the previous entry in the database. 5935 ** Return values: 5936 ** 5937 ** SQLITE_OK success 5938 ** SQLITE_DONE the cursor is already on the first element of the table 5939 ** otherwise some kind of error occurred 5940 ** 5941 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized 5942 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx 5943 ** to the previous cell on the current page. The (slower) btreePrevious() 5944 ** helper routine is called when it is necessary to move to a different page 5945 ** or to restore the cursor. 5946 ** 5947 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then 5948 ** the cursor corresponds to an SQL index and this routine could have been 5949 ** skipped if the SQL index had been a unique index. The F argument is a 5950 ** hint to the implement. The native SQLite btree implementation does not 5951 ** use this hint, but COMDB2 does. 5952 */ 5953 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){ 5954 int rc; 5955 MemPage *pPage; 5956 5957 assert( cursorOwnsBtShared(pCur) ); 5958 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); 5959 assert( pCur->info.nSize==0 ); 5960 if( pCur->eState!=CURSOR_VALID ){ 5961 rc = restoreCursorPosition(pCur); 5962 if( rc!=SQLITE_OK ){ 5963 return rc; 5964 } 5965 if( CURSOR_INVALID==pCur->eState ){ 5966 return SQLITE_DONE; 5967 } 5968 if( CURSOR_SKIPNEXT==pCur->eState ){ 5969 pCur->eState = CURSOR_VALID; 5970 if( pCur->skipNext<0 ) return SQLITE_OK; 5971 } 5972 } 5973 5974 pPage = pCur->pPage; 5975 assert( pPage->isInit ); 5976 if( !pPage->leaf ){ 5977 int idx = pCur->ix; 5978 rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); 5979 if( rc ) return rc; 5980 rc = moveToRightmost(pCur); 5981 }else{ 5982 while( pCur->ix==0 ){ 5983 if( pCur->iPage==0 ){ 5984 pCur->eState = CURSOR_INVALID; 5985 return SQLITE_DONE; 5986 } 5987 moveToParent(pCur); 5988 } 5989 assert( pCur->info.nSize==0 ); 5990 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 ); 5991 5992 pCur->ix--; 5993 pPage = pCur->pPage; 5994 if( pPage->intKey && !pPage->leaf ){ 5995 rc = sqlite3BtreePrevious(pCur, 0); 5996 }else{ 5997 rc = SQLITE_OK; 5998 } 5999 } 6000 return rc; 6001 } 6002 int sqlite3BtreePrevious(BtCursor *pCur, int flags){ 6003 assert( cursorOwnsBtShared(pCur) ); 6004 assert( flags==0 || flags==1 ); 6005 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ 6006 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); 6007 pCur->info.nSize = 0; 6008 if( pCur->eState!=CURSOR_VALID 6009 || pCur->ix==0 6010 || pCur->pPage->leaf==0 6011 ){ 6012 return btreePrevious(pCur); 6013 } 6014 pCur->ix--; 6015 return SQLITE_OK; 6016 } 6017 6018 /* 6019 ** Allocate a new page from the database file. 6020 ** 6021 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() 6022 ** has already been called on the new page.) The new page has also 6023 ** been referenced and the calling routine is responsible for calling 6024 ** sqlite3PagerUnref() on the new page when it is done. 6025 ** 6026 ** SQLITE_OK is returned on success. Any other return value indicates 6027 ** an error. *ppPage is set to NULL in the event of an error. 6028 ** 6029 ** If the "nearby" parameter is not 0, then an effort is made to 6030 ** locate a page close to the page number "nearby". This can be used in an 6031 ** attempt to keep related pages close to each other in the database file, 6032 ** which in turn can make database access faster. 6033 ** 6034 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists 6035 ** anywhere on the free-list, then it is guaranteed to be returned. If 6036 ** eMode is BTALLOC_LT then the page returned will be less than or equal 6037 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there 6038 ** are no restrictions on which page is returned. 6039 */ 6040 static int allocateBtreePage( 6041 BtShared *pBt, /* The btree */ 6042 MemPage **ppPage, /* Store pointer to the allocated page here */ 6043 Pgno *pPgno, /* Store the page number here */ 6044 Pgno nearby, /* Search for a page near this one */ 6045 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ 6046 ){ 6047 MemPage *pPage1; 6048 int rc; 6049 u32 n; /* Number of pages on the freelist */ 6050 u32 k; /* Number of leaves on the trunk of the freelist */ 6051 MemPage *pTrunk = 0; 6052 MemPage *pPrevTrunk = 0; 6053 Pgno mxPage; /* Total size of the database file */ 6054 6055 assert( sqlite3_mutex_held(pBt->mutex) ); 6056 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); 6057 pPage1 = pBt->pPage1; 6058 mxPage = btreePagecount(pBt); 6059 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 6060 ** stores stores the total number of pages on the freelist. */ 6061 n = get4byte(&pPage1->aData[36]); 6062 testcase( n==mxPage-1 ); 6063 if( n>=mxPage ){ 6064 return SQLITE_CORRUPT_BKPT; 6065 } 6066 if( n>0 ){ 6067 /* There are pages on the freelist. Reuse one of those pages. */ 6068 Pgno iTrunk; 6069 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ 6070 u32 nSearch = 0; /* Count of the number of search attempts */ 6071 6072 /* If eMode==BTALLOC_EXACT and a query of the pointer-map 6073 ** shows that the page 'nearby' is somewhere on the free-list, then 6074 ** the entire-list will be searched for that page. 6075 */ 6076 #ifndef SQLITE_OMIT_AUTOVACUUM 6077 if( eMode==BTALLOC_EXACT ){ 6078 if( nearby<=mxPage ){ 6079 u8 eType; 6080 assert( nearby>0 ); 6081 assert( pBt->autoVacuum ); 6082 rc = ptrmapGet(pBt, nearby, &eType, 0); 6083 if( rc ) return rc; 6084 if( eType==PTRMAP_FREEPAGE ){ 6085 searchList = 1; 6086 } 6087 } 6088 }else if( eMode==BTALLOC_LE ){ 6089 searchList = 1; 6090 } 6091 #endif 6092 6093 /* Decrement the free-list count by 1. Set iTrunk to the index of the 6094 ** first free-list trunk page. iPrevTrunk is initially 1. 6095 */ 6096 rc = sqlite3PagerWrite(pPage1->pDbPage); 6097 if( rc ) return rc; 6098 put4byte(&pPage1->aData[36], n-1); 6099 6100 /* The code within this loop is run only once if the 'searchList' variable 6101 ** is not true. Otherwise, it runs once for each trunk-page on the 6102 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) 6103 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) 6104 */ 6105 do { 6106 pPrevTrunk = pTrunk; 6107 if( pPrevTrunk ){ 6108 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page 6109 ** is the page number of the next freelist trunk page in the list or 6110 ** zero if this is the last freelist trunk page. */ 6111 iTrunk = get4byte(&pPrevTrunk->aData[0]); 6112 }else{ 6113 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 6114 ** stores the page number of the first page of the freelist, or zero if 6115 ** the freelist is empty. */ 6116 iTrunk = get4byte(&pPage1->aData[32]); 6117 } 6118 testcase( iTrunk==mxPage ); 6119 if( iTrunk>mxPage || nSearch++ > n ){ 6120 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1); 6121 }else{ 6122 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); 6123 } 6124 if( rc ){ 6125 pTrunk = 0; 6126 goto end_allocate_page; 6127 } 6128 assert( pTrunk!=0 ); 6129 assert( pTrunk->aData!=0 ); 6130 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page 6131 ** is the number of leaf page pointers to follow. */ 6132 k = get4byte(&pTrunk->aData[4]); 6133 if( k==0 && !searchList ){ 6134 /* The trunk has no leaves and the list is not being searched. 6135 ** So extract the trunk page itself and use it as the newly 6136 ** allocated page */ 6137 assert( pPrevTrunk==0 ); 6138 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6139 if( rc ){ 6140 goto end_allocate_page; 6141 } 6142 *pPgno = iTrunk; 6143 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 6144 *ppPage = pTrunk; 6145 pTrunk = 0; 6146 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 6147 }else if( k>(u32)(pBt->usableSize/4 - 2) ){ 6148 /* Value of k is out of range. Database corruption */ 6149 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6150 goto end_allocate_page; 6151 #ifndef SQLITE_OMIT_AUTOVACUUM 6152 }else if( searchList 6153 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 6154 ){ 6155 /* The list is being searched and this trunk page is the page 6156 ** to allocate, regardless of whether it has leaves. 6157 */ 6158 *pPgno = iTrunk; 6159 *ppPage = pTrunk; 6160 searchList = 0; 6161 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6162 if( rc ){ 6163 goto end_allocate_page; 6164 } 6165 if( k==0 ){ 6166 if( !pPrevTrunk ){ 6167 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 6168 }else{ 6169 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 6170 if( rc!=SQLITE_OK ){ 6171 goto end_allocate_page; 6172 } 6173 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); 6174 } 6175 }else{ 6176 /* The trunk page is required by the caller but it contains 6177 ** pointers to free-list leaves. The first leaf becomes a trunk 6178 ** page in this case. 6179 */ 6180 MemPage *pNewTrunk; 6181 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); 6182 if( iNewTrunk>mxPage ){ 6183 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6184 goto end_allocate_page; 6185 } 6186 testcase( iNewTrunk==mxPage ); 6187 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); 6188 if( rc!=SQLITE_OK ){ 6189 goto end_allocate_page; 6190 } 6191 rc = sqlite3PagerWrite(pNewTrunk->pDbPage); 6192 if( rc!=SQLITE_OK ){ 6193 releasePage(pNewTrunk); 6194 goto end_allocate_page; 6195 } 6196 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); 6197 put4byte(&pNewTrunk->aData[4], k-1); 6198 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); 6199 releasePage(pNewTrunk); 6200 if( !pPrevTrunk ){ 6201 assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); 6202 put4byte(&pPage1->aData[32], iNewTrunk); 6203 }else{ 6204 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 6205 if( rc ){ 6206 goto end_allocate_page; 6207 } 6208 put4byte(&pPrevTrunk->aData[0], iNewTrunk); 6209 } 6210 } 6211 pTrunk = 0; 6212 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 6213 #endif 6214 }else if( k>0 ){ 6215 /* Extract a leaf from the trunk */ 6216 u32 closest; 6217 Pgno iPage; 6218 unsigned char *aData = pTrunk->aData; 6219 if( nearby>0 ){ 6220 u32 i; 6221 closest = 0; 6222 if( eMode==BTALLOC_LE ){ 6223 for(i=0; i<k; i++){ 6224 iPage = get4byte(&aData[8+i*4]); 6225 if( iPage<=nearby ){ 6226 closest = i; 6227 break; 6228 } 6229 } 6230 }else{ 6231 int dist; 6232 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); 6233 for(i=1; i<k; i++){ 6234 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); 6235 if( d2<dist ){ 6236 closest = i; 6237 dist = d2; 6238 } 6239 } 6240 } 6241 }else{ 6242 closest = 0; 6243 } 6244 6245 iPage = get4byte(&aData[8+closest*4]); 6246 testcase( iPage==mxPage ); 6247 if( iPage>mxPage || iPage<2 ){ 6248 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6249 goto end_allocate_page; 6250 } 6251 testcase( iPage==mxPage ); 6252 if( !searchList 6253 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 6254 ){ 6255 int noContent; 6256 *pPgno = iPage; 6257 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" 6258 ": %d more free pages\n", 6259 *pPgno, closest+1, k, pTrunk->pgno, n-1)); 6260 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6261 if( rc ) goto end_allocate_page; 6262 if( closest<k-1 ){ 6263 memcpy(&aData[8+closest*4], &aData[4+k*4], 4); 6264 } 6265 put4byte(&aData[4], k-1); 6266 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; 6267 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); 6268 if( rc==SQLITE_OK ){ 6269 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 6270 if( rc!=SQLITE_OK ){ 6271 releasePage(*ppPage); 6272 *ppPage = 0; 6273 } 6274 } 6275 searchList = 0; 6276 } 6277 } 6278 releasePage(pPrevTrunk); 6279 pPrevTrunk = 0; 6280 }while( searchList ); 6281 }else{ 6282 /* There are no pages on the freelist, so append a new page to the 6283 ** database image. 6284 ** 6285 ** Normally, new pages allocated by this block can be requested from the 6286 ** pager layer with the 'no-content' flag set. This prevents the pager 6287 ** from trying to read the pages content from disk. However, if the 6288 ** current transaction has already run one or more incremental-vacuum 6289 ** steps, then the page we are about to allocate may contain content 6290 ** that is required in the event of a rollback. In this case, do 6291 ** not set the no-content flag. This causes the pager to load and journal 6292 ** the current page content before overwriting it. 6293 ** 6294 ** Note that the pager will not actually attempt to load or journal 6295 ** content for any page that really does lie past the end of the database 6296 ** file on disk. So the effects of disabling the no-content optimization 6297 ** here are confined to those pages that lie between the end of the 6298 ** database image and the end of the database file. 6299 */ 6300 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; 6301 6302 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 6303 if( rc ) return rc; 6304 pBt->nPage++; 6305 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; 6306 6307 #ifndef SQLITE_OMIT_AUTOVACUUM 6308 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ 6309 /* If *pPgno refers to a pointer-map page, allocate two new pages 6310 ** at the end of the file instead of one. The first allocated page 6311 ** becomes a new pointer-map page, the second is used by the caller. 6312 */ 6313 MemPage *pPg = 0; 6314 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); 6315 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); 6316 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); 6317 if( rc==SQLITE_OK ){ 6318 rc = sqlite3PagerWrite(pPg->pDbPage); 6319 releasePage(pPg); 6320 } 6321 if( rc ) return rc; 6322 pBt->nPage++; 6323 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } 6324 } 6325 #endif 6326 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); 6327 *pPgno = pBt->nPage; 6328 6329 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); 6330 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); 6331 if( rc ) return rc; 6332 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 6333 if( rc!=SQLITE_OK ){ 6334 releasePage(*ppPage); 6335 *ppPage = 0; 6336 } 6337 TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); 6338 } 6339 6340 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) ); 6341 6342 end_allocate_page: 6343 releasePage(pTrunk); 6344 releasePage(pPrevTrunk); 6345 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); 6346 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); 6347 return rc; 6348 } 6349 6350 /* 6351 ** This function is used to add page iPage to the database file free-list. 6352 ** It is assumed that the page is not already a part of the free-list. 6353 ** 6354 ** The value passed as the second argument to this function is optional. 6355 ** If the caller happens to have a pointer to the MemPage object 6356 ** corresponding to page iPage handy, it may pass it as the second value. 6357 ** Otherwise, it may pass NULL. 6358 ** 6359 ** If a pointer to a MemPage object is passed as the second argument, 6360 ** its reference count is not altered by this function. 6361 */ 6362 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ 6363 MemPage *pTrunk = 0; /* Free-list trunk page */ 6364 Pgno iTrunk = 0; /* Page number of free-list trunk page */ 6365 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ 6366 MemPage *pPage; /* Page being freed. May be NULL. */ 6367 int rc; /* Return Code */ 6368 u32 nFree; /* Initial number of pages on free-list */ 6369 6370 assert( sqlite3_mutex_held(pBt->mutex) ); 6371 assert( CORRUPT_DB || iPage>1 ); 6372 assert( !pMemPage || pMemPage->pgno==iPage ); 6373 6374 if( iPage<2 || iPage>pBt->nPage ){ 6375 return SQLITE_CORRUPT_BKPT; 6376 } 6377 if( pMemPage ){ 6378 pPage = pMemPage; 6379 sqlite3PagerRef(pPage->pDbPage); 6380 }else{ 6381 pPage = btreePageLookup(pBt, iPage); 6382 } 6383 6384 /* Increment the free page count on pPage1 */ 6385 rc = sqlite3PagerWrite(pPage1->pDbPage); 6386 if( rc ) goto freepage_out; 6387 nFree = get4byte(&pPage1->aData[36]); 6388 put4byte(&pPage1->aData[36], nFree+1); 6389 6390 if( pBt->btsFlags & BTS_SECURE_DELETE ){ 6391 /* If the secure_delete option is enabled, then 6392 ** always fully overwrite deleted information with zeros. 6393 */ 6394 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) 6395 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) 6396 ){ 6397 goto freepage_out; 6398 } 6399 memset(pPage->aData, 0, pPage->pBt->pageSize); 6400 } 6401 6402 /* If the database supports auto-vacuum, write an entry in the pointer-map 6403 ** to indicate that the page is free. 6404 */ 6405 if( ISAUTOVACUUM ){ 6406 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); 6407 if( rc ) goto freepage_out; 6408 } 6409 6410 /* Now manipulate the actual database free-list structure. There are two 6411 ** possibilities. If the free-list is currently empty, or if the first 6412 ** trunk page in the free-list is full, then this page will become a 6413 ** new free-list trunk page. Otherwise, it will become a leaf of the 6414 ** first trunk page in the current free-list. This block tests if it 6415 ** is possible to add the page as a new free-list leaf. 6416 */ 6417 if( nFree!=0 ){ 6418 u32 nLeaf; /* Initial number of leaf cells on trunk page */ 6419 6420 iTrunk = get4byte(&pPage1->aData[32]); 6421 if( iTrunk>btreePagecount(pBt) ){ 6422 rc = SQLITE_CORRUPT_BKPT; 6423 goto freepage_out; 6424 } 6425 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); 6426 if( rc!=SQLITE_OK ){ 6427 goto freepage_out; 6428 } 6429 6430 nLeaf = get4byte(&pTrunk->aData[4]); 6431 assert( pBt->usableSize>32 ); 6432 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ 6433 rc = SQLITE_CORRUPT_BKPT; 6434 goto freepage_out; 6435 } 6436 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ 6437 /* In this case there is room on the trunk page to insert the page 6438 ** being freed as a new leaf. 6439 ** 6440 ** Note that the trunk page is not really full until it contains 6441 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have 6442 ** coded. But due to a coding error in versions of SQLite prior to 6443 ** 3.6.0, databases with freelist trunk pages holding more than 6444 ** usableSize/4 - 8 entries will be reported as corrupt. In order 6445 ** to maintain backwards compatibility with older versions of SQLite, 6446 ** we will continue to restrict the number of entries to usableSize/4 - 8 6447 ** for now. At some point in the future (once everyone has upgraded 6448 ** to 3.6.0 or later) we should consider fixing the conditional above 6449 ** to read "usableSize/4-2" instead of "usableSize/4-8". 6450 ** 6451 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still 6452 ** avoid using the last six entries in the freelist trunk page array in 6453 ** order that database files created by newer versions of SQLite can be 6454 ** read by older versions of SQLite. 6455 */ 6456 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6457 if( rc==SQLITE_OK ){ 6458 put4byte(&pTrunk->aData[4], nLeaf+1); 6459 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); 6460 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ 6461 sqlite3PagerDontWrite(pPage->pDbPage); 6462 } 6463 rc = btreeSetHasContent(pBt, iPage); 6464 } 6465 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); 6466 goto freepage_out; 6467 } 6468 } 6469 6470 /* If control flows to this point, then it was not possible to add the 6471 ** the page being freed as a leaf page of the first trunk in the free-list. 6472 ** Possibly because the free-list is empty, or possibly because the 6473 ** first trunk in the free-list is full. Either way, the page being freed 6474 ** will become the new first trunk page in the free-list. 6475 */ 6476 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ 6477 goto freepage_out; 6478 } 6479 rc = sqlite3PagerWrite(pPage->pDbPage); 6480 if( rc!=SQLITE_OK ){ 6481 goto freepage_out; 6482 } 6483 put4byte(pPage->aData, iTrunk); 6484 put4byte(&pPage->aData[4], 0); 6485 put4byte(&pPage1->aData[32], iPage); 6486 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); 6487 6488 freepage_out: 6489 if( pPage ){ 6490 pPage->isInit = 0; 6491 } 6492 releasePage(pPage); 6493 releasePage(pTrunk); 6494 return rc; 6495 } 6496 static void freePage(MemPage *pPage, int *pRC){ 6497 if( (*pRC)==SQLITE_OK ){ 6498 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); 6499 } 6500 } 6501 6502 /* 6503 ** Free the overflow pages associated with the given Cell. 6504 */ 6505 static SQLITE_NOINLINE int clearCellOverflow( 6506 MemPage *pPage, /* The page that contains the Cell */ 6507 unsigned char *pCell, /* First byte of the Cell */ 6508 CellInfo *pInfo /* Size information about the cell */ 6509 ){ 6510 BtShared *pBt; 6511 Pgno ovflPgno; 6512 int rc; 6513 int nOvfl; 6514 u32 ovflPageSize; 6515 6516 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6517 assert( pInfo->nLocal!=pInfo->nPayload ); 6518 testcase( pCell + pInfo->nSize == pPage->aDataEnd ); 6519 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd ); 6520 if( pCell + pInfo->nSize > pPage->aDataEnd ){ 6521 /* Cell extends past end of page */ 6522 return SQLITE_CORRUPT_PAGE(pPage); 6523 } 6524 ovflPgno = get4byte(pCell + pInfo->nSize - 4); 6525 pBt = pPage->pBt; 6526 assert( pBt->usableSize > 4 ); 6527 ovflPageSize = pBt->usableSize - 4; 6528 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; 6529 assert( nOvfl>0 || 6530 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize) 6531 ); 6532 while( nOvfl-- ){ 6533 Pgno iNext = 0; 6534 MemPage *pOvfl = 0; 6535 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ 6536 /* 0 is not a legal page number and page 1 cannot be an 6537 ** overflow page. Therefore if ovflPgno<2 or past the end of the 6538 ** file the database must be corrupt. */ 6539 return SQLITE_CORRUPT_BKPT; 6540 } 6541 if( nOvfl ){ 6542 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); 6543 if( rc ) return rc; 6544 } 6545 6546 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) 6547 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 6548 ){ 6549 /* There is no reason any cursor should have an outstanding reference 6550 ** to an overflow page belonging to a cell that is being deleted/updated. 6551 ** So if there exists more than one reference to this page, then it 6552 ** must not really be an overflow page and the database must be corrupt. 6553 ** It is helpful to detect this before calling freePage2(), as 6554 ** freePage2() may zero the page contents if secure-delete mode is 6555 ** enabled. If this 'overflow' page happens to be a page that the 6556 ** caller is iterating through or using in some other way, this 6557 ** can be problematic. 6558 */ 6559 rc = SQLITE_CORRUPT_BKPT; 6560 }else{ 6561 rc = freePage2(pBt, pOvfl, ovflPgno); 6562 } 6563 6564 if( pOvfl ){ 6565 sqlite3PagerUnref(pOvfl->pDbPage); 6566 } 6567 if( rc ) return rc; 6568 ovflPgno = iNext; 6569 } 6570 return SQLITE_OK; 6571 } 6572 6573 /* Call xParseCell to compute the size of a cell. If the cell contains 6574 ** overflow, then invoke cellClearOverflow to clear out that overflow. 6575 ** STore the result code (SQLITE_OK or some error code) in rc. 6576 ** 6577 ** Implemented as macro to force inlining for performance. 6578 */ 6579 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \ 6580 pPage->xParseCell(pPage, pCell, &sInfo); \ 6581 if( sInfo.nLocal!=sInfo.nPayload ){ \ 6582 rc = clearCellOverflow(pPage, pCell, &sInfo); \ 6583 }else{ \ 6584 rc = SQLITE_OK; \ 6585 } 6586 6587 6588 /* 6589 ** Create the byte sequence used to represent a cell on page pPage 6590 ** and write that byte sequence into pCell[]. Overflow pages are 6591 ** allocated and filled in as necessary. The calling procedure 6592 ** is responsible for making sure sufficient space has been allocated 6593 ** for pCell[]. 6594 ** 6595 ** Note that pCell does not necessary need to point to the pPage->aData 6596 ** area. pCell might point to some temporary storage. The cell will 6597 ** be constructed in this temporary area then copied into pPage->aData 6598 ** later. 6599 */ 6600 static int fillInCell( 6601 MemPage *pPage, /* The page that contains the cell */ 6602 unsigned char *pCell, /* Complete text of the cell */ 6603 const BtreePayload *pX, /* Payload with which to construct the cell */ 6604 int *pnSize /* Write cell size here */ 6605 ){ 6606 int nPayload; 6607 const u8 *pSrc; 6608 int nSrc, n, rc, mn; 6609 int spaceLeft; 6610 MemPage *pToRelease; 6611 unsigned char *pPrior; 6612 unsigned char *pPayload; 6613 BtShared *pBt; 6614 Pgno pgnoOvfl; 6615 int nHeader; 6616 6617 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6618 6619 /* pPage is not necessarily writeable since pCell might be auxiliary 6620 ** buffer space that is separate from the pPage buffer area */ 6621 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize] 6622 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6623 6624 /* Fill in the header. */ 6625 nHeader = pPage->childPtrSize; 6626 if( pPage->intKey ){ 6627 nPayload = pX->nData + pX->nZero; 6628 pSrc = pX->pData; 6629 nSrc = pX->nData; 6630 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ 6631 nHeader += putVarint32(&pCell[nHeader], nPayload); 6632 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); 6633 }else{ 6634 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); 6635 nSrc = nPayload = (int)pX->nKey; 6636 pSrc = pX->pKey; 6637 nHeader += putVarint32(&pCell[nHeader], nPayload); 6638 } 6639 6640 /* Fill in the payload */ 6641 pPayload = &pCell[nHeader]; 6642 if( nPayload<=pPage->maxLocal ){ 6643 /* This is the common case where everything fits on the btree page 6644 ** and no overflow pages are required. */ 6645 n = nHeader + nPayload; 6646 testcase( n==3 ); 6647 testcase( n==4 ); 6648 if( n<4 ) n = 4; 6649 *pnSize = n; 6650 assert( nSrc<=nPayload ); 6651 testcase( nSrc<nPayload ); 6652 memcpy(pPayload, pSrc, nSrc); 6653 memset(pPayload+nSrc, 0, nPayload-nSrc); 6654 return SQLITE_OK; 6655 } 6656 6657 /* If we reach this point, it means that some of the content will need 6658 ** to spill onto overflow pages. 6659 */ 6660 mn = pPage->minLocal; 6661 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); 6662 testcase( n==pPage->maxLocal ); 6663 testcase( n==pPage->maxLocal+1 ); 6664 if( n > pPage->maxLocal ) n = mn; 6665 spaceLeft = n; 6666 *pnSize = n + nHeader + 4; 6667 pPrior = &pCell[nHeader+n]; 6668 pToRelease = 0; 6669 pgnoOvfl = 0; 6670 pBt = pPage->pBt; 6671 6672 /* At this point variables should be set as follows: 6673 ** 6674 ** nPayload Total payload size in bytes 6675 ** pPayload Begin writing payload here 6676 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, 6677 ** that means content must spill into overflow pages. 6678 ** *pnSize Size of the local cell (not counting overflow pages) 6679 ** pPrior Where to write the pgno of the first overflow page 6680 ** 6681 ** Use a call to btreeParseCellPtr() to verify that the values above 6682 ** were computed correctly. 6683 */ 6684 #ifdef SQLITE_DEBUG 6685 { 6686 CellInfo info; 6687 pPage->xParseCell(pPage, pCell, &info); 6688 assert( nHeader==(int)(info.pPayload - pCell) ); 6689 assert( info.nKey==pX->nKey ); 6690 assert( *pnSize == info.nSize ); 6691 assert( spaceLeft == info.nLocal ); 6692 } 6693 #endif 6694 6695 /* Write the payload into the local Cell and any extra into overflow pages */ 6696 while( 1 ){ 6697 n = nPayload; 6698 if( n>spaceLeft ) n = spaceLeft; 6699 6700 /* If pToRelease is not zero than pPayload points into the data area 6701 ** of pToRelease. Make sure pToRelease is still writeable. */ 6702 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6703 6704 /* If pPayload is part of the data area of pPage, then make sure pPage 6705 ** is still writeable */ 6706 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] 6707 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6708 6709 if( nSrc>=n ){ 6710 memcpy(pPayload, pSrc, n); 6711 }else if( nSrc>0 ){ 6712 n = nSrc; 6713 memcpy(pPayload, pSrc, n); 6714 }else{ 6715 memset(pPayload, 0, n); 6716 } 6717 nPayload -= n; 6718 if( nPayload<=0 ) break; 6719 pPayload += n; 6720 pSrc += n; 6721 nSrc -= n; 6722 spaceLeft -= n; 6723 if( spaceLeft==0 ){ 6724 MemPage *pOvfl = 0; 6725 #ifndef SQLITE_OMIT_AUTOVACUUM 6726 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ 6727 if( pBt->autoVacuum ){ 6728 do{ 6729 pgnoOvfl++; 6730 } while( 6731 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 6732 ); 6733 } 6734 #endif 6735 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); 6736 #ifndef SQLITE_OMIT_AUTOVACUUM 6737 /* If the database supports auto-vacuum, and the second or subsequent 6738 ** overflow page is being allocated, add an entry to the pointer-map 6739 ** for that page now. 6740 ** 6741 ** If this is the first overflow page, then write a partial entry 6742 ** to the pointer-map. If we write nothing to this pointer-map slot, 6743 ** then the optimistic overflow chain processing in clearCell() 6744 ** may misinterpret the uninitialized values and delete the 6745 ** wrong pages from the database. 6746 */ 6747 if( pBt->autoVacuum && rc==SQLITE_OK ){ 6748 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); 6749 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); 6750 if( rc ){ 6751 releasePage(pOvfl); 6752 } 6753 } 6754 #endif 6755 if( rc ){ 6756 releasePage(pToRelease); 6757 return rc; 6758 } 6759 6760 /* If pToRelease is not zero than pPrior points into the data area 6761 ** of pToRelease. Make sure pToRelease is still writeable. */ 6762 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6763 6764 /* If pPrior is part of the data area of pPage, then make sure pPage 6765 ** is still writeable */ 6766 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize] 6767 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6768 6769 put4byte(pPrior, pgnoOvfl); 6770 releasePage(pToRelease); 6771 pToRelease = pOvfl; 6772 pPrior = pOvfl->aData; 6773 put4byte(pPrior, 0); 6774 pPayload = &pOvfl->aData[4]; 6775 spaceLeft = pBt->usableSize - 4; 6776 } 6777 } 6778 releasePage(pToRelease); 6779 return SQLITE_OK; 6780 } 6781 6782 /* 6783 ** Remove the i-th cell from pPage. This routine effects pPage only. 6784 ** The cell content is not freed or deallocated. It is assumed that 6785 ** the cell content has been copied someplace else. This routine just 6786 ** removes the reference to the cell from pPage. 6787 ** 6788 ** "sz" must be the number of bytes in the cell. 6789 */ 6790 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ 6791 u32 pc; /* Offset to cell content of cell being deleted */ 6792 u8 *data; /* pPage->aData */ 6793 u8 *ptr; /* Used to move bytes around within data[] */ 6794 int rc; /* The return code */ 6795 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ 6796 6797 if( *pRC ) return; 6798 assert( idx>=0 && idx<pPage->nCell ); 6799 assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); 6800 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6801 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6802 assert( pPage->nFree>=0 ); 6803 data = pPage->aData; 6804 ptr = &pPage->aCellIdx[2*idx]; 6805 pc = get2byte(ptr); 6806 hdr = pPage->hdrOffset; 6807 testcase( pc==get2byte(&data[hdr+5]) ); 6808 testcase( pc+sz==pPage->pBt->usableSize ); 6809 if( pc+sz > pPage->pBt->usableSize ){ 6810 *pRC = SQLITE_CORRUPT_BKPT; 6811 return; 6812 } 6813 rc = freeSpace(pPage, pc, sz); 6814 if( rc ){ 6815 *pRC = rc; 6816 return; 6817 } 6818 pPage->nCell--; 6819 if( pPage->nCell==0 ){ 6820 memset(&data[hdr+1], 0, 4); 6821 data[hdr+7] = 0; 6822 put2byte(&data[hdr+5], pPage->pBt->usableSize); 6823 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset 6824 - pPage->childPtrSize - 8; 6825 }else{ 6826 memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); 6827 put2byte(&data[hdr+3], pPage->nCell); 6828 pPage->nFree += 2; 6829 } 6830 } 6831 6832 /* 6833 ** Insert a new cell on pPage at cell index "i". pCell points to the 6834 ** content of the cell. 6835 ** 6836 ** If the cell content will fit on the page, then put it there. If it 6837 ** will not fit, then make a copy of the cell content into pTemp if 6838 ** pTemp is not null. Regardless of pTemp, allocate a new entry 6839 ** in pPage->apOvfl[] and make it point to the cell content (either 6840 ** in pTemp or the original pCell) and also record its index. 6841 ** Allocating a new entry in pPage->aCell[] implies that 6842 ** pPage->nOverflow is incremented. 6843 ** 6844 ** *pRC must be SQLITE_OK when this routine is called. 6845 */ 6846 static void insertCell( 6847 MemPage *pPage, /* Page into which we are copying */ 6848 int i, /* New cell becomes the i-th cell of the page */ 6849 u8 *pCell, /* Content of the new cell */ 6850 int sz, /* Bytes of content in pCell */ 6851 u8 *pTemp, /* Temp storage space for pCell, if needed */ 6852 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ 6853 int *pRC /* Read and write return code from here */ 6854 ){ 6855 int idx = 0; /* Where to write new cell content in data[] */ 6856 int j; /* Loop counter */ 6857 u8 *data; /* The content of the whole page */ 6858 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ 6859 6860 assert( *pRC==SQLITE_OK ); 6861 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); 6862 assert( MX_CELL(pPage->pBt)<=10921 ); 6863 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); 6864 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); 6865 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); 6866 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6867 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB ); 6868 assert( pPage->nFree>=0 ); 6869 if( pPage->nOverflow || sz+2>pPage->nFree ){ 6870 if( pTemp ){ 6871 memcpy(pTemp, pCell, sz); 6872 pCell = pTemp; 6873 } 6874 if( iChild ){ 6875 put4byte(pCell, iChild); 6876 } 6877 j = pPage->nOverflow++; 6878 /* Comparison against ArraySize-1 since we hold back one extra slot 6879 ** as a contingency. In other words, never need more than 3 overflow 6880 ** slots but 4 are allocated, just to be safe. */ 6881 assert( j < ArraySize(pPage->apOvfl)-1 ); 6882 pPage->apOvfl[j] = pCell; 6883 pPage->aiOvfl[j] = (u16)i; 6884 6885 /* When multiple overflows occur, they are always sequential and in 6886 ** sorted order. This invariants arise because multiple overflows can 6887 ** only occur when inserting divider cells into the parent page during 6888 ** balancing, and the dividers are adjacent and sorted. 6889 */ 6890 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ 6891 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ 6892 }else{ 6893 int rc = sqlite3PagerWrite(pPage->pDbPage); 6894 if( rc!=SQLITE_OK ){ 6895 *pRC = rc; 6896 return; 6897 } 6898 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6899 data = pPage->aData; 6900 assert( &data[pPage->cellOffset]==pPage->aCellIdx ); 6901 rc = allocateSpace(pPage, sz, &idx); 6902 if( rc ){ *pRC = rc; return; } 6903 /* The allocateSpace() routine guarantees the following properties 6904 ** if it returns successfully */ 6905 assert( idx >= 0 ); 6906 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); 6907 assert( idx+sz <= (int)pPage->pBt->usableSize ); 6908 pPage->nFree -= (u16)(2 + sz); 6909 if( iChild ){ 6910 /* In a corrupt database where an entry in the cell index section of 6911 ** a btree page has a value of 3 or less, the pCell value might point 6912 ** as many as 4 bytes in front of the start of the aData buffer for 6913 ** the source page. Make sure this does not cause problems by not 6914 ** reading the first 4 bytes */ 6915 memcpy(&data[idx+4], pCell+4, sz-4); 6916 put4byte(&data[idx], iChild); 6917 }else{ 6918 memcpy(&data[idx], pCell, sz); 6919 } 6920 pIns = pPage->aCellIdx + i*2; 6921 memmove(pIns+2, pIns, 2*(pPage->nCell - i)); 6922 put2byte(pIns, idx); 6923 pPage->nCell++; 6924 /* increment the cell count */ 6925 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; 6926 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB ); 6927 #ifndef SQLITE_OMIT_AUTOVACUUM 6928 if( pPage->pBt->autoVacuum ){ 6929 /* The cell may contain a pointer to an overflow page. If so, write 6930 ** the entry for the overflow page into the pointer map. 6931 */ 6932 ptrmapPutOvflPtr(pPage, pPage, pCell, pRC); 6933 } 6934 #endif 6935 } 6936 } 6937 6938 /* 6939 ** The following parameters determine how many adjacent pages get involved 6940 ** in a balancing operation. NN is the number of neighbors on either side 6941 ** of the page that participate in the balancing operation. NB is the 6942 ** total number of pages that participate, including the target page and 6943 ** NN neighbors on either side. 6944 ** 6945 ** The minimum value of NN is 1 (of course). Increasing NN above 1 6946 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance 6947 ** in exchange for a larger degradation in INSERT and UPDATE performance. 6948 ** The value of NN appears to give the best results overall. 6949 ** 6950 ** (Later:) The description above makes it seem as if these values are 6951 ** tunable - as if you could change them and recompile and it would all work. 6952 ** But that is unlikely. NB has been 3 since the inception of SQLite and 6953 ** we have never tested any other value. 6954 */ 6955 #define NN 1 /* Number of neighbors on either side of pPage */ 6956 #define NB 3 /* (NN*2+1): Total pages involved in the balance */ 6957 6958 /* 6959 ** A CellArray object contains a cache of pointers and sizes for a 6960 ** consecutive sequence of cells that might be held on multiple pages. 6961 ** 6962 ** The cells in this array are the divider cell or cells from the pParent 6963 ** page plus up to three child pages. There are a total of nCell cells. 6964 ** 6965 ** pRef is a pointer to one of the pages that contributes cells. This is 6966 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize 6967 ** which should be common to all pages that contribute cells to this array. 6968 ** 6969 ** apCell[] and szCell[] hold, respectively, pointers to the start of each 6970 ** cell and the size of each cell. Some of the apCell[] pointers might refer 6971 ** to overflow cells. In other words, some apCel[] pointers might not point 6972 ** to content area of the pages. 6973 ** 6974 ** A szCell[] of zero means the size of that cell has not yet been computed. 6975 ** 6976 ** The cells come from as many as four different pages: 6977 ** 6978 ** ----------- 6979 ** | Parent | 6980 ** ----------- 6981 ** / | \ 6982 ** / | \ 6983 ** --------- --------- --------- 6984 ** |Child-1| |Child-2| |Child-3| 6985 ** --------- --------- --------- 6986 ** 6987 ** The order of cells is in the array is for an index btree is: 6988 ** 6989 ** 1. All cells from Child-1 in order 6990 ** 2. The first divider cell from Parent 6991 ** 3. All cells from Child-2 in order 6992 ** 4. The second divider cell from Parent 6993 ** 5. All cells from Child-3 in order 6994 ** 6995 ** For a table-btree (with rowids) the items 2 and 4 are empty because 6996 ** content exists only in leaves and there are no divider cells. 6997 ** 6998 ** For an index btree, the apEnd[] array holds pointer to the end of page 6999 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3, 7000 ** respectively. The ixNx[] array holds the number of cells contained in 7001 ** each of these 5 stages, and all stages to the left. Hence: 7002 ** 7003 ** ixNx[0] = Number of cells in Child-1. 7004 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider. 7005 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider. 7006 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells 7007 ** ixNx[4] = Total number of cells. 7008 ** 7009 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2] 7010 ** are used and they point to the leaf pages only, and the ixNx value are: 7011 ** 7012 ** ixNx[0] = Number of cells in Child-1. 7013 ** ixNx[1] = Number of cells in Child-1 and Child-2. 7014 ** ixNx[2] = Total number of cells. 7015 ** 7016 ** Sometimes when deleting, a child page can have zero cells. In those 7017 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[] 7018 ** entries, shift down. The end result is that each ixNx[] entry should 7019 ** be larger than the previous 7020 */ 7021 typedef struct CellArray CellArray; 7022 struct CellArray { 7023 int nCell; /* Number of cells in apCell[] */ 7024 MemPage *pRef; /* Reference page */ 7025 u8 **apCell; /* All cells begin balanced */ 7026 u16 *szCell; /* Local size of all cells in apCell[] */ 7027 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */ 7028 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */ 7029 }; 7030 7031 /* 7032 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been 7033 ** computed. 7034 */ 7035 static void populateCellCache(CellArray *p, int idx, int N){ 7036 assert( idx>=0 && idx+N<=p->nCell ); 7037 while( N>0 ){ 7038 assert( p->apCell[idx]!=0 ); 7039 if( p->szCell[idx]==0 ){ 7040 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); 7041 }else{ 7042 assert( CORRUPT_DB || 7043 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); 7044 } 7045 idx++; 7046 N--; 7047 } 7048 } 7049 7050 /* 7051 ** Return the size of the Nth element of the cell array 7052 */ 7053 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ 7054 assert( N>=0 && N<p->nCell ); 7055 assert( p->szCell[N]==0 ); 7056 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); 7057 return p->szCell[N]; 7058 } 7059 static u16 cachedCellSize(CellArray *p, int N){ 7060 assert( N>=0 && N<p->nCell ); 7061 if( p->szCell[N] ) return p->szCell[N]; 7062 return computeCellSize(p, N); 7063 } 7064 7065 /* 7066 ** Array apCell[] contains pointers to nCell b-tree page cells. The 7067 ** szCell[] array contains the size in bytes of each cell. This function 7068 ** replaces the current contents of page pPg with the contents of the cell 7069 ** array. 7070 ** 7071 ** Some of the cells in apCell[] may currently be stored in pPg. This 7072 ** function works around problems caused by this by making a copy of any 7073 ** such cells before overwriting the page data. 7074 ** 7075 ** The MemPage.nFree field is invalidated by this function. It is the 7076 ** responsibility of the caller to set it correctly. 7077 */ 7078 static int rebuildPage( 7079 CellArray *pCArray, /* Content to be added to page pPg */ 7080 int iFirst, /* First cell in pCArray to use */ 7081 int nCell, /* Final number of cells on page */ 7082 MemPage *pPg /* The page to be reconstructed */ 7083 ){ 7084 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ 7085 u8 * const aData = pPg->aData; /* Pointer to data for pPg */ 7086 const int usableSize = pPg->pBt->usableSize; 7087 u8 * const pEnd = &aData[usableSize]; 7088 int i = iFirst; /* Which cell to copy from pCArray*/ 7089 u32 j; /* Start of cell content area */ 7090 int iEnd = i+nCell; /* Loop terminator */ 7091 u8 *pCellptr = pPg->aCellIdx; 7092 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 7093 u8 *pData; 7094 int k; /* Current slot in pCArray->apEnd[] */ 7095 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */ 7096 7097 assert( i<iEnd ); 7098 j = get2byte(&aData[hdr+5]); 7099 if( NEVER(j>(u32)usableSize) ){ j = 0; } 7100 memcpy(&pTmp[j], &aData[j], usableSize - j); 7101 7102 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} 7103 pSrcEnd = pCArray->apEnd[k]; 7104 7105 pData = pEnd; 7106 while( 1/*exit by break*/ ){ 7107 u8 *pCell = pCArray->apCell[i]; 7108 u16 sz = pCArray->szCell[i]; 7109 assert( sz>0 ); 7110 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){ 7111 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT; 7112 pCell = &pTmp[pCell - aData]; 7113 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd 7114 && (uptr)(pCell)<(uptr)pSrcEnd 7115 ){ 7116 return SQLITE_CORRUPT_BKPT; 7117 } 7118 7119 pData -= sz; 7120 put2byte(pCellptr, (pData - aData)); 7121 pCellptr += 2; 7122 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; 7123 memmove(pData, pCell, sz); 7124 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); 7125 i++; 7126 if( i>=iEnd ) break; 7127 if( pCArray->ixNx[k]<=i ){ 7128 k++; 7129 pSrcEnd = pCArray->apEnd[k]; 7130 } 7131 } 7132 7133 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ 7134 pPg->nCell = nCell; 7135 pPg->nOverflow = 0; 7136 7137 put2byte(&aData[hdr+1], 0); 7138 put2byte(&aData[hdr+3], pPg->nCell); 7139 put2byte(&aData[hdr+5], pData - aData); 7140 aData[hdr+7] = 0x00; 7141 return SQLITE_OK; 7142 } 7143 7144 /* 7145 ** The pCArray objects contains pointers to b-tree cells and the cell sizes. 7146 ** This function attempts to add the cells stored in the array to page pPg. 7147 ** If it cannot (because the page needs to be defragmented before the cells 7148 ** will fit), non-zero is returned. Otherwise, if the cells are added 7149 ** successfully, zero is returned. 7150 ** 7151 ** Argument pCellptr points to the first entry in the cell-pointer array 7152 ** (part of page pPg) to populate. After cell apCell[0] is written to the 7153 ** page body, a 16-bit offset is written to pCellptr. And so on, for each 7154 ** cell in the array. It is the responsibility of the caller to ensure 7155 ** that it is safe to overwrite this part of the cell-pointer array. 7156 ** 7157 ** When this function is called, *ppData points to the start of the 7158 ** content area on page pPg. If the size of the content area is extended, 7159 ** *ppData is updated to point to the new start of the content area 7160 ** before returning. 7161 ** 7162 ** Finally, argument pBegin points to the byte immediately following the 7163 ** end of the space required by this page for the cell-pointer area (for 7164 ** all cells - not just those inserted by the current call). If the content 7165 ** area must be extended to before this point in order to accomodate all 7166 ** cells in apCell[], then the cells do not fit and non-zero is returned. 7167 */ 7168 static int pageInsertArray( 7169 MemPage *pPg, /* Page to add cells to */ 7170 u8 *pBegin, /* End of cell-pointer array */ 7171 u8 **ppData, /* IN/OUT: Page content-area pointer */ 7172 u8 *pCellptr, /* Pointer to cell-pointer area */ 7173 int iFirst, /* Index of first cell to add */ 7174 int nCell, /* Number of cells to add to pPg */ 7175 CellArray *pCArray /* Array of cells */ 7176 ){ 7177 int i = iFirst; /* Loop counter - cell index to insert */ 7178 u8 *aData = pPg->aData; /* Complete page */ 7179 u8 *pData = *ppData; /* Content area. A subset of aData[] */ 7180 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */ 7181 int k; /* Current slot in pCArray->apEnd[] */ 7182 u8 *pEnd; /* Maximum extent of cell data */ 7183 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ 7184 if( iEnd<=iFirst ) return 0; 7185 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} 7186 pEnd = pCArray->apEnd[k]; 7187 while( 1 /*Exit by break*/ ){ 7188 int sz, rc; 7189 u8 *pSlot; 7190 assert( pCArray->szCell[i]!=0 ); 7191 sz = pCArray->szCell[i]; 7192 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ 7193 if( (pData - pBegin)<sz ) return 1; 7194 pData -= sz; 7195 pSlot = pData; 7196 } 7197 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed 7198 ** database. But they might for a corrupt database. Hence use memmove() 7199 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ 7200 assert( (pSlot+sz)<=pCArray->apCell[i] 7201 || pSlot>=(pCArray->apCell[i]+sz) 7202 || CORRUPT_DB ); 7203 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd 7204 && (uptr)(pCArray->apCell[i])<(uptr)pEnd 7205 ){ 7206 assert( CORRUPT_DB ); 7207 (void)SQLITE_CORRUPT_BKPT; 7208 return 1; 7209 } 7210 memmove(pSlot, pCArray->apCell[i], sz); 7211 put2byte(pCellptr, (pSlot - aData)); 7212 pCellptr += 2; 7213 i++; 7214 if( i>=iEnd ) break; 7215 if( pCArray->ixNx[k]<=i ){ 7216 k++; 7217 pEnd = pCArray->apEnd[k]; 7218 } 7219 } 7220 *ppData = pData; 7221 return 0; 7222 } 7223 7224 /* 7225 ** The pCArray object contains pointers to b-tree cells and their sizes. 7226 ** 7227 ** This function adds the space associated with each cell in the array 7228 ** that is currently stored within the body of pPg to the pPg free-list. 7229 ** The cell-pointers and other fields of the page are not updated. 7230 ** 7231 ** This function returns the total number of cells added to the free-list. 7232 */ 7233 static int pageFreeArray( 7234 MemPage *pPg, /* Page to edit */ 7235 int iFirst, /* First cell to delete */ 7236 int nCell, /* Cells to delete */ 7237 CellArray *pCArray /* Array of cells */ 7238 ){ 7239 u8 * const aData = pPg->aData; 7240 u8 * const pEnd = &aData[pPg->pBt->usableSize]; 7241 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; 7242 int nRet = 0; 7243 int i; 7244 int iEnd = iFirst + nCell; 7245 u8 *pFree = 0; 7246 int szFree = 0; 7247 7248 for(i=iFirst; i<iEnd; i++){ 7249 u8 *pCell = pCArray->apCell[i]; 7250 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){ 7251 int sz; 7252 /* No need to use cachedCellSize() here. The sizes of all cells that 7253 ** are to be freed have already been computing while deciding which 7254 ** cells need freeing */ 7255 sz = pCArray->szCell[i]; assert( sz>0 ); 7256 if( pFree!=(pCell + sz) ){ 7257 if( pFree ){ 7258 assert( pFree>aData && (pFree - aData)<65536 ); 7259 freeSpace(pPg, (u16)(pFree - aData), szFree); 7260 } 7261 pFree = pCell; 7262 szFree = sz; 7263 if( pFree+sz>pEnd ){ 7264 return 0; 7265 } 7266 }else{ 7267 pFree = pCell; 7268 szFree += sz; 7269 } 7270 nRet++; 7271 } 7272 } 7273 if( pFree ){ 7274 assert( pFree>aData && (pFree - aData)<65536 ); 7275 freeSpace(pPg, (u16)(pFree - aData), szFree); 7276 } 7277 return nRet; 7278 } 7279 7280 /* 7281 ** pCArray contains pointers to and sizes of all cells in the page being 7282 ** balanced. The current page, pPg, has pPg->nCell cells starting with 7283 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells 7284 ** starting at apCell[iNew]. 7285 ** 7286 ** This routine makes the necessary adjustments to pPg so that it contains 7287 ** the correct cells after being balanced. 7288 ** 7289 ** The pPg->nFree field is invalid when this function returns. It is the 7290 ** responsibility of the caller to set it correctly. 7291 */ 7292 static int editPage( 7293 MemPage *pPg, /* Edit this page */ 7294 int iOld, /* Index of first cell currently on page */ 7295 int iNew, /* Index of new first cell on page */ 7296 int nNew, /* Final number of cells on page */ 7297 CellArray *pCArray /* Array of cells and sizes */ 7298 ){ 7299 u8 * const aData = pPg->aData; 7300 const int hdr = pPg->hdrOffset; 7301 u8 *pBegin = &pPg->aCellIdx[nNew * 2]; 7302 int nCell = pPg->nCell; /* Cells stored on pPg */ 7303 u8 *pData; 7304 u8 *pCellptr; 7305 int i; 7306 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; 7307 int iNewEnd = iNew + nNew; 7308 7309 #ifdef SQLITE_DEBUG 7310 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 7311 memcpy(pTmp, aData, pPg->pBt->usableSize); 7312 #endif 7313 7314 /* Remove cells from the start and end of the page */ 7315 assert( nCell>=0 ); 7316 if( iOld<iNew ){ 7317 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); 7318 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT; 7319 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); 7320 nCell -= nShift; 7321 } 7322 if( iNewEnd < iOldEnd ){ 7323 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); 7324 assert( nCell>=nTail ); 7325 nCell -= nTail; 7326 } 7327 7328 pData = &aData[get2byteNotZero(&aData[hdr+5])]; 7329 if( pData<pBegin ) goto editpage_fail; 7330 7331 /* Add cells to the start of the page */ 7332 if( iNew<iOld ){ 7333 int nAdd = MIN(nNew,iOld-iNew); 7334 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB ); 7335 assert( nAdd>=0 ); 7336 pCellptr = pPg->aCellIdx; 7337 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); 7338 if( pageInsertArray( 7339 pPg, pBegin, &pData, pCellptr, 7340 iNew, nAdd, pCArray 7341 ) ) goto editpage_fail; 7342 nCell += nAdd; 7343 } 7344 7345 /* Add any overflow cells */ 7346 for(i=0; i<pPg->nOverflow; i++){ 7347 int iCell = (iOld + pPg->aiOvfl[i]) - iNew; 7348 if( iCell>=0 && iCell<nNew ){ 7349 pCellptr = &pPg->aCellIdx[iCell * 2]; 7350 if( nCell>iCell ){ 7351 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); 7352 } 7353 nCell++; 7354 cachedCellSize(pCArray, iCell+iNew); 7355 if( pageInsertArray( 7356 pPg, pBegin, &pData, pCellptr, 7357 iCell+iNew, 1, pCArray 7358 ) ) goto editpage_fail; 7359 } 7360 } 7361 7362 /* Append cells to the end of the page */ 7363 assert( nCell>=0 ); 7364 pCellptr = &pPg->aCellIdx[nCell*2]; 7365 if( pageInsertArray( 7366 pPg, pBegin, &pData, pCellptr, 7367 iNew+nCell, nNew-nCell, pCArray 7368 ) ) goto editpage_fail; 7369 7370 pPg->nCell = nNew; 7371 pPg->nOverflow = 0; 7372 7373 put2byte(&aData[hdr+3], pPg->nCell); 7374 put2byte(&aData[hdr+5], pData - aData); 7375 7376 #ifdef SQLITE_DEBUG 7377 for(i=0; i<nNew && !CORRUPT_DB; i++){ 7378 u8 *pCell = pCArray->apCell[i+iNew]; 7379 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); 7380 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){ 7381 pCell = &pTmp[pCell - aData]; 7382 } 7383 assert( 0==memcmp(pCell, &aData[iOff], 7384 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); 7385 } 7386 #endif 7387 7388 return SQLITE_OK; 7389 editpage_fail: 7390 /* Unable to edit this page. Rebuild it from scratch instead. */ 7391 populateCellCache(pCArray, iNew, nNew); 7392 return rebuildPage(pCArray, iNew, nNew, pPg); 7393 } 7394 7395 7396 #ifndef SQLITE_OMIT_QUICKBALANCE 7397 /* 7398 ** This version of balance() handles the common special case where 7399 ** a new entry is being inserted on the extreme right-end of the 7400 ** tree, in other words, when the new entry will become the largest 7401 ** entry in the tree. 7402 ** 7403 ** Instead of trying to balance the 3 right-most leaf pages, just add 7404 ** a new page to the right-hand side and put the one new entry in 7405 ** that page. This leaves the right side of the tree somewhat 7406 ** unbalanced. But odds are that we will be inserting new entries 7407 ** at the end soon afterwards so the nearly empty page will quickly 7408 ** fill up. On average. 7409 ** 7410 ** pPage is the leaf page which is the right-most page in the tree. 7411 ** pParent is its parent. pPage must have a single overflow entry 7412 ** which is also the right-most entry on the page. 7413 ** 7414 ** The pSpace buffer is used to store a temporary copy of the divider 7415 ** cell that will be inserted into pParent. Such a cell consists of a 4 7416 ** byte page number followed by a variable length integer. In other 7417 ** words, at most 13 bytes. Hence the pSpace buffer must be at 7418 ** least 13 bytes in size. 7419 */ 7420 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ 7421 BtShared *const pBt = pPage->pBt; /* B-Tree Database */ 7422 MemPage *pNew; /* Newly allocated page */ 7423 int rc; /* Return Code */ 7424 Pgno pgnoNew; /* Page number of pNew */ 7425 7426 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 7427 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7428 assert( pPage->nOverflow==1 ); 7429 7430 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */ 7431 assert( pPage->nFree>=0 ); 7432 assert( pParent->nFree>=0 ); 7433 7434 /* Allocate a new page. This page will become the right-sibling of 7435 ** pPage. Make the parent page writable, so that the new divider cell 7436 ** may be inserted. If both these operations are successful, proceed. 7437 */ 7438 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); 7439 7440 if( rc==SQLITE_OK ){ 7441 7442 u8 *pOut = &pSpace[4]; 7443 u8 *pCell = pPage->apOvfl[0]; 7444 u16 szCell = pPage->xCellSize(pPage, pCell); 7445 u8 *pStop; 7446 CellArray b; 7447 7448 assert( sqlite3PagerIswriteable(pNew->pDbPage) ); 7449 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); 7450 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); 7451 b.nCell = 1; 7452 b.pRef = pPage; 7453 b.apCell = &pCell; 7454 b.szCell = &szCell; 7455 b.apEnd[0] = pPage->aDataEnd; 7456 b.ixNx[0] = 2; 7457 rc = rebuildPage(&b, 0, 1, pNew); 7458 if( NEVER(rc) ){ 7459 releasePage(pNew); 7460 return rc; 7461 } 7462 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; 7463 7464 /* If this is an auto-vacuum database, update the pointer map 7465 ** with entries for the new page, and any pointer from the 7466 ** cell on the page to an overflow page. If either of these 7467 ** operations fails, the return code is set, but the contents 7468 ** of the parent page are still manipulated by thh code below. 7469 ** That is Ok, at this point the parent page is guaranteed to 7470 ** be marked as dirty. Returning an error code will cause a 7471 ** rollback, undoing any changes made to the parent page. 7472 */ 7473 if( ISAUTOVACUUM ){ 7474 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); 7475 if( szCell>pNew->minLocal ){ 7476 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc); 7477 } 7478 } 7479 7480 /* Create a divider cell to insert into pParent. The divider cell 7481 ** consists of a 4-byte page number (the page number of pPage) and 7482 ** a variable length key value (which must be the same value as the 7483 ** largest key on pPage). 7484 ** 7485 ** To find the largest key value on pPage, first find the right-most 7486 ** cell on pPage. The first two fields of this cell are the 7487 ** record-length (a variable length integer at most 32-bits in size) 7488 ** and the key value (a variable length integer, may have any value). 7489 ** The first of the while(...) loops below skips over the record-length 7490 ** field. The second while(...) loop copies the key value from the 7491 ** cell on pPage into the pSpace buffer. 7492 */ 7493 pCell = findCell(pPage, pPage->nCell-1); 7494 pStop = &pCell[9]; 7495 while( (*(pCell++)&0x80) && pCell<pStop ); 7496 pStop = &pCell[9]; 7497 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop ); 7498 7499 /* Insert the new divider cell into pParent. */ 7500 if( rc==SQLITE_OK ){ 7501 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace), 7502 0, pPage->pgno, &rc); 7503 } 7504 7505 /* Set the right-child pointer of pParent to point to the new page. */ 7506 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); 7507 7508 /* Release the reference to the new page. */ 7509 releasePage(pNew); 7510 } 7511 7512 return rc; 7513 } 7514 #endif /* SQLITE_OMIT_QUICKBALANCE */ 7515 7516 #if 0 7517 /* 7518 ** This function does not contribute anything to the operation of SQLite. 7519 ** it is sometimes activated temporarily while debugging code responsible 7520 ** for setting pointer-map entries. 7521 */ 7522 static int ptrmapCheckPages(MemPage **apPage, int nPage){ 7523 int i, j; 7524 for(i=0; i<nPage; i++){ 7525 Pgno n; 7526 u8 e; 7527 MemPage *pPage = apPage[i]; 7528 BtShared *pBt = pPage->pBt; 7529 assert( pPage->isInit ); 7530 7531 for(j=0; j<pPage->nCell; j++){ 7532 CellInfo info; 7533 u8 *z; 7534 7535 z = findCell(pPage, j); 7536 pPage->xParseCell(pPage, z, &info); 7537 if( info.nLocal<info.nPayload ){ 7538 Pgno ovfl = get4byte(&z[info.nSize-4]); 7539 ptrmapGet(pBt, ovfl, &e, &n); 7540 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); 7541 } 7542 if( !pPage->leaf ){ 7543 Pgno child = get4byte(z); 7544 ptrmapGet(pBt, child, &e, &n); 7545 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 7546 } 7547 } 7548 if( !pPage->leaf ){ 7549 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); 7550 ptrmapGet(pBt, child, &e, &n); 7551 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 7552 } 7553 } 7554 return 1; 7555 } 7556 #endif 7557 7558 /* 7559 ** This function is used to copy the contents of the b-tree node stored 7560 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then 7561 ** the pointer-map entries for each child page are updated so that the 7562 ** parent page stored in the pointer map is page pTo. If pFrom contained 7563 ** any cells with overflow page pointers, then the corresponding pointer 7564 ** map entries are also updated so that the parent page is page pTo. 7565 ** 7566 ** If pFrom is currently carrying any overflow cells (entries in the 7567 ** MemPage.apOvfl[] array), they are not copied to pTo. 7568 ** 7569 ** Before returning, page pTo is reinitialized using btreeInitPage(). 7570 ** 7571 ** The performance of this function is not critical. It is only used by 7572 ** the balance_shallower() and balance_deeper() procedures, neither of 7573 ** which are called often under normal circumstances. 7574 */ 7575 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ 7576 if( (*pRC)==SQLITE_OK ){ 7577 BtShared * const pBt = pFrom->pBt; 7578 u8 * const aFrom = pFrom->aData; 7579 u8 * const aTo = pTo->aData; 7580 int const iFromHdr = pFrom->hdrOffset; 7581 int const iToHdr = ((pTo->pgno==1) ? 100 : 0); 7582 int rc; 7583 int iData; 7584 7585 7586 assert( pFrom->isInit ); 7587 assert( pFrom->nFree>=iToHdr ); 7588 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); 7589 7590 /* Copy the b-tree node content from page pFrom to page pTo. */ 7591 iData = get2byte(&aFrom[iFromHdr+5]); 7592 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); 7593 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); 7594 7595 /* Reinitialize page pTo so that the contents of the MemPage structure 7596 ** match the new data. The initialization of pTo can actually fail under 7597 ** fairly obscure circumstances, even though it is a copy of initialized 7598 ** page pFrom. 7599 */ 7600 pTo->isInit = 0; 7601 rc = btreeInitPage(pTo); 7602 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo); 7603 if( rc!=SQLITE_OK ){ 7604 *pRC = rc; 7605 return; 7606 } 7607 7608 /* If this is an auto-vacuum database, update the pointer-map entries 7609 ** for any b-tree or overflow pages that pTo now contains the pointers to. 7610 */ 7611 if( ISAUTOVACUUM ){ 7612 *pRC = setChildPtrmaps(pTo); 7613 } 7614 } 7615 } 7616 7617 /* 7618 ** This routine redistributes cells on the iParentIdx'th child of pParent 7619 ** (hereafter "the page") and up to 2 siblings so that all pages have about the 7620 ** same amount of free space. Usually a single sibling on either side of the 7621 ** page are used in the balancing, though both siblings might come from one 7622 ** side if the page is the first or last child of its parent. If the page 7623 ** has fewer than 2 siblings (something which can only happen if the page 7624 ** is a root page or a child of a root page) then all available siblings 7625 ** participate in the balancing. 7626 ** 7627 ** The number of siblings of the page might be increased or decreased by 7628 ** one or two in an effort to keep pages nearly full but not over full. 7629 ** 7630 ** Note that when this routine is called, some of the cells on the page 7631 ** might not actually be stored in MemPage.aData[]. This can happen 7632 ** if the page is overfull. This routine ensures that all cells allocated 7633 ** to the page and its siblings fit into MemPage.aData[] before returning. 7634 ** 7635 ** In the course of balancing the page and its siblings, cells may be 7636 ** inserted into or removed from the parent page (pParent). Doing so 7637 ** may cause the parent page to become overfull or underfull. If this 7638 ** happens, it is the responsibility of the caller to invoke the correct 7639 ** balancing routine to fix this problem (see the balance() routine). 7640 ** 7641 ** If this routine fails for any reason, it might leave the database 7642 ** in a corrupted state. So if this routine fails, the database should 7643 ** be rolled back. 7644 ** 7645 ** The third argument to this function, aOvflSpace, is a pointer to a 7646 ** buffer big enough to hold one page. If while inserting cells into the parent 7647 ** page (pParent) the parent page becomes overfull, this buffer is 7648 ** used to store the parent's overflow cells. Because this function inserts 7649 ** a maximum of four divider cells into the parent page, and the maximum 7650 ** size of a cell stored within an internal node is always less than 1/4 7651 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large 7652 ** enough for all overflow cells. 7653 ** 7654 ** If aOvflSpace is set to a null pointer, this function returns 7655 ** SQLITE_NOMEM. 7656 */ 7657 static int balance_nonroot( 7658 MemPage *pParent, /* Parent page of siblings being balanced */ 7659 int iParentIdx, /* Index of "the page" in pParent */ 7660 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ 7661 int isRoot, /* True if pParent is a root-page */ 7662 int bBulk /* True if this call is part of a bulk load */ 7663 ){ 7664 BtShared *pBt; /* The whole database */ 7665 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ 7666 int nNew = 0; /* Number of pages in apNew[] */ 7667 int nOld; /* Number of pages in apOld[] */ 7668 int i, j, k; /* Loop counters */ 7669 int nxDiv; /* Next divider slot in pParent->aCell[] */ 7670 int rc = SQLITE_OK; /* The return code */ 7671 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ 7672 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ 7673 int usableSpace; /* Bytes in pPage beyond the header */ 7674 int pageFlags; /* Value of pPage->aData[0] */ 7675 int iSpace1 = 0; /* First unused byte of aSpace1[] */ 7676 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ 7677 int szScratch; /* Size of scratch memory requested */ 7678 MemPage *apOld[NB]; /* pPage and up to two siblings */ 7679 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ 7680 u8 *pRight; /* Location in parent of right-sibling pointer */ 7681 u8 *apDiv[NB-1]; /* Divider cells in pParent */ 7682 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ 7683 int cntOld[NB+2]; /* Old index in b.apCell[] */ 7684 int szNew[NB+2]; /* Combined size of cells placed on i-th page */ 7685 u8 *aSpace1; /* Space for copies of dividers cells */ 7686 Pgno pgno; /* Temp var to store a page number in */ 7687 u8 abDone[NB+2]; /* True after i'th new page is populated */ 7688 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ 7689 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ 7690 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ 7691 CellArray b; /* Parsed information on cells being balanced */ 7692 7693 memset(abDone, 0, sizeof(abDone)); 7694 b.nCell = 0; 7695 b.apCell = 0; 7696 pBt = pParent->pBt; 7697 assert( sqlite3_mutex_held(pBt->mutex) ); 7698 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7699 7700 /* At this point pParent may have at most one overflow cell. And if 7701 ** this overflow cell is present, it must be the cell with 7702 ** index iParentIdx. This scenario comes about when this function 7703 ** is called (indirectly) from sqlite3BtreeDelete(). 7704 */ 7705 assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); 7706 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); 7707 7708 if( !aOvflSpace ){ 7709 return SQLITE_NOMEM_BKPT; 7710 } 7711 assert( pParent->nFree>=0 ); 7712 7713 /* Find the sibling pages to balance. Also locate the cells in pParent 7714 ** that divide the siblings. An attempt is made to find NN siblings on 7715 ** either side of pPage. More siblings are taken from one side, however, 7716 ** if there are fewer than NN siblings on the other side. If pParent 7717 ** has NB or fewer children then all children of pParent are taken. 7718 ** 7719 ** This loop also drops the divider cells from the parent page. This 7720 ** way, the remainder of the function does not have to deal with any 7721 ** overflow cells in the parent page, since if any existed they will 7722 ** have already been removed. 7723 */ 7724 i = pParent->nOverflow + pParent->nCell; 7725 if( i<2 ){ 7726 nxDiv = 0; 7727 }else{ 7728 assert( bBulk==0 || bBulk==1 ); 7729 if( iParentIdx==0 ){ 7730 nxDiv = 0; 7731 }else if( iParentIdx==i ){ 7732 nxDiv = i-2+bBulk; 7733 }else{ 7734 nxDiv = iParentIdx-1; 7735 } 7736 i = 2-bBulk; 7737 } 7738 nOld = i+1; 7739 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ 7740 pRight = &pParent->aData[pParent->hdrOffset+8]; 7741 }else{ 7742 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); 7743 } 7744 pgno = get4byte(pRight); 7745 while( 1 ){ 7746 if( rc==SQLITE_OK ){ 7747 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); 7748 } 7749 if( rc ){ 7750 memset(apOld, 0, (i+1)*sizeof(MemPage*)); 7751 goto balance_cleanup; 7752 } 7753 if( apOld[i]->nFree<0 ){ 7754 rc = btreeComputeFreeSpace(apOld[i]); 7755 if( rc ){ 7756 memset(apOld, 0, (i)*sizeof(MemPage*)); 7757 goto balance_cleanup; 7758 } 7759 } 7760 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl); 7761 if( (i--)==0 ) break; 7762 7763 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ 7764 apDiv[i] = pParent->apOvfl[0]; 7765 pgno = get4byte(apDiv[i]); 7766 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7767 pParent->nOverflow = 0; 7768 }else{ 7769 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); 7770 pgno = get4byte(apDiv[i]); 7771 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7772 7773 /* Drop the cell from the parent page. apDiv[i] still points to 7774 ** the cell within the parent, even though it has been dropped. 7775 ** This is safe because dropping a cell only overwrites the first 7776 ** four bytes of it, and this function does not need the first 7777 ** four bytes of the divider cell. So the pointer is safe to use 7778 ** later on. 7779 ** 7780 ** But not if we are in secure-delete mode. In secure-delete mode, 7781 ** the dropCell() routine will overwrite the entire cell with zeroes. 7782 ** In this case, temporarily copy the cell into the aOvflSpace[] 7783 ** buffer. It will be copied out again as soon as the aSpace[] buffer 7784 ** is allocated. */ 7785 if( pBt->btsFlags & BTS_FAST_SECURE ){ 7786 int iOff; 7787 7788 /* If the following if() condition is not true, the db is corrupted. 7789 ** The call to dropCell() below will detect this. */ 7790 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); 7791 if( (iOff+szNew[i])<=(int)pBt->usableSize ){ 7792 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); 7793 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; 7794 } 7795 } 7796 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); 7797 } 7798 } 7799 7800 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte 7801 ** alignment */ 7802 nMaxCells = (nMaxCells + 3)&~3; 7803 7804 /* 7805 ** Allocate space for memory structures 7806 */ 7807 szScratch = 7808 nMaxCells*sizeof(u8*) /* b.apCell */ 7809 + nMaxCells*sizeof(u16) /* b.szCell */ 7810 + pBt->pageSize; /* aSpace1 */ 7811 7812 assert( szScratch<=7*(int)pBt->pageSize ); 7813 b.apCell = sqlite3StackAllocRaw(0, szScratch ); 7814 if( b.apCell==0 ){ 7815 rc = SQLITE_NOMEM_BKPT; 7816 goto balance_cleanup; 7817 } 7818 b.szCell = (u16*)&b.apCell[nMaxCells]; 7819 aSpace1 = (u8*)&b.szCell[nMaxCells]; 7820 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); 7821 7822 /* 7823 ** Load pointers to all cells on sibling pages and the divider cells 7824 ** into the local b.apCell[] array. Make copies of the divider cells 7825 ** into space obtained from aSpace1[]. The divider cells have already 7826 ** been removed from pParent. 7827 ** 7828 ** If the siblings are on leaf pages, then the child pointers of the 7829 ** divider cells are stripped from the cells before they are copied 7830 ** into aSpace1[]. In this way, all cells in b.apCell[] are without 7831 ** child pointers. If siblings are not leaves, then all cell in 7832 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] 7833 ** are alike. 7834 ** 7835 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. 7836 ** leafData: 1 if pPage holds key+data and pParent holds only keys. 7837 */ 7838 b.pRef = apOld[0]; 7839 leafCorrection = b.pRef->leaf*4; 7840 leafData = b.pRef->intKeyLeaf; 7841 for(i=0; i<nOld; i++){ 7842 MemPage *pOld = apOld[i]; 7843 int limit = pOld->nCell; 7844 u8 *aData = pOld->aData; 7845 u16 maskPage = pOld->maskPage; 7846 u8 *piCell = aData + pOld->cellOffset; 7847 u8 *piEnd; 7848 VVA_ONLY( int nCellAtStart = b.nCell; ) 7849 7850 /* Verify that all sibling pages are of the same "type" (table-leaf, 7851 ** table-interior, index-leaf, or index-interior). 7852 */ 7853 if( pOld->aData[0]!=apOld[0]->aData[0] ){ 7854 rc = SQLITE_CORRUPT_BKPT; 7855 goto balance_cleanup; 7856 } 7857 7858 /* Load b.apCell[] with pointers to all cells in pOld. If pOld 7859 ** contains overflow cells, include them in the b.apCell[] array 7860 ** in the correct spot. 7861 ** 7862 ** Note that when there are multiple overflow cells, it is always the 7863 ** case that they are sequential and adjacent. This invariant arises 7864 ** because multiple overflows can only occurs when inserting divider 7865 ** cells into a parent on a prior balance, and divider cells are always 7866 ** adjacent and are inserted in order. There is an assert() tagged 7867 ** with "NOTE 1" in the overflow cell insertion loop to prove this 7868 ** invariant. 7869 ** 7870 ** This must be done in advance. Once the balance starts, the cell 7871 ** offset section of the btree page will be overwritten and we will no 7872 ** long be able to find the cells if a pointer to each cell is not saved 7873 ** first. 7874 */ 7875 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); 7876 if( pOld->nOverflow>0 ){ 7877 if( NEVER(limit<pOld->aiOvfl[0]) ){ 7878 rc = SQLITE_CORRUPT_BKPT; 7879 goto balance_cleanup; 7880 } 7881 limit = pOld->aiOvfl[0]; 7882 for(j=0; j<limit; j++){ 7883 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7884 piCell += 2; 7885 b.nCell++; 7886 } 7887 for(k=0; k<pOld->nOverflow; k++){ 7888 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ 7889 b.apCell[b.nCell] = pOld->apOvfl[k]; 7890 b.nCell++; 7891 } 7892 } 7893 piEnd = aData + pOld->cellOffset + 2*pOld->nCell; 7894 while( piCell<piEnd ){ 7895 assert( b.nCell<nMaxCells ); 7896 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7897 piCell += 2; 7898 b.nCell++; 7899 } 7900 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) ); 7901 7902 cntOld[i] = b.nCell; 7903 if( i<nOld-1 && !leafData){ 7904 u16 sz = (u16)szNew[i]; 7905 u8 *pTemp; 7906 assert( b.nCell<nMaxCells ); 7907 b.szCell[b.nCell] = sz; 7908 pTemp = &aSpace1[iSpace1]; 7909 iSpace1 += sz; 7910 assert( sz<=pBt->maxLocal+23 ); 7911 assert( iSpace1 <= (int)pBt->pageSize ); 7912 memcpy(pTemp, apDiv[i], sz); 7913 b.apCell[b.nCell] = pTemp+leafCorrection; 7914 assert( leafCorrection==0 || leafCorrection==4 ); 7915 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; 7916 if( !pOld->leaf ){ 7917 assert( leafCorrection==0 ); 7918 assert( pOld->hdrOffset==0 || CORRUPT_DB ); 7919 /* The right pointer of the child page pOld becomes the left 7920 ** pointer of the divider cell */ 7921 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); 7922 }else{ 7923 assert( leafCorrection==4 ); 7924 while( b.szCell[b.nCell]<4 ){ 7925 /* Do not allow any cells smaller than 4 bytes. If a smaller cell 7926 ** does exist, pad it with 0x00 bytes. */ 7927 assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); 7928 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); 7929 aSpace1[iSpace1++] = 0x00; 7930 b.szCell[b.nCell]++; 7931 } 7932 } 7933 b.nCell++; 7934 } 7935 } 7936 7937 /* 7938 ** Figure out the number of pages needed to hold all b.nCell cells. 7939 ** Store this number in "k". Also compute szNew[] which is the total 7940 ** size of all cells on the i-th page and cntNew[] which is the index 7941 ** in b.apCell[] of the cell that divides page i from page i+1. 7942 ** cntNew[k] should equal b.nCell. 7943 ** 7944 ** Values computed by this block: 7945 ** 7946 ** k: The total number of sibling pages 7947 ** szNew[i]: Spaced used on the i-th sibling page. 7948 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to 7949 ** the right of the i-th sibling page. 7950 ** usableSpace: Number of bytes of space available on each sibling. 7951 ** 7952 */ 7953 usableSpace = pBt->usableSize - 12 + leafCorrection; 7954 for(i=k=0; i<nOld; i++, k++){ 7955 MemPage *p = apOld[i]; 7956 b.apEnd[k] = p->aDataEnd; 7957 b.ixNx[k] = cntOld[i]; 7958 if( k && b.ixNx[k]==b.ixNx[k-1] ){ 7959 k--; /* Omit b.ixNx[] entry for child pages with no cells */ 7960 } 7961 if( !leafData ){ 7962 k++; 7963 b.apEnd[k] = pParent->aDataEnd; 7964 b.ixNx[k] = cntOld[i]+1; 7965 } 7966 assert( p->nFree>=0 ); 7967 szNew[i] = usableSpace - p->nFree; 7968 for(j=0; j<p->nOverflow; j++){ 7969 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); 7970 } 7971 cntNew[i] = cntOld[i]; 7972 } 7973 k = nOld; 7974 for(i=0; i<k; i++){ 7975 int sz; 7976 while( szNew[i]>usableSpace ){ 7977 if( i+1>=k ){ 7978 k = i+2; 7979 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } 7980 szNew[k-1] = 0; 7981 cntNew[k-1] = b.nCell; 7982 } 7983 sz = 2 + cachedCellSize(&b, cntNew[i]-1); 7984 szNew[i] -= sz; 7985 if( !leafData ){ 7986 if( cntNew[i]<b.nCell ){ 7987 sz = 2 + cachedCellSize(&b, cntNew[i]); 7988 }else{ 7989 sz = 0; 7990 } 7991 } 7992 szNew[i+1] += sz; 7993 cntNew[i]--; 7994 } 7995 while( cntNew[i]<b.nCell ){ 7996 sz = 2 + cachedCellSize(&b, cntNew[i]); 7997 if( szNew[i]+sz>usableSpace ) break; 7998 szNew[i] += sz; 7999 cntNew[i]++; 8000 if( !leafData ){ 8001 if( cntNew[i]<b.nCell ){ 8002 sz = 2 + cachedCellSize(&b, cntNew[i]); 8003 }else{ 8004 sz = 0; 8005 } 8006 } 8007 szNew[i+1] -= sz; 8008 } 8009 if( cntNew[i]>=b.nCell ){ 8010 k = i+1; 8011 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ 8012 rc = SQLITE_CORRUPT_BKPT; 8013 goto balance_cleanup; 8014 } 8015 } 8016 8017 /* 8018 ** The packing computed by the previous block is biased toward the siblings 8019 ** on the left side (siblings with smaller keys). The left siblings are 8020 ** always nearly full, while the right-most sibling might be nearly empty. 8021 ** The next block of code attempts to adjust the packing of siblings to 8022 ** get a better balance. 8023 ** 8024 ** This adjustment is more than an optimization. The packing above might 8025 ** be so out of balance as to be illegal. For example, the right-most 8026 ** sibling might be completely empty. This adjustment is not optional. 8027 */ 8028 for(i=k-1; i>0; i--){ 8029 int szRight = szNew[i]; /* Size of sibling on the right */ 8030 int szLeft = szNew[i-1]; /* Size of sibling on the left */ 8031 int r; /* Index of right-most cell in left sibling */ 8032 int d; /* Index of first cell to the left of right sibling */ 8033 8034 r = cntNew[i-1] - 1; 8035 d = r + 1 - leafData; 8036 (void)cachedCellSize(&b, d); 8037 do{ 8038 assert( d<nMaxCells ); 8039 assert( r<nMaxCells ); 8040 (void)cachedCellSize(&b, r); 8041 if( szRight!=0 8042 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){ 8043 break; 8044 } 8045 szRight += b.szCell[d] + 2; 8046 szLeft -= b.szCell[r] + 2; 8047 cntNew[i-1] = r; 8048 r--; 8049 d--; 8050 }while( r>=0 ); 8051 szNew[i] = szRight; 8052 szNew[i-1] = szLeft; 8053 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ 8054 rc = SQLITE_CORRUPT_BKPT; 8055 goto balance_cleanup; 8056 } 8057 } 8058 8059 /* Sanity check: For a non-corrupt database file one of the follwing 8060 ** must be true: 8061 ** (1) We found one or more cells (cntNew[0])>0), or 8062 ** (2) pPage is a virtual root page. A virtual root page is when 8063 ** the real root page is page 1 and we are the only child of 8064 ** that page. 8065 */ 8066 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); 8067 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", 8068 apOld[0]->pgno, apOld[0]->nCell, 8069 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, 8070 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 8071 )); 8072 8073 /* 8074 ** Allocate k new pages. Reuse old pages where possible. 8075 */ 8076 pageFlags = apOld[0]->aData[0]; 8077 for(i=0; i<k; i++){ 8078 MemPage *pNew; 8079 if( i<nOld ){ 8080 pNew = apNew[i] = apOld[i]; 8081 apOld[i] = 0; 8082 rc = sqlite3PagerWrite(pNew->pDbPage); 8083 nNew++; 8084 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) 8085 && rc==SQLITE_OK 8086 ){ 8087 rc = SQLITE_CORRUPT_BKPT; 8088 } 8089 if( rc ) goto balance_cleanup; 8090 }else{ 8091 assert( i>0 ); 8092 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); 8093 if( rc ) goto balance_cleanup; 8094 zeroPage(pNew, pageFlags); 8095 apNew[i] = pNew; 8096 nNew++; 8097 cntOld[i] = b.nCell; 8098 8099 /* Set the pointer-map entry for the new sibling page. */ 8100 if( ISAUTOVACUUM ){ 8101 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); 8102 if( rc!=SQLITE_OK ){ 8103 goto balance_cleanup; 8104 } 8105 } 8106 } 8107 } 8108 8109 /* 8110 ** Reassign page numbers so that the new pages are in ascending order. 8111 ** This helps to keep entries in the disk file in order so that a scan 8112 ** of the table is closer to a linear scan through the file. That in turn 8113 ** helps the operating system to deliver pages from the disk more rapidly. 8114 ** 8115 ** An O(n^2) insertion sort algorithm is used, but since n is never more 8116 ** than (NB+2) (a small constant), that should not be a problem. 8117 ** 8118 ** When NB==3, this one optimization makes the database about 25% faster 8119 ** for large insertions and deletions. 8120 */ 8121 for(i=0; i<nNew; i++){ 8122 aPgOrder[i] = aPgno[i] = apNew[i]->pgno; 8123 aPgFlags[i] = apNew[i]->pDbPage->flags; 8124 for(j=0; j<i; j++){ 8125 if( NEVER(aPgno[j]==aPgno[i]) ){ 8126 /* This branch is taken if the set of sibling pages somehow contains 8127 ** duplicate entries. This can happen if the database is corrupt. 8128 ** It would be simpler to detect this as part of the loop below, but 8129 ** we do the detection here in order to avoid populating the pager 8130 ** cache with two separate objects associated with the same 8131 ** page number. */ 8132 assert( CORRUPT_DB ); 8133 rc = SQLITE_CORRUPT_BKPT; 8134 goto balance_cleanup; 8135 } 8136 } 8137 } 8138 for(i=0; i<nNew; i++){ 8139 int iBest = 0; /* aPgno[] index of page number to use */ 8140 for(j=1; j<nNew; j++){ 8141 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j; 8142 } 8143 pgno = aPgOrder[iBest]; 8144 aPgOrder[iBest] = 0xffffffff; 8145 if( iBest!=i ){ 8146 if( iBest>i ){ 8147 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); 8148 } 8149 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); 8150 apNew[i]->pgno = pgno; 8151 } 8152 } 8153 8154 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " 8155 "%d(%d nc=%d) %d(%d nc=%d)\n", 8156 apNew[0]->pgno, szNew[0], cntNew[0], 8157 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, 8158 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, 8159 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, 8160 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, 8161 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, 8162 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, 8163 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, 8164 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 8165 )); 8166 8167 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 8168 assert( nNew>=1 && nNew<=ArraySize(apNew) ); 8169 assert( apNew[nNew-1]!=0 ); 8170 put4byte(pRight, apNew[nNew-1]->pgno); 8171 8172 /* If the sibling pages are not leaves, ensure that the right-child pointer 8173 ** of the right-most new sibling page is set to the value that was 8174 ** originally in the same field of the right-most old sibling page. */ 8175 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ 8176 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; 8177 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); 8178 } 8179 8180 /* Make any required updates to pointer map entries associated with 8181 ** cells stored on sibling pages following the balance operation. Pointer 8182 ** map entries associated with divider cells are set by the insertCell() 8183 ** routine. The associated pointer map entries are: 8184 ** 8185 ** a) if the cell contains a reference to an overflow chain, the 8186 ** entry associated with the first page in the overflow chain, and 8187 ** 8188 ** b) if the sibling pages are not leaves, the child page associated 8189 ** with the cell. 8190 ** 8191 ** If the sibling pages are not leaves, then the pointer map entry 8192 ** associated with the right-child of each sibling may also need to be 8193 ** updated. This happens below, after the sibling pages have been 8194 ** populated, not here. 8195 */ 8196 if( ISAUTOVACUUM ){ 8197 MemPage *pOld; 8198 MemPage *pNew = pOld = apNew[0]; 8199 int cntOldNext = pNew->nCell + pNew->nOverflow; 8200 int iNew = 0; 8201 int iOld = 0; 8202 8203 for(i=0; i<b.nCell; i++){ 8204 u8 *pCell = b.apCell[i]; 8205 while( i==cntOldNext ){ 8206 iOld++; 8207 assert( iOld<nNew || iOld<nOld ); 8208 assert( iOld>=0 && iOld<NB ); 8209 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld]; 8210 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; 8211 } 8212 if( i==cntNew[iNew] ){ 8213 pNew = apNew[++iNew]; 8214 if( !leafData ) continue; 8215 } 8216 8217 /* Cell pCell is destined for new sibling page pNew. Originally, it 8218 ** was either part of sibling page iOld (possibly an overflow cell), 8219 ** or else the divider cell to the left of sibling page iOld. So, 8220 ** if sibling page iOld had the same page number as pNew, and if 8221 ** pCell really was a part of sibling page iOld (not a divider or 8222 ** overflow cell), we can skip updating the pointer map entries. */ 8223 if( iOld>=nNew 8224 || pNew->pgno!=aPgno[iOld] 8225 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd) 8226 ){ 8227 if( !leafCorrection ){ 8228 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); 8229 } 8230 if( cachedCellSize(&b,i)>pNew->minLocal ){ 8231 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc); 8232 } 8233 if( rc ) goto balance_cleanup; 8234 } 8235 } 8236 } 8237 8238 /* Insert new divider cells into pParent. */ 8239 for(i=0; i<nNew-1; i++){ 8240 u8 *pCell; 8241 u8 *pTemp; 8242 int sz; 8243 u8 *pSrcEnd; 8244 MemPage *pNew = apNew[i]; 8245 j = cntNew[i]; 8246 8247 assert( j<nMaxCells ); 8248 assert( b.apCell[j]!=0 ); 8249 pCell = b.apCell[j]; 8250 sz = b.szCell[j] + leafCorrection; 8251 pTemp = &aOvflSpace[iOvflSpace]; 8252 if( !pNew->leaf ){ 8253 memcpy(&pNew->aData[8], pCell, 4); 8254 }else if( leafData ){ 8255 /* If the tree is a leaf-data tree, and the siblings are leaves, 8256 ** then there is no divider cell in b.apCell[]. Instead, the divider 8257 ** cell consists of the integer key for the right-most cell of 8258 ** the sibling-page assembled above only. 8259 */ 8260 CellInfo info; 8261 j--; 8262 pNew->xParseCell(pNew, b.apCell[j], &info); 8263 pCell = pTemp; 8264 sz = 4 + putVarint(&pCell[4], info.nKey); 8265 pTemp = 0; 8266 }else{ 8267 pCell -= 4; 8268 /* Obscure case for non-leaf-data trees: If the cell at pCell was 8269 ** previously stored on a leaf node, and its reported size was 4 8270 ** bytes, then it may actually be smaller than this 8271 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of 8272 ** any cell). But it is important to pass the correct size to 8273 ** insertCell(), so reparse the cell now. 8274 ** 8275 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" 8276 ** and WITHOUT ROWID tables with exactly one column which is the 8277 ** primary key. 8278 */ 8279 if( b.szCell[j]==4 ){ 8280 assert(leafCorrection==4); 8281 sz = pParent->xCellSize(pParent, pCell); 8282 } 8283 } 8284 iOvflSpace += sz; 8285 assert( sz<=pBt->maxLocal+23 ); 8286 assert( iOvflSpace <= (int)pBt->pageSize ); 8287 for(k=0; b.ixNx[k]<=i && ALWAYS(k<NB*2); k++){} 8288 pSrcEnd = b.apEnd[k]; 8289 if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){ 8290 rc = SQLITE_CORRUPT_BKPT; 8291 goto balance_cleanup; 8292 } 8293 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); 8294 if( rc!=SQLITE_OK ) goto balance_cleanup; 8295 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 8296 } 8297 8298 /* Now update the actual sibling pages. The order in which they are updated 8299 ** is important, as this code needs to avoid disrupting any page from which 8300 ** cells may still to be read. In practice, this means: 8301 ** 8302 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) 8303 ** then it is not safe to update page apNew[iPg] until after 8304 ** the left-hand sibling apNew[iPg-1] has been updated. 8305 ** 8306 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) 8307 ** then it is not safe to update page apNew[iPg] until after 8308 ** the right-hand sibling apNew[iPg+1] has been updated. 8309 ** 8310 ** If neither of the above apply, the page is safe to update. 8311 ** 8312 ** The iPg value in the following loop starts at nNew-1 goes down 8313 ** to 0, then back up to nNew-1 again, thus making two passes over 8314 ** the pages. On the initial downward pass, only condition (1) above 8315 ** needs to be tested because (2) will always be true from the previous 8316 ** step. On the upward pass, both conditions are always true, so the 8317 ** upwards pass simply processes pages that were missed on the downward 8318 ** pass. 8319 */ 8320 for(i=1-nNew; i<nNew; i++){ 8321 int iPg = i<0 ? -i : i; 8322 assert( iPg>=0 && iPg<nNew ); 8323 if( abDone[iPg] ) continue; /* Skip pages already processed */ 8324 if( i>=0 /* On the upwards pass, or... */ 8325 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ 8326 ){ 8327 int iNew; 8328 int iOld; 8329 int nNewCell; 8330 8331 /* Verify condition (1): If cells are moving left, update iPg 8332 ** only after iPg-1 has already been updated. */ 8333 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); 8334 8335 /* Verify condition (2): If cells are moving right, update iPg 8336 ** only after iPg+1 has already been updated. */ 8337 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); 8338 8339 if( iPg==0 ){ 8340 iNew = iOld = 0; 8341 nNewCell = cntNew[0]; 8342 }else{ 8343 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell; 8344 iNew = cntNew[iPg-1] + !leafData; 8345 nNewCell = cntNew[iPg] - iNew; 8346 } 8347 8348 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b); 8349 if( rc ) goto balance_cleanup; 8350 abDone[iPg]++; 8351 apNew[iPg]->nFree = usableSpace-szNew[iPg]; 8352 assert( apNew[iPg]->nOverflow==0 ); 8353 assert( apNew[iPg]->nCell==nNewCell ); 8354 } 8355 } 8356 8357 /* All pages have been processed exactly once */ 8358 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); 8359 8360 assert( nOld>0 ); 8361 assert( nNew>0 ); 8362 8363 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ 8364 /* The root page of the b-tree now contains no cells. The only sibling 8365 ** page is the right-child of the parent. Copy the contents of the 8366 ** child page into the parent, decreasing the overall height of the 8367 ** b-tree structure by one. This is described as the "balance-shallower" 8368 ** sub-algorithm in some documentation. 8369 ** 8370 ** If this is an auto-vacuum database, the call to copyNodeContent() 8371 ** sets all pointer-map entries corresponding to database image pages 8372 ** for which the pointer is stored within the content being copied. 8373 ** 8374 ** It is critical that the child page be defragmented before being 8375 ** copied into the parent, because if the parent is page 1 then it will 8376 ** by smaller than the child due to the database header, and so all the 8377 ** free space needs to be up front. 8378 */ 8379 assert( nNew==1 || CORRUPT_DB ); 8380 rc = defragmentPage(apNew[0], -1); 8381 testcase( rc!=SQLITE_OK ); 8382 assert( apNew[0]->nFree == 8383 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset 8384 - apNew[0]->nCell*2) 8385 || rc!=SQLITE_OK 8386 ); 8387 copyNodeContent(apNew[0], pParent, &rc); 8388 freePage(apNew[0], &rc); 8389 }else if( ISAUTOVACUUM && !leafCorrection ){ 8390 /* Fix the pointer map entries associated with the right-child of each 8391 ** sibling page. All other pointer map entries have already been taken 8392 ** care of. */ 8393 for(i=0; i<nNew; i++){ 8394 u32 key = get4byte(&apNew[i]->aData[8]); 8395 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); 8396 } 8397 } 8398 8399 assert( pParent->isInit ); 8400 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", 8401 nOld, nNew, b.nCell)); 8402 8403 /* Free any old pages that were not reused as new pages. 8404 */ 8405 for(i=nNew; i<nOld; i++){ 8406 freePage(apOld[i], &rc); 8407 } 8408 8409 #if 0 8410 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){ 8411 /* The ptrmapCheckPages() contains assert() statements that verify that 8412 ** all pointer map pages are set correctly. This is helpful while 8413 ** debugging. This is usually disabled because a corrupt database may 8414 ** cause an assert() statement to fail. */ 8415 ptrmapCheckPages(apNew, nNew); 8416 ptrmapCheckPages(&pParent, 1); 8417 } 8418 #endif 8419 8420 /* 8421 ** Cleanup before returning. 8422 */ 8423 balance_cleanup: 8424 sqlite3StackFree(0, b.apCell); 8425 for(i=0; i<nOld; i++){ 8426 releasePage(apOld[i]); 8427 } 8428 for(i=0; i<nNew; i++){ 8429 releasePage(apNew[i]); 8430 } 8431 8432 return rc; 8433 } 8434 8435 8436 /* 8437 ** This function is called when the root page of a b-tree structure is 8438 ** overfull (has one or more overflow pages). 8439 ** 8440 ** A new child page is allocated and the contents of the current root 8441 ** page, including overflow cells, are copied into the child. The root 8442 ** page is then overwritten to make it an empty page with the right-child 8443 ** pointer pointing to the new page. 8444 ** 8445 ** Before returning, all pointer-map entries corresponding to pages 8446 ** that the new child-page now contains pointers to are updated. The 8447 ** entry corresponding to the new right-child pointer of the root 8448 ** page is also updated. 8449 ** 8450 ** If successful, *ppChild is set to contain a reference to the child 8451 ** page and SQLITE_OK is returned. In this case the caller is required 8452 ** to call releasePage() on *ppChild exactly once. If an error occurs, 8453 ** an error code is returned and *ppChild is set to 0. 8454 */ 8455 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ 8456 int rc; /* Return value from subprocedures */ 8457 MemPage *pChild = 0; /* Pointer to a new child page */ 8458 Pgno pgnoChild = 0; /* Page number of the new child page */ 8459 BtShared *pBt = pRoot->pBt; /* The BTree */ 8460 8461 assert( pRoot->nOverflow>0 ); 8462 assert( sqlite3_mutex_held(pBt->mutex) ); 8463 8464 /* Make pRoot, the root page of the b-tree, writable. Allocate a new 8465 ** page that will become the new right-child of pPage. Copy the contents 8466 ** of the node stored on pRoot into the new child page. 8467 */ 8468 rc = sqlite3PagerWrite(pRoot->pDbPage); 8469 if( rc==SQLITE_OK ){ 8470 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); 8471 copyNodeContent(pRoot, pChild, &rc); 8472 if( ISAUTOVACUUM ){ 8473 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); 8474 } 8475 } 8476 if( rc ){ 8477 *ppChild = 0; 8478 releasePage(pChild); 8479 return rc; 8480 } 8481 assert( sqlite3PagerIswriteable(pChild->pDbPage) ); 8482 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 8483 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB ); 8484 8485 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); 8486 8487 /* Copy the overflow cells from pRoot to pChild */ 8488 memcpy(pChild->aiOvfl, pRoot->aiOvfl, 8489 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); 8490 memcpy(pChild->apOvfl, pRoot->apOvfl, 8491 pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); 8492 pChild->nOverflow = pRoot->nOverflow; 8493 8494 /* Zero the contents of pRoot. Then install pChild as the right-child. */ 8495 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); 8496 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); 8497 8498 *ppChild = pChild; 8499 return SQLITE_OK; 8500 } 8501 8502 /* 8503 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid 8504 ** on the same B-tree as pCur. 8505 ** 8506 ** This can if a database is corrupt with two or more SQL tables 8507 ** pointing to the same b-tree. If an insert occurs on one SQL table 8508 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL 8509 ** table linked to the same b-tree. If the secondary insert causes a 8510 ** rebalance, that can change content out from under the cursor on the 8511 ** first SQL table, violating invariants on the first insert. 8512 */ 8513 static int anotherValidCursor(BtCursor *pCur){ 8514 BtCursor *pOther; 8515 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){ 8516 if( pOther!=pCur 8517 && pOther->eState==CURSOR_VALID 8518 && pOther->pPage==pCur->pPage 8519 ){ 8520 return SQLITE_CORRUPT_BKPT; 8521 } 8522 } 8523 return SQLITE_OK; 8524 } 8525 8526 /* 8527 ** The page that pCur currently points to has just been modified in 8528 ** some way. This function figures out if this modification means the 8529 ** tree needs to be balanced, and if so calls the appropriate balancing 8530 ** routine. Balancing routines are: 8531 ** 8532 ** balance_quick() 8533 ** balance_deeper() 8534 ** balance_nonroot() 8535 */ 8536 static int balance(BtCursor *pCur){ 8537 int rc = SQLITE_OK; 8538 const int nMin = pCur->pBt->usableSize * 2 / 3; 8539 u8 aBalanceQuickSpace[13]; 8540 u8 *pFree = 0; 8541 8542 VVA_ONLY( int balance_quick_called = 0 ); 8543 VVA_ONLY( int balance_deeper_called = 0 ); 8544 8545 do { 8546 int iPage; 8547 MemPage *pPage = pCur->pPage; 8548 8549 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break; 8550 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ 8551 break; 8552 }else if( (iPage = pCur->iPage)==0 ){ 8553 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){ 8554 /* The root page of the b-tree is overfull. In this case call the 8555 ** balance_deeper() function to create a new child for the root-page 8556 ** and copy the current contents of the root-page to it. The 8557 ** next iteration of the do-loop will balance the child page. 8558 */ 8559 assert( balance_deeper_called==0 ); 8560 VVA_ONLY( balance_deeper_called++ ); 8561 rc = balance_deeper(pPage, &pCur->apPage[1]); 8562 if( rc==SQLITE_OK ){ 8563 pCur->iPage = 1; 8564 pCur->ix = 0; 8565 pCur->aiIdx[0] = 0; 8566 pCur->apPage[0] = pPage; 8567 pCur->pPage = pCur->apPage[1]; 8568 assert( pCur->pPage->nOverflow ); 8569 } 8570 }else{ 8571 break; 8572 } 8573 }else{ 8574 MemPage * const pParent = pCur->apPage[iPage-1]; 8575 int const iIdx = pCur->aiIdx[iPage-1]; 8576 8577 rc = sqlite3PagerWrite(pParent->pDbPage); 8578 if( rc==SQLITE_OK && pParent->nFree<0 ){ 8579 rc = btreeComputeFreeSpace(pParent); 8580 } 8581 if( rc==SQLITE_OK ){ 8582 #ifndef SQLITE_OMIT_QUICKBALANCE 8583 if( pPage->intKeyLeaf 8584 && pPage->nOverflow==1 8585 && pPage->aiOvfl[0]==pPage->nCell 8586 && pParent->pgno!=1 8587 && pParent->nCell==iIdx 8588 ){ 8589 /* Call balance_quick() to create a new sibling of pPage on which 8590 ** to store the overflow cell. balance_quick() inserts a new cell 8591 ** into pParent, which may cause pParent overflow. If this 8592 ** happens, the next iteration of the do-loop will balance pParent 8593 ** use either balance_nonroot() or balance_deeper(). Until this 8594 ** happens, the overflow cell is stored in the aBalanceQuickSpace[] 8595 ** buffer. 8596 ** 8597 ** The purpose of the following assert() is to check that only a 8598 ** single call to balance_quick() is made for each call to this 8599 ** function. If this were not verified, a subtle bug involving reuse 8600 ** of the aBalanceQuickSpace[] might sneak in. 8601 */ 8602 assert( balance_quick_called==0 ); 8603 VVA_ONLY( balance_quick_called++ ); 8604 rc = balance_quick(pParent, pPage, aBalanceQuickSpace); 8605 }else 8606 #endif 8607 { 8608 /* In this case, call balance_nonroot() to redistribute cells 8609 ** between pPage and up to 2 of its sibling pages. This involves 8610 ** modifying the contents of pParent, which may cause pParent to 8611 ** become overfull or underfull. The next iteration of the do-loop 8612 ** will balance the parent page to correct this. 8613 ** 8614 ** If the parent page becomes overfull, the overflow cell or cells 8615 ** are stored in the pSpace buffer allocated immediately below. 8616 ** A subsequent iteration of the do-loop will deal with this by 8617 ** calling balance_nonroot() (balance_deeper() may be called first, 8618 ** but it doesn't deal with overflow cells - just moves them to a 8619 ** different page). Once this subsequent call to balance_nonroot() 8620 ** has completed, it is safe to release the pSpace buffer used by 8621 ** the previous call, as the overflow cell data will have been 8622 ** copied either into the body of a database page or into the new 8623 ** pSpace buffer passed to the latter call to balance_nonroot(). 8624 */ 8625 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); 8626 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, 8627 pCur->hints&BTREE_BULKLOAD); 8628 if( pFree ){ 8629 /* If pFree is not NULL, it points to the pSpace buffer used 8630 ** by a previous call to balance_nonroot(). Its contents are 8631 ** now stored either on real database pages or within the 8632 ** new pSpace buffer, so it may be safely freed here. */ 8633 sqlite3PageFree(pFree); 8634 } 8635 8636 /* The pSpace buffer will be freed after the next call to 8637 ** balance_nonroot(), or just before this function returns, whichever 8638 ** comes first. */ 8639 pFree = pSpace; 8640 } 8641 } 8642 8643 pPage->nOverflow = 0; 8644 8645 /* The next iteration of the do-loop balances the parent page. */ 8646 releasePage(pPage); 8647 pCur->iPage--; 8648 assert( pCur->iPage>=0 ); 8649 pCur->pPage = pCur->apPage[pCur->iPage]; 8650 } 8651 }while( rc==SQLITE_OK ); 8652 8653 if( pFree ){ 8654 sqlite3PageFree(pFree); 8655 } 8656 return rc; 8657 } 8658 8659 /* Overwrite content from pX into pDest. Only do the write if the 8660 ** content is different from what is already there. 8661 */ 8662 static int btreeOverwriteContent( 8663 MemPage *pPage, /* MemPage on which writing will occur */ 8664 u8 *pDest, /* Pointer to the place to start writing */ 8665 const BtreePayload *pX, /* Source of data to write */ 8666 int iOffset, /* Offset of first byte to write */ 8667 int iAmt /* Number of bytes to be written */ 8668 ){ 8669 int nData = pX->nData - iOffset; 8670 if( nData<=0 ){ 8671 /* Overwritting with zeros */ 8672 int i; 8673 for(i=0; i<iAmt && pDest[i]==0; i++){} 8674 if( i<iAmt ){ 8675 int rc = sqlite3PagerWrite(pPage->pDbPage); 8676 if( rc ) return rc; 8677 memset(pDest + i, 0, iAmt - i); 8678 } 8679 }else{ 8680 if( nData<iAmt ){ 8681 /* Mixed read data and zeros at the end. Make a recursive call 8682 ** to write the zeros then fall through to write the real data */ 8683 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData, 8684 iAmt-nData); 8685 if( rc ) return rc; 8686 iAmt = nData; 8687 } 8688 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){ 8689 int rc = sqlite3PagerWrite(pPage->pDbPage); 8690 if( rc ) return rc; 8691 /* In a corrupt database, it is possible for the source and destination 8692 ** buffers to overlap. This is harmless since the database is already 8693 ** corrupt but it does cause valgrind and ASAN warnings. So use 8694 ** memmove(). */ 8695 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); 8696 } 8697 } 8698 return SQLITE_OK; 8699 } 8700 8701 /* 8702 ** Overwrite the cell that cursor pCur is pointing to with fresh content 8703 ** contained in pX. 8704 */ 8705 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){ 8706 int iOffset; /* Next byte of pX->pData to write */ 8707 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ 8708 int rc; /* Return code */ 8709 MemPage *pPage = pCur->pPage; /* Page being written */ 8710 BtShared *pBt; /* Btree */ 8711 Pgno ovflPgno; /* Next overflow page to write */ 8712 u32 ovflPageSize; /* Size to write on overflow page */ 8713 8714 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd 8715 || pCur->info.pPayload < pPage->aData + pPage->cellOffset 8716 ){ 8717 return SQLITE_CORRUPT_BKPT; 8718 } 8719 /* Overwrite the local portion first */ 8720 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX, 8721 0, pCur->info.nLocal); 8722 if( rc ) return rc; 8723 if( pCur->info.nLocal==nTotal ) return SQLITE_OK; 8724 8725 /* Now overwrite the overflow pages */ 8726 iOffset = pCur->info.nLocal; 8727 assert( nTotal>=0 ); 8728 assert( iOffset>=0 ); 8729 ovflPgno = get4byte(pCur->info.pPayload + iOffset); 8730 pBt = pPage->pBt; 8731 ovflPageSize = pBt->usableSize - 4; 8732 do{ 8733 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0); 8734 if( rc ) return rc; 8735 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){ 8736 rc = SQLITE_CORRUPT_BKPT; 8737 }else{ 8738 if( iOffset+ovflPageSize<(u32)nTotal ){ 8739 ovflPgno = get4byte(pPage->aData); 8740 }else{ 8741 ovflPageSize = nTotal - iOffset; 8742 } 8743 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX, 8744 iOffset, ovflPageSize); 8745 } 8746 sqlite3PagerUnref(pPage->pDbPage); 8747 if( rc ) return rc; 8748 iOffset += ovflPageSize; 8749 }while( iOffset<nTotal ); 8750 return SQLITE_OK; 8751 } 8752 8753 8754 /* 8755 ** Insert a new record into the BTree. The content of the new record 8756 ** is described by the pX object. The pCur cursor is used only to 8757 ** define what table the record should be inserted into, and is left 8758 ** pointing at a random location. 8759 ** 8760 ** For a table btree (used for rowid tables), only the pX.nKey value of 8761 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the 8762 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields 8763 ** hold the content of the row. 8764 ** 8765 ** For an index btree (used for indexes and WITHOUT ROWID tables), the 8766 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The 8767 ** pX.pData,nData,nZero fields must be zero. 8768 ** 8769 ** If the seekResult parameter is non-zero, then a successful call to 8770 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already 8771 ** been performed. In other words, if seekResult!=0 then the cursor 8772 ** is currently pointing to a cell that will be adjacent to the cell 8773 ** to be inserted. If seekResult<0 then pCur points to a cell that is 8774 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell 8775 ** that is larger than (pKey,nKey). 8776 ** 8777 ** If seekResult==0, that means pCur is pointing at some unknown location. 8778 ** In that case, this routine must seek the cursor to the correct insertion 8779 ** point for (pKey,nKey) before doing the insertion. For index btrees, 8780 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked 8781 ** key values and pX->aMem can be used instead of pX->pKey to avoid having 8782 ** to decode the key. 8783 */ 8784 int sqlite3BtreeInsert( 8785 BtCursor *pCur, /* Insert data into the table of this cursor */ 8786 const BtreePayload *pX, /* Content of the row to be inserted */ 8787 int flags, /* True if this is likely an append */ 8788 int seekResult /* Result of prior MovetoUnpacked() call */ 8789 ){ 8790 int rc; 8791 int loc = seekResult; /* -1: before desired location +1: after */ 8792 int szNew = 0; 8793 int idx; 8794 MemPage *pPage; 8795 Btree *p = pCur->pBtree; 8796 BtShared *pBt = p->pBt; 8797 unsigned char *oldCell; 8798 unsigned char *newCell = 0; 8799 8800 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags ); 8801 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 ); 8802 8803 if( pCur->eState==CURSOR_FAULT ){ 8804 assert( pCur->skipNext!=SQLITE_OK ); 8805 return pCur->skipNext; 8806 } 8807 8808 assert( cursorOwnsBtShared(pCur) ); 8809 assert( (pCur->curFlags & BTCF_WriteFlag)!=0 8810 && pBt->inTransaction==TRANS_WRITE 8811 && (pBt->btsFlags & BTS_READ_ONLY)==0 ); 8812 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 8813 8814 /* Assert that the caller has been consistent. If this cursor was opened 8815 ** expecting an index b-tree, then the caller should be inserting blob 8816 ** keys with no associated data. If the cursor was opened expecting an 8817 ** intkey table, the caller should be inserting integer keys with a 8818 ** blob of associated data. */ 8819 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) ); 8820 8821 /* Save the positions of any other cursors open on this table. 8822 ** 8823 ** In some cases, the call to btreeMoveto() below is a no-op. For 8824 ** example, when inserting data into a table with auto-generated integer 8825 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 8826 ** integer key to use. It then calls this function to actually insert the 8827 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes 8828 ** that the cursor is already where it needs to be and returns without 8829 ** doing any work. To avoid thwarting these optimizations, it is important 8830 ** not to clear the cursor here. 8831 */ 8832 if( pCur->curFlags & BTCF_Multiple ){ 8833 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 8834 if( rc ) return rc; 8835 if( loc && pCur->iPage<0 ){ 8836 /* This can only happen if the schema is corrupt such that there is more 8837 ** than one table or index with the same root page as used by the cursor. 8838 ** Which can only happen if the SQLITE_NoSchemaError flag was set when 8839 ** the schema was loaded. This cannot be asserted though, as a user might 8840 ** set the flag, load the schema, and then unset the flag. */ 8841 return SQLITE_CORRUPT_BKPT; 8842 } 8843 } 8844 8845 if( pCur->pKeyInfo==0 ){ 8846 assert( pX->pKey==0 ); 8847 /* If this is an insert into a table b-tree, invalidate any incrblob 8848 ** cursors open on the row being replaced */ 8849 if( p->hasIncrblobCur ){ 8850 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0); 8851 } 8852 8853 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 8854 ** to a row with the same key as the new entry being inserted. 8855 */ 8856 #ifdef SQLITE_DEBUG 8857 if( flags & BTREE_SAVEPOSITION ){ 8858 assert( pCur->curFlags & BTCF_ValidNKey ); 8859 assert( pX->nKey==pCur->info.nKey ); 8860 assert( loc==0 ); 8861 } 8862 #endif 8863 8864 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply 8865 ** that the cursor is not pointing to a row to be overwritten. 8866 ** So do a complete check. 8867 */ 8868 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ 8869 /* The cursor is pointing to the entry that is to be 8870 ** overwritten */ 8871 assert( pX->nData>=0 && pX->nZero>=0 ); 8872 if( pCur->info.nSize!=0 8873 && pCur->info.nPayload==(u32)pX->nData+pX->nZero 8874 ){ 8875 /* New entry is the same size as the old. Do an overwrite */ 8876 return btreeOverwriteCell(pCur, pX); 8877 } 8878 assert( loc==0 ); 8879 }else if( loc==0 ){ 8880 /* The cursor is *not* pointing to the cell to be overwritten, nor 8881 ** to an adjacent cell. Move the cursor so that it is pointing either 8882 ** to the cell to be overwritten or an adjacent cell. 8883 */ 8884 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey, 8885 (flags & BTREE_APPEND)!=0, &loc); 8886 if( rc ) return rc; 8887 } 8888 }else{ 8889 /* This is an index or a WITHOUT ROWID table */ 8890 8891 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 8892 ** to a row with the same key as the new entry being inserted. 8893 */ 8894 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 ); 8895 8896 /* If the cursor is not already pointing either to the cell to be 8897 ** overwritten, or if a new cell is being inserted, if the cursor is 8898 ** not pointing to an immediately adjacent cell, then move the cursor 8899 ** so that it does. 8900 */ 8901 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){ 8902 if( pX->nMem ){ 8903 UnpackedRecord r; 8904 r.pKeyInfo = pCur->pKeyInfo; 8905 r.aMem = pX->aMem; 8906 r.nField = pX->nMem; 8907 r.default_rc = 0; 8908 r.eqSeen = 0; 8909 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc); 8910 }else{ 8911 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, 8912 (flags & BTREE_APPEND)!=0, &loc); 8913 } 8914 if( rc ) return rc; 8915 } 8916 8917 /* If the cursor is currently pointing to an entry to be overwritten 8918 ** and the new content is the same as as the old, then use the 8919 ** overwrite optimization. 8920 */ 8921 if( loc==0 ){ 8922 getCellInfo(pCur); 8923 if( pCur->info.nKey==pX->nKey ){ 8924 BtreePayload x2; 8925 x2.pData = pX->pKey; 8926 x2.nData = pX->nKey; 8927 x2.nZero = 0; 8928 return btreeOverwriteCell(pCur, &x2); 8929 } 8930 } 8931 } 8932 assert( pCur->eState==CURSOR_VALID 8933 || (pCur->eState==CURSOR_INVALID && loc) 8934 || CORRUPT_DB ); 8935 8936 pPage = pCur->pPage; 8937 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) ); 8938 assert( pPage->leaf || !pPage->intKey ); 8939 if( pPage->nFree<0 ){ 8940 if( NEVER(pCur->eState>CURSOR_INVALID) ){ 8941 rc = SQLITE_CORRUPT_BKPT; 8942 }else{ 8943 rc = btreeComputeFreeSpace(pPage); 8944 } 8945 if( rc ) return rc; 8946 } 8947 8948 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", 8949 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, 8950 loc==0 ? "overwrite" : "new entry")); 8951 assert( pPage->isInit ); 8952 newCell = pBt->pTmpSpace; 8953 assert( newCell!=0 ); 8954 if( flags & BTREE_PREFORMAT ){ 8955 rc = SQLITE_OK; 8956 szNew = pBt->nPreformatSize; 8957 if( szNew<4 ) szNew = 4; 8958 if( ISAUTOVACUUM && szNew>pPage->maxLocal ){ 8959 CellInfo info; 8960 pPage->xParseCell(pPage, newCell, &info); 8961 if( info.nPayload!=info.nLocal ){ 8962 Pgno ovfl = get4byte(&newCell[szNew-4]); 8963 ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc); 8964 } 8965 } 8966 }else{ 8967 rc = fillInCell(pPage, newCell, pX, &szNew); 8968 } 8969 if( rc ) goto end_insert; 8970 assert( szNew==pPage->xCellSize(pPage, newCell) ); 8971 assert( szNew <= MX_CELL_SIZE(pBt) ); 8972 idx = pCur->ix; 8973 if( loc==0 ){ 8974 CellInfo info; 8975 assert( idx<pPage->nCell ); 8976 rc = sqlite3PagerWrite(pPage->pDbPage); 8977 if( rc ){ 8978 goto end_insert; 8979 } 8980 oldCell = findCell(pPage, idx); 8981 if( !pPage->leaf ){ 8982 memcpy(newCell, oldCell, 4); 8983 } 8984 BTREE_CLEAR_CELL(rc, pPage, oldCell, info); 8985 testcase( pCur->curFlags & BTCF_ValidOvfl ); 8986 invalidateOverflowCache(pCur); 8987 if( info.nSize==szNew && info.nLocal==info.nPayload 8988 && (!ISAUTOVACUUM || szNew<pPage->minLocal) 8989 ){ 8990 /* Overwrite the old cell with the new if they are the same size. 8991 ** We could also try to do this if the old cell is smaller, then add 8992 ** the leftover space to the free list. But experiments show that 8993 ** doing that is no faster then skipping this optimization and just 8994 ** calling dropCell() and insertCell(). 8995 ** 8996 ** This optimization cannot be used on an autovacuum database if the 8997 ** new entry uses overflow pages, as the insertCell() call below is 8998 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ 8999 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ 9000 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){ 9001 return SQLITE_CORRUPT_BKPT; 9002 } 9003 if( oldCell+szNew > pPage->aDataEnd ){ 9004 return SQLITE_CORRUPT_BKPT; 9005 } 9006 memcpy(oldCell, newCell, szNew); 9007 return SQLITE_OK; 9008 } 9009 dropCell(pPage, idx, info.nSize, &rc); 9010 if( rc ) goto end_insert; 9011 }else if( loc<0 && pPage->nCell>0 ){ 9012 assert( pPage->leaf ); 9013 idx = ++pCur->ix; 9014 pCur->curFlags &= ~BTCF_ValidNKey; 9015 }else{ 9016 assert( pPage->leaf ); 9017 } 9018 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); 9019 assert( pPage->nOverflow==0 || rc==SQLITE_OK ); 9020 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); 9021 9022 /* If no error has occurred and pPage has an overflow cell, call balance() 9023 ** to redistribute the cells within the tree. Since balance() may move 9024 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey 9025 ** variables. 9026 ** 9027 ** Previous versions of SQLite called moveToRoot() to move the cursor 9028 ** back to the root page as balance() used to invalidate the contents 9029 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, 9030 ** set the cursor state to "invalid". This makes common insert operations 9031 ** slightly faster. 9032 ** 9033 ** There is a subtle but important optimization here too. When inserting 9034 ** multiple records into an intkey b-tree using a single cursor (as can 9035 ** happen while processing an "INSERT INTO ... SELECT" statement), it 9036 ** is advantageous to leave the cursor pointing to the last entry in 9037 ** the b-tree if possible. If the cursor is left pointing to the last 9038 ** entry in the table, and the next row inserted has an integer key 9039 ** larger than the largest existing key, it is possible to insert the 9040 ** row without seeking the cursor. This can be a big performance boost. 9041 */ 9042 pCur->info.nSize = 0; 9043 if( pPage->nOverflow ){ 9044 assert( rc==SQLITE_OK ); 9045 pCur->curFlags &= ~(BTCF_ValidNKey); 9046 rc = balance(pCur); 9047 9048 /* Must make sure nOverflow is reset to zero even if the balance() 9049 ** fails. Internal data structure corruption will result otherwise. 9050 ** Also, set the cursor state to invalid. This stops saveCursorPosition() 9051 ** from trying to save the current position of the cursor. */ 9052 pCur->pPage->nOverflow = 0; 9053 pCur->eState = CURSOR_INVALID; 9054 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){ 9055 btreeReleaseAllCursorPages(pCur); 9056 if( pCur->pKeyInfo ){ 9057 assert( pCur->pKey==0 ); 9058 pCur->pKey = sqlite3Malloc( pX->nKey ); 9059 if( pCur->pKey==0 ){ 9060 rc = SQLITE_NOMEM; 9061 }else{ 9062 memcpy(pCur->pKey, pX->pKey, pX->nKey); 9063 } 9064 } 9065 pCur->eState = CURSOR_REQUIRESEEK; 9066 pCur->nKey = pX->nKey; 9067 } 9068 } 9069 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 ); 9070 9071 end_insert: 9072 return rc; 9073 } 9074 9075 /* 9076 ** This function is used as part of copying the current row from cursor 9077 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then 9078 ** parameter iKey is used as the rowid value when the record is copied 9079 ** into pDest. Otherwise, the record is copied verbatim. 9080 ** 9081 ** This function does not actually write the new value to cursor pDest. 9082 ** Instead, it creates and populates any required overflow pages and 9083 ** writes the data for the new cell into the BtShared.pTmpSpace buffer 9084 ** for the destination database. The size of the cell, in bytes, is left 9085 ** in BtShared.nPreformatSize. The caller completes the insertion by 9086 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified. 9087 ** 9088 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. 9089 */ 9090 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){ 9091 int rc = SQLITE_OK; 9092 BtShared *pBt = pDest->pBt; 9093 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */ 9094 const u8 *aIn; /* Pointer to next input buffer */ 9095 u32 nIn; /* Size of input buffer aIn[] */ 9096 u32 nRem; /* Bytes of data still to copy */ 9097 9098 getCellInfo(pSrc); 9099 aOut += putVarint32(aOut, pSrc->info.nPayload); 9100 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey); 9101 nIn = pSrc->info.nLocal; 9102 aIn = pSrc->info.pPayload; 9103 if( aIn+nIn>pSrc->pPage->aDataEnd ){ 9104 return SQLITE_CORRUPT_BKPT; 9105 } 9106 nRem = pSrc->info.nPayload; 9107 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){ 9108 memcpy(aOut, aIn, nIn); 9109 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace); 9110 }else{ 9111 Pager *pSrcPager = pSrc->pBt->pPager; 9112 u8 *pPgnoOut = 0; 9113 Pgno ovflIn = 0; 9114 DbPage *pPageIn = 0; 9115 MemPage *pPageOut = 0; 9116 u32 nOut; /* Size of output buffer aOut[] */ 9117 9118 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload); 9119 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace); 9120 if( nOut<pSrc->info.nPayload ){ 9121 pPgnoOut = &aOut[nOut]; 9122 pBt->nPreformatSize += 4; 9123 } 9124 9125 if( nRem>nIn ){ 9126 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){ 9127 return SQLITE_CORRUPT_BKPT; 9128 } 9129 ovflIn = get4byte(&pSrc->info.pPayload[nIn]); 9130 } 9131 9132 do { 9133 nRem -= nOut; 9134 do{ 9135 assert( nOut>0 ); 9136 if( nIn>0 ){ 9137 int nCopy = MIN(nOut, nIn); 9138 memcpy(aOut, aIn, nCopy); 9139 nOut -= nCopy; 9140 nIn -= nCopy; 9141 aOut += nCopy; 9142 aIn += nCopy; 9143 } 9144 if( nOut>0 ){ 9145 sqlite3PagerUnref(pPageIn); 9146 pPageIn = 0; 9147 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY); 9148 if( rc==SQLITE_OK ){ 9149 aIn = (const u8*)sqlite3PagerGetData(pPageIn); 9150 ovflIn = get4byte(aIn); 9151 aIn += 4; 9152 nIn = pSrc->pBt->usableSize - 4; 9153 } 9154 } 9155 }while( rc==SQLITE_OK && nOut>0 ); 9156 9157 if( rc==SQLITE_OK && nRem>0 ){ 9158 Pgno pgnoNew; 9159 MemPage *pNew = 0; 9160 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); 9161 put4byte(pPgnoOut, pgnoNew); 9162 if( ISAUTOVACUUM && pPageOut ){ 9163 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc); 9164 } 9165 releasePage(pPageOut); 9166 pPageOut = pNew; 9167 if( pPageOut ){ 9168 pPgnoOut = pPageOut->aData; 9169 put4byte(pPgnoOut, 0); 9170 aOut = &pPgnoOut[4]; 9171 nOut = MIN(pBt->usableSize - 4, nRem); 9172 } 9173 } 9174 }while( nRem>0 && rc==SQLITE_OK ); 9175 9176 releasePage(pPageOut); 9177 sqlite3PagerUnref(pPageIn); 9178 } 9179 9180 return rc; 9181 } 9182 9183 /* 9184 ** Delete the entry that the cursor is pointing to. 9185 ** 9186 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then 9187 ** the cursor is left pointing at an arbitrary location after the delete. 9188 ** But if that bit is set, then the cursor is left in a state such that 9189 ** the next call to BtreeNext() or BtreePrev() moves it to the same row 9190 ** as it would have been on if the call to BtreeDelete() had been omitted. 9191 ** 9192 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes 9193 ** associated with a single table entry and its indexes. Only one of those 9194 ** deletes is considered the "primary" delete. The primary delete occurs 9195 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete 9196 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. 9197 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, 9198 ** but which might be used by alternative storage engines. 9199 */ 9200 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ 9201 Btree *p = pCur->pBtree; 9202 BtShared *pBt = p->pBt; 9203 int rc; /* Return code */ 9204 MemPage *pPage; /* Page to delete cell from */ 9205 unsigned char *pCell; /* Pointer to cell to delete */ 9206 int iCellIdx; /* Index of cell to delete */ 9207 int iCellDepth; /* Depth of node containing pCell */ 9208 CellInfo info; /* Size of the cell being deleted */ 9209 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ 9210 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ 9211 9212 assert( cursorOwnsBtShared(pCur) ); 9213 assert( pBt->inTransaction==TRANS_WRITE ); 9214 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 9215 assert( pCur->curFlags & BTCF_WriteFlag ); 9216 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 9217 assert( !hasReadConflicts(p, pCur->pgnoRoot) ); 9218 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); 9219 if( pCur->eState==CURSOR_REQUIRESEEK ){ 9220 rc = btreeRestoreCursorPosition(pCur); 9221 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID ); 9222 if( rc || pCur->eState!=CURSOR_VALID ) return rc; 9223 } 9224 assert( CORRUPT_DB || pCur->eState==CURSOR_VALID ); 9225 9226 iCellDepth = pCur->iPage; 9227 iCellIdx = pCur->ix; 9228 pPage = pCur->pPage; 9229 pCell = findCell(pPage, iCellIdx); 9230 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT; 9231 9232 /* If the bPreserve flag is set to true, then the cursor position must 9233 ** be preserved following this delete operation. If the current delete 9234 ** will cause a b-tree rebalance, then this is done by saving the cursor 9235 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 9236 ** returning. 9237 ** 9238 ** Or, if the current delete will not cause a rebalance, then the cursor 9239 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately 9240 ** before or after the deleted entry. In this case set bSkipnext to true. */ 9241 if( bPreserve ){ 9242 if( !pPage->leaf 9243 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) 9244 || pPage->nCell==1 /* See dbfuzz001.test for a test case */ 9245 ){ 9246 /* A b-tree rebalance will be required after deleting this entry. 9247 ** Save the cursor key. */ 9248 rc = saveCursorKey(pCur); 9249 if( rc ) return rc; 9250 }else{ 9251 bSkipnext = 1; 9252 } 9253 } 9254 9255 /* If the page containing the entry to delete is not a leaf page, move 9256 ** the cursor to the largest entry in the tree that is smaller than 9257 ** the entry being deleted. This cell will replace the cell being deleted 9258 ** from the internal node. The 'previous' entry is used for this instead 9259 ** of the 'next' entry, as the previous entry is always a part of the 9260 ** sub-tree headed by the child page of the cell being deleted. This makes 9261 ** balancing the tree following the delete operation easier. */ 9262 if( !pPage->leaf ){ 9263 rc = sqlite3BtreePrevious(pCur, 0); 9264 assert( rc!=SQLITE_DONE ); 9265 if( rc ) return rc; 9266 } 9267 9268 /* Save the positions of any other cursors open on this table before 9269 ** making any modifications. */ 9270 if( pCur->curFlags & BTCF_Multiple ){ 9271 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 9272 if( rc ) return rc; 9273 } 9274 9275 /* If this is a delete operation to remove a row from a table b-tree, 9276 ** invalidate any incrblob cursors open on the row being deleted. */ 9277 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){ 9278 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0); 9279 } 9280 9281 /* Make the page containing the entry to be deleted writable. Then free any 9282 ** overflow pages associated with the entry and finally remove the cell 9283 ** itself from within the page. */ 9284 rc = sqlite3PagerWrite(pPage->pDbPage); 9285 if( rc ) return rc; 9286 BTREE_CLEAR_CELL(rc, pPage, pCell, info); 9287 dropCell(pPage, iCellIdx, info.nSize, &rc); 9288 if( rc ) return rc; 9289 9290 /* If the cell deleted was not located on a leaf page, then the cursor 9291 ** is currently pointing to the largest entry in the sub-tree headed 9292 ** by the child-page of the cell that was just deleted from an internal 9293 ** node. The cell from the leaf node needs to be moved to the internal 9294 ** node to replace the deleted cell. */ 9295 if( !pPage->leaf ){ 9296 MemPage *pLeaf = pCur->pPage; 9297 int nCell; 9298 Pgno n; 9299 unsigned char *pTmp; 9300 9301 if( pLeaf->nFree<0 ){ 9302 rc = btreeComputeFreeSpace(pLeaf); 9303 if( rc ) return rc; 9304 } 9305 if( iCellDepth<pCur->iPage-1 ){ 9306 n = pCur->apPage[iCellDepth+1]->pgno; 9307 }else{ 9308 n = pCur->pPage->pgno; 9309 } 9310 pCell = findCell(pLeaf, pLeaf->nCell-1); 9311 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; 9312 nCell = pLeaf->xCellSize(pLeaf, pCell); 9313 assert( MX_CELL_SIZE(pBt) >= nCell ); 9314 pTmp = pBt->pTmpSpace; 9315 assert( pTmp!=0 ); 9316 rc = sqlite3PagerWrite(pLeaf->pDbPage); 9317 if( rc==SQLITE_OK ){ 9318 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); 9319 } 9320 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); 9321 if( rc ) return rc; 9322 } 9323 9324 /* Balance the tree. If the entry deleted was located on a leaf page, 9325 ** then the cursor still points to that page. In this case the first 9326 ** call to balance() repairs the tree, and the if(...) condition is 9327 ** never true. 9328 ** 9329 ** Otherwise, if the entry deleted was on an internal node page, then 9330 ** pCur is pointing to the leaf page from which a cell was removed to 9331 ** replace the cell deleted from the internal node. This is slightly 9332 ** tricky as the leaf node may be underfull, and the internal node may 9333 ** be either under or overfull. In this case run the balancing algorithm 9334 ** on the leaf node first. If the balance proceeds far enough up the 9335 ** tree that we can be sure that any problem in the internal node has 9336 ** been corrected, so be it. Otherwise, after balancing the leaf node, 9337 ** walk the cursor up the tree to the internal node and balance it as 9338 ** well. */ 9339 rc = balance(pCur); 9340 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ 9341 releasePageNotNull(pCur->pPage); 9342 pCur->iPage--; 9343 while( pCur->iPage>iCellDepth ){ 9344 releasePage(pCur->apPage[pCur->iPage--]); 9345 } 9346 pCur->pPage = pCur->apPage[pCur->iPage]; 9347 rc = balance(pCur); 9348 } 9349 9350 if( rc==SQLITE_OK ){ 9351 if( bSkipnext ){ 9352 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); 9353 assert( pPage==pCur->pPage || CORRUPT_DB ); 9354 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); 9355 pCur->eState = CURSOR_SKIPNEXT; 9356 if( iCellIdx>=pPage->nCell ){ 9357 pCur->skipNext = -1; 9358 pCur->ix = pPage->nCell-1; 9359 }else{ 9360 pCur->skipNext = 1; 9361 } 9362 }else{ 9363 rc = moveToRoot(pCur); 9364 if( bPreserve ){ 9365 btreeReleaseAllCursorPages(pCur); 9366 pCur->eState = CURSOR_REQUIRESEEK; 9367 } 9368 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK; 9369 } 9370 } 9371 return rc; 9372 } 9373 9374 /* 9375 ** Create a new BTree table. Write into *piTable the page 9376 ** number for the root page of the new table. 9377 ** 9378 ** The type of type is determined by the flags parameter. Only the 9379 ** following values of flags are currently in use. Other values for 9380 ** flags might not work: 9381 ** 9382 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys 9383 ** BTREE_ZERODATA Used for SQL indices 9384 */ 9385 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){ 9386 BtShared *pBt = p->pBt; 9387 MemPage *pRoot; 9388 Pgno pgnoRoot; 9389 int rc; 9390 int ptfFlags; /* Page-type flage for the root page of new table */ 9391 9392 assert( sqlite3BtreeHoldsMutex(p) ); 9393 assert( pBt->inTransaction==TRANS_WRITE ); 9394 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 9395 9396 #ifdef SQLITE_OMIT_AUTOVACUUM 9397 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 9398 if( rc ){ 9399 return rc; 9400 } 9401 #else 9402 if( pBt->autoVacuum ){ 9403 Pgno pgnoMove; /* Move a page here to make room for the root-page */ 9404 MemPage *pPageMove; /* The page to move to. */ 9405 9406 /* Creating a new table may probably require moving an existing database 9407 ** to make room for the new tables root page. In case this page turns 9408 ** out to be an overflow page, delete all overflow page-map caches 9409 ** held by open cursors. 9410 */ 9411 invalidateAllOverflowCache(pBt); 9412 9413 /* Read the value of meta[3] from the database to determine where the 9414 ** root page of the new table should go. meta[3] is the largest root-page 9415 ** created so far, so the new root-page is (meta[3]+1). 9416 */ 9417 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); 9418 if( pgnoRoot>btreePagecount(pBt) ){ 9419 return SQLITE_CORRUPT_BKPT; 9420 } 9421 pgnoRoot++; 9422 9423 /* The new root-page may not be allocated on a pointer-map page, or the 9424 ** PENDING_BYTE page. 9425 */ 9426 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || 9427 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ 9428 pgnoRoot++; 9429 } 9430 assert( pgnoRoot>=3 ); 9431 9432 /* Allocate a page. The page that currently resides at pgnoRoot will 9433 ** be moved to the allocated page (unless the allocated page happens 9434 ** to reside at pgnoRoot). 9435 */ 9436 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); 9437 if( rc!=SQLITE_OK ){ 9438 return rc; 9439 } 9440 9441 if( pgnoMove!=pgnoRoot ){ 9442 /* pgnoRoot is the page that will be used for the root-page of 9443 ** the new table (assuming an error did not occur). But we were 9444 ** allocated pgnoMove. If required (i.e. if it was not allocated 9445 ** by extending the file), the current page at position pgnoMove 9446 ** is already journaled. 9447 */ 9448 u8 eType = 0; 9449 Pgno iPtrPage = 0; 9450 9451 /* Save the positions of any open cursors. This is required in 9452 ** case they are holding a reference to an xFetch reference 9453 ** corresponding to page pgnoRoot. */ 9454 rc = saveAllCursors(pBt, 0, 0); 9455 releasePage(pPageMove); 9456 if( rc!=SQLITE_OK ){ 9457 return rc; 9458 } 9459 9460 /* Move the page currently at pgnoRoot to pgnoMove. */ 9461 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 9462 if( rc!=SQLITE_OK ){ 9463 return rc; 9464 } 9465 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); 9466 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ 9467 rc = SQLITE_CORRUPT_BKPT; 9468 } 9469 if( rc!=SQLITE_OK ){ 9470 releasePage(pRoot); 9471 return rc; 9472 } 9473 assert( eType!=PTRMAP_ROOTPAGE ); 9474 assert( eType!=PTRMAP_FREEPAGE ); 9475 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); 9476 releasePage(pRoot); 9477 9478 /* Obtain the page at pgnoRoot */ 9479 if( rc!=SQLITE_OK ){ 9480 return rc; 9481 } 9482 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 9483 if( rc!=SQLITE_OK ){ 9484 return rc; 9485 } 9486 rc = sqlite3PagerWrite(pRoot->pDbPage); 9487 if( rc!=SQLITE_OK ){ 9488 releasePage(pRoot); 9489 return rc; 9490 } 9491 }else{ 9492 pRoot = pPageMove; 9493 } 9494 9495 /* Update the pointer-map and meta-data with the new root-page number. */ 9496 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); 9497 if( rc ){ 9498 releasePage(pRoot); 9499 return rc; 9500 } 9501 9502 /* When the new root page was allocated, page 1 was made writable in 9503 ** order either to increase the database filesize, or to decrement the 9504 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. 9505 */ 9506 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); 9507 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); 9508 if( NEVER(rc) ){ 9509 releasePage(pRoot); 9510 return rc; 9511 } 9512 9513 }else{ 9514 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 9515 if( rc ) return rc; 9516 } 9517 #endif 9518 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 9519 if( createTabFlags & BTREE_INTKEY ){ 9520 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; 9521 }else{ 9522 ptfFlags = PTF_ZERODATA | PTF_LEAF; 9523 } 9524 zeroPage(pRoot, ptfFlags); 9525 sqlite3PagerUnref(pRoot->pDbPage); 9526 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); 9527 *piTable = pgnoRoot; 9528 return SQLITE_OK; 9529 } 9530 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){ 9531 int rc; 9532 sqlite3BtreeEnter(p); 9533 rc = btreeCreateTable(p, piTable, flags); 9534 sqlite3BtreeLeave(p); 9535 return rc; 9536 } 9537 9538 /* 9539 ** Erase the given database page and all its children. Return 9540 ** the page to the freelist. 9541 */ 9542 static int clearDatabasePage( 9543 BtShared *pBt, /* The BTree that contains the table */ 9544 Pgno pgno, /* Page number to clear */ 9545 int freePageFlag, /* Deallocate page if true */ 9546 i64 *pnChange /* Add number of Cells freed to this counter */ 9547 ){ 9548 MemPage *pPage; 9549 int rc; 9550 unsigned char *pCell; 9551 int i; 9552 int hdr; 9553 CellInfo info; 9554 9555 assert( sqlite3_mutex_held(pBt->mutex) ); 9556 if( pgno>btreePagecount(pBt) ){ 9557 return SQLITE_CORRUPT_BKPT; 9558 } 9559 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); 9560 if( rc ) return rc; 9561 if( pPage->bBusy ){ 9562 rc = SQLITE_CORRUPT_BKPT; 9563 goto cleardatabasepage_out; 9564 } 9565 pPage->bBusy = 1; 9566 hdr = pPage->hdrOffset; 9567 for(i=0; i<pPage->nCell; i++){ 9568 pCell = findCell(pPage, i); 9569 if( !pPage->leaf ){ 9570 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); 9571 if( rc ) goto cleardatabasepage_out; 9572 } 9573 BTREE_CLEAR_CELL(rc, pPage, pCell, info); 9574 if( rc ) goto cleardatabasepage_out; 9575 } 9576 if( !pPage->leaf ){ 9577 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); 9578 if( rc ) goto cleardatabasepage_out; 9579 if( pPage->intKey ) pnChange = 0; 9580 } 9581 if( pnChange ){ 9582 testcase( !pPage->intKey ); 9583 *pnChange += pPage->nCell; 9584 } 9585 if( freePageFlag ){ 9586 freePage(pPage, &rc); 9587 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ 9588 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); 9589 } 9590 9591 cleardatabasepage_out: 9592 pPage->bBusy = 0; 9593 releasePage(pPage); 9594 return rc; 9595 } 9596 9597 /* 9598 ** Delete all information from a single table in the database. iTable is 9599 ** the page number of the root of the table. After this routine returns, 9600 ** the root page is empty, but still exists. 9601 ** 9602 ** This routine will fail with SQLITE_LOCKED if there are any open 9603 ** read cursors on the table. Open write cursors are moved to the 9604 ** root of the table. 9605 ** 9606 ** If pnChange is not NULL, then the integer value pointed to by pnChange 9607 ** is incremented by the number of entries in the table. 9608 */ 9609 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){ 9610 int rc; 9611 BtShared *pBt = p->pBt; 9612 sqlite3BtreeEnter(p); 9613 assert( p->inTrans==TRANS_WRITE ); 9614 9615 rc = saveAllCursors(pBt, (Pgno)iTable, 0); 9616 9617 if( SQLITE_OK==rc ){ 9618 /* Invalidate all incrblob cursors open on table iTable (assuming iTable 9619 ** is the root of a table b-tree - if it is not, the following call is 9620 ** a no-op). */ 9621 if( p->hasIncrblobCur ){ 9622 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1); 9623 } 9624 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); 9625 } 9626 sqlite3BtreeLeave(p); 9627 return rc; 9628 } 9629 9630 /* 9631 ** Delete all information from the single table that pCur is open on. 9632 ** 9633 ** This routine only work for pCur on an ephemeral table. 9634 */ 9635 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ 9636 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); 9637 } 9638 9639 /* 9640 ** Erase all information in a table and add the root of the table to 9641 ** the freelist. Except, the root of the principle table (the one on 9642 ** page 1) is never added to the freelist. 9643 ** 9644 ** This routine will fail with SQLITE_LOCKED if there are any open 9645 ** cursors on the table. 9646 ** 9647 ** If AUTOVACUUM is enabled and the page at iTable is not the last 9648 ** root page in the database file, then the last root page 9649 ** in the database file is moved into the slot formerly occupied by 9650 ** iTable and that last slot formerly occupied by the last root page 9651 ** is added to the freelist instead of iTable. In this say, all 9652 ** root pages are kept at the beginning of the database file, which 9653 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the 9654 ** page number that used to be the last root page in the file before 9655 ** the move. If no page gets moved, *piMoved is set to 0. 9656 ** The last root page is recorded in meta[3] and the value of 9657 ** meta[3] is updated by this procedure. 9658 */ 9659 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ 9660 int rc; 9661 MemPage *pPage = 0; 9662 BtShared *pBt = p->pBt; 9663 9664 assert( sqlite3BtreeHoldsMutex(p) ); 9665 assert( p->inTrans==TRANS_WRITE ); 9666 assert( iTable>=2 ); 9667 if( iTable>btreePagecount(pBt) ){ 9668 return SQLITE_CORRUPT_BKPT; 9669 } 9670 9671 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); 9672 if( rc ) return rc; 9673 rc = sqlite3BtreeClearTable(p, iTable, 0); 9674 if( rc ){ 9675 releasePage(pPage); 9676 return rc; 9677 } 9678 9679 *piMoved = 0; 9680 9681 #ifdef SQLITE_OMIT_AUTOVACUUM 9682 freePage(pPage, &rc); 9683 releasePage(pPage); 9684 #else 9685 if( pBt->autoVacuum ){ 9686 Pgno maxRootPgno; 9687 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); 9688 9689 if( iTable==maxRootPgno ){ 9690 /* If the table being dropped is the table with the largest root-page 9691 ** number in the database, put the root page on the free list. 9692 */ 9693 freePage(pPage, &rc); 9694 releasePage(pPage); 9695 if( rc!=SQLITE_OK ){ 9696 return rc; 9697 } 9698 }else{ 9699 /* The table being dropped does not have the largest root-page 9700 ** number in the database. So move the page that does into the 9701 ** gap left by the deleted root-page. 9702 */ 9703 MemPage *pMove; 9704 releasePage(pPage); 9705 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 9706 if( rc!=SQLITE_OK ){ 9707 return rc; 9708 } 9709 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); 9710 releasePage(pMove); 9711 if( rc!=SQLITE_OK ){ 9712 return rc; 9713 } 9714 pMove = 0; 9715 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 9716 freePage(pMove, &rc); 9717 releasePage(pMove); 9718 if( rc!=SQLITE_OK ){ 9719 return rc; 9720 } 9721 *piMoved = maxRootPgno; 9722 } 9723 9724 /* Set the new 'max-root-page' value in the database header. This 9725 ** is the old value less one, less one more if that happens to 9726 ** be a root-page number, less one again if that is the 9727 ** PENDING_BYTE_PAGE. 9728 */ 9729 maxRootPgno--; 9730 while( maxRootPgno==PENDING_BYTE_PAGE(pBt) 9731 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ 9732 maxRootPgno--; 9733 } 9734 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); 9735 9736 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); 9737 }else{ 9738 freePage(pPage, &rc); 9739 releasePage(pPage); 9740 } 9741 #endif 9742 return rc; 9743 } 9744 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ 9745 int rc; 9746 sqlite3BtreeEnter(p); 9747 rc = btreeDropTable(p, iTable, piMoved); 9748 sqlite3BtreeLeave(p); 9749 return rc; 9750 } 9751 9752 9753 /* 9754 ** This function may only be called if the b-tree connection already 9755 ** has a read or write transaction open on the database. 9756 ** 9757 ** Read the meta-information out of a database file. Meta[0] 9758 ** is the number of free pages currently in the database. Meta[1] 9759 ** through meta[15] are available for use by higher layers. Meta[0] 9760 ** is read-only, the others are read/write. 9761 ** 9762 ** The schema layer numbers meta values differently. At the schema 9763 ** layer (and the SetCookie and ReadCookie opcodes) the number of 9764 ** free pages is not visible. So Cookie[0] is the same as Meta[1]. 9765 ** 9766 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead 9767 ** of reading the value out of the header, it instead loads the "DataVersion" 9768 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the 9769 ** database file. It is a number computed by the pager. But its access 9770 ** pattern is the same as header meta values, and so it is convenient to 9771 ** read it from this routine. 9772 */ 9773 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ 9774 BtShared *pBt = p->pBt; 9775 9776 sqlite3BtreeEnter(p); 9777 assert( p->inTrans>TRANS_NONE ); 9778 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) ); 9779 assert( pBt->pPage1 ); 9780 assert( idx>=0 && idx<=15 ); 9781 9782 if( idx==BTREE_DATA_VERSION ){ 9783 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion; 9784 }else{ 9785 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); 9786 } 9787 9788 /* If auto-vacuum is disabled in this build and this is an auto-vacuum 9789 ** database, mark the database as read-only. */ 9790 #ifdef SQLITE_OMIT_AUTOVACUUM 9791 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ 9792 pBt->btsFlags |= BTS_READ_ONLY; 9793 } 9794 #endif 9795 9796 sqlite3BtreeLeave(p); 9797 } 9798 9799 /* 9800 ** Write meta-information back into the database. Meta[0] is 9801 ** read-only and may not be written. 9802 */ 9803 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ 9804 BtShared *pBt = p->pBt; 9805 unsigned char *pP1; 9806 int rc; 9807 assert( idx>=1 && idx<=15 ); 9808 sqlite3BtreeEnter(p); 9809 assert( p->inTrans==TRANS_WRITE ); 9810 assert( pBt->pPage1!=0 ); 9811 pP1 = pBt->pPage1->aData; 9812 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 9813 if( rc==SQLITE_OK ){ 9814 put4byte(&pP1[36 + idx*4], iMeta); 9815 #ifndef SQLITE_OMIT_AUTOVACUUM 9816 if( idx==BTREE_INCR_VACUUM ){ 9817 assert( pBt->autoVacuum || iMeta==0 ); 9818 assert( iMeta==0 || iMeta==1 ); 9819 pBt->incrVacuum = (u8)iMeta; 9820 } 9821 #endif 9822 } 9823 sqlite3BtreeLeave(p); 9824 return rc; 9825 } 9826 9827 /* 9828 ** The first argument, pCur, is a cursor opened on some b-tree. Count the 9829 ** number of entries in the b-tree and write the result to *pnEntry. 9830 ** 9831 ** SQLITE_OK is returned if the operation is successfully executed. 9832 ** Otherwise, if an error is encountered (i.e. an IO error or database 9833 ** corruption) an SQLite error code is returned. 9834 */ 9835 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){ 9836 i64 nEntry = 0; /* Value to return in *pnEntry */ 9837 int rc; /* Return code */ 9838 9839 rc = moveToRoot(pCur); 9840 if( rc==SQLITE_EMPTY ){ 9841 *pnEntry = 0; 9842 return SQLITE_OK; 9843 } 9844 9845 /* Unless an error occurs, the following loop runs one iteration for each 9846 ** page in the B-Tree structure (not including overflow pages). 9847 */ 9848 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){ 9849 int iIdx; /* Index of child node in parent */ 9850 MemPage *pPage; /* Current page of the b-tree */ 9851 9852 /* If this is a leaf page or the tree is not an int-key tree, then 9853 ** this page contains countable entries. Increment the entry counter 9854 ** accordingly. 9855 */ 9856 pPage = pCur->pPage; 9857 if( pPage->leaf || !pPage->intKey ){ 9858 nEntry += pPage->nCell; 9859 } 9860 9861 /* pPage is a leaf node. This loop navigates the cursor so that it 9862 ** points to the first interior cell that it points to the parent of 9863 ** the next page in the tree that has not yet been visited. The 9864 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell 9865 ** of the page, or to the number of cells in the page if the next page 9866 ** to visit is the right-child of its parent. 9867 ** 9868 ** If all pages in the tree have been visited, return SQLITE_OK to the 9869 ** caller. 9870 */ 9871 if( pPage->leaf ){ 9872 do { 9873 if( pCur->iPage==0 ){ 9874 /* All pages of the b-tree have been visited. Return successfully. */ 9875 *pnEntry = nEntry; 9876 return moveToRoot(pCur); 9877 } 9878 moveToParent(pCur); 9879 }while ( pCur->ix>=pCur->pPage->nCell ); 9880 9881 pCur->ix++; 9882 pPage = pCur->pPage; 9883 } 9884 9885 /* Descend to the child node of the cell that the cursor currently 9886 ** points at. This is the right-child if (iIdx==pPage->nCell). 9887 */ 9888 iIdx = pCur->ix; 9889 if( iIdx==pPage->nCell ){ 9890 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 9891 }else{ 9892 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); 9893 } 9894 } 9895 9896 /* An error has occurred. Return an error code. */ 9897 return rc; 9898 } 9899 9900 /* 9901 ** Return the pager associated with a BTree. This routine is used for 9902 ** testing and debugging only. 9903 */ 9904 Pager *sqlite3BtreePager(Btree *p){ 9905 return p->pBt->pPager; 9906 } 9907 9908 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9909 /* 9910 ** Append a message to the error message string. 9911 */ 9912 static void checkAppendMsg( 9913 IntegrityCk *pCheck, 9914 const char *zFormat, 9915 ... 9916 ){ 9917 va_list ap; 9918 if( !pCheck->mxErr ) return; 9919 pCheck->mxErr--; 9920 pCheck->nErr++; 9921 va_start(ap, zFormat); 9922 if( pCheck->errMsg.nChar ){ 9923 sqlite3_str_append(&pCheck->errMsg, "\n", 1); 9924 } 9925 if( pCheck->zPfx ){ 9926 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); 9927 } 9928 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap); 9929 va_end(ap); 9930 if( pCheck->errMsg.accError==SQLITE_NOMEM ){ 9931 pCheck->bOomFault = 1; 9932 } 9933 } 9934 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 9935 9936 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9937 9938 /* 9939 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that 9940 ** corresponds to page iPg is already set. 9941 */ 9942 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 9943 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 9944 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); 9945 } 9946 9947 /* 9948 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. 9949 */ 9950 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 9951 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 9952 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); 9953 } 9954 9955 9956 /* 9957 ** Add 1 to the reference count for page iPage. If this is the second 9958 ** reference to the page, add an error message to pCheck->zErrMsg. 9959 ** Return 1 if there are 2 or more references to the page and 0 if 9960 ** if this is the first reference to the page. 9961 ** 9962 ** Also check that the page number is in bounds. 9963 */ 9964 static int checkRef(IntegrityCk *pCheck, Pgno iPage){ 9965 if( iPage>pCheck->nPage || iPage==0 ){ 9966 checkAppendMsg(pCheck, "invalid page number %d", iPage); 9967 return 1; 9968 } 9969 if( getPageReferenced(pCheck, iPage) ){ 9970 checkAppendMsg(pCheck, "2nd reference to page %d", iPage); 9971 return 1; 9972 } 9973 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1; 9974 setPageReferenced(pCheck, iPage); 9975 return 0; 9976 } 9977 9978 #ifndef SQLITE_OMIT_AUTOVACUUM 9979 /* 9980 ** Check that the entry in the pointer-map for page iChild maps to 9981 ** page iParent, pointer type ptrType. If not, append an error message 9982 ** to pCheck. 9983 */ 9984 static void checkPtrmap( 9985 IntegrityCk *pCheck, /* Integrity check context */ 9986 Pgno iChild, /* Child page number */ 9987 u8 eType, /* Expected pointer map type */ 9988 Pgno iParent /* Expected pointer map parent page number */ 9989 ){ 9990 int rc; 9991 u8 ePtrmapType; 9992 Pgno iPtrmapParent; 9993 9994 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); 9995 if( rc!=SQLITE_OK ){ 9996 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1; 9997 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); 9998 return; 9999 } 10000 10001 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ 10002 checkAppendMsg(pCheck, 10003 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 10004 iChild, eType, iParent, ePtrmapType, iPtrmapParent); 10005 } 10006 } 10007 #endif 10008 10009 /* 10010 ** Check the integrity of the freelist or of an overflow page list. 10011 ** Verify that the number of pages on the list is N. 10012 */ 10013 static void checkList( 10014 IntegrityCk *pCheck, /* Integrity checking context */ 10015 int isFreeList, /* True for a freelist. False for overflow page list */ 10016 Pgno iPage, /* Page number for first page in the list */ 10017 u32 N /* Expected number of pages in the list */ 10018 ){ 10019 int i; 10020 u32 expected = N; 10021 int nErrAtStart = pCheck->nErr; 10022 while( iPage!=0 && pCheck->mxErr ){ 10023 DbPage *pOvflPage; 10024 unsigned char *pOvflData; 10025 if( checkRef(pCheck, iPage) ) break; 10026 N--; 10027 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ 10028 checkAppendMsg(pCheck, "failed to get page %d", iPage); 10029 break; 10030 } 10031 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); 10032 if( isFreeList ){ 10033 u32 n = (u32)get4byte(&pOvflData[4]); 10034 #ifndef SQLITE_OMIT_AUTOVACUUM 10035 if( pCheck->pBt->autoVacuum ){ 10036 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); 10037 } 10038 #endif 10039 if( n>pCheck->pBt->usableSize/4-2 ){ 10040 checkAppendMsg(pCheck, 10041 "freelist leaf count too big on page %d", iPage); 10042 N--; 10043 }else{ 10044 for(i=0; i<(int)n; i++){ 10045 Pgno iFreePage = get4byte(&pOvflData[8+i*4]); 10046 #ifndef SQLITE_OMIT_AUTOVACUUM 10047 if( pCheck->pBt->autoVacuum ){ 10048 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); 10049 } 10050 #endif 10051 checkRef(pCheck, iFreePage); 10052 } 10053 N -= n; 10054 } 10055 } 10056 #ifndef SQLITE_OMIT_AUTOVACUUM 10057 else{ 10058 /* If this database supports auto-vacuum and iPage is not the last 10059 ** page in this overflow list, check that the pointer-map entry for 10060 ** the following page matches iPage. 10061 */ 10062 if( pCheck->pBt->autoVacuum && N>0 ){ 10063 i = get4byte(pOvflData); 10064 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); 10065 } 10066 } 10067 #endif 10068 iPage = get4byte(pOvflData); 10069 sqlite3PagerUnref(pOvflPage); 10070 } 10071 if( N && nErrAtStart==pCheck->nErr ){ 10072 checkAppendMsg(pCheck, 10073 "%s is %d but should be %d", 10074 isFreeList ? "size" : "overflow list length", 10075 expected-N, expected); 10076 } 10077 } 10078 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 10079 10080 /* 10081 ** An implementation of a min-heap. 10082 ** 10083 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the 10084 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] 10085 ** and aHeap[N*2+1]. 10086 ** 10087 ** The heap property is this: Every node is less than or equal to both 10088 ** of its daughter nodes. A consequence of the heap property is that the 10089 ** root node aHeap[1] is always the minimum value currently in the heap. 10090 ** 10091 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto 10092 ** the heap, preserving the heap property. The btreeHeapPull() routine 10093 ** removes the root element from the heap (the minimum value in the heap) 10094 ** and then moves other nodes around as necessary to preserve the heap 10095 ** property. 10096 ** 10097 ** This heap is used for cell overlap and coverage testing. Each u32 10098 ** entry represents the span of a cell or freeblock on a btree page. 10099 ** The upper 16 bits are the index of the first byte of a range and the 10100 ** lower 16 bits are the index of the last byte of that range. 10101 */ 10102 static void btreeHeapInsert(u32 *aHeap, u32 x){ 10103 u32 j, i = ++aHeap[0]; 10104 aHeap[i] = x; 10105 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ 10106 x = aHeap[j]; 10107 aHeap[j] = aHeap[i]; 10108 aHeap[i] = x; 10109 i = j; 10110 } 10111 } 10112 static int btreeHeapPull(u32 *aHeap, u32 *pOut){ 10113 u32 j, i, x; 10114 if( (x = aHeap[0])==0 ) return 0; 10115 *pOut = aHeap[1]; 10116 aHeap[1] = aHeap[x]; 10117 aHeap[x] = 0xffffffff; 10118 aHeap[0]--; 10119 i = 1; 10120 while( (j = i*2)<=aHeap[0] ){ 10121 if( aHeap[j]>aHeap[j+1] ) j++; 10122 if( aHeap[i]<aHeap[j] ) break; 10123 x = aHeap[i]; 10124 aHeap[i] = aHeap[j]; 10125 aHeap[j] = x; 10126 i = j; 10127 } 10128 return 1; 10129 } 10130 10131 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 10132 /* 10133 ** Do various sanity checks on a single page of a tree. Return 10134 ** the tree depth. Root pages return 0. Parents of root pages 10135 ** return 1, and so forth. 10136 ** 10137 ** These checks are done: 10138 ** 10139 ** 1. Make sure that cells and freeblocks do not overlap 10140 ** but combine to completely cover the page. 10141 ** 2. Make sure integer cell keys are in order. 10142 ** 3. Check the integrity of overflow pages. 10143 ** 4. Recursively call checkTreePage on all children. 10144 ** 5. Verify that the depth of all children is the same. 10145 */ 10146 static int checkTreePage( 10147 IntegrityCk *pCheck, /* Context for the sanity check */ 10148 Pgno iPage, /* Page number of the page to check */ 10149 i64 *piMinKey, /* Write minimum integer primary key here */ 10150 i64 maxKey /* Error if integer primary key greater than this */ 10151 ){ 10152 MemPage *pPage = 0; /* The page being analyzed */ 10153 int i; /* Loop counter */ 10154 int rc; /* Result code from subroutine call */ 10155 int depth = -1, d2; /* Depth of a subtree */ 10156 int pgno; /* Page number */ 10157 int nFrag; /* Number of fragmented bytes on the page */ 10158 int hdr; /* Offset to the page header */ 10159 int cellStart; /* Offset to the start of the cell pointer array */ 10160 int nCell; /* Number of cells */ 10161 int doCoverageCheck = 1; /* True if cell coverage checking should be done */ 10162 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey 10163 ** False if IPK must be strictly less than maxKey */ 10164 u8 *data; /* Page content */ 10165 u8 *pCell; /* Cell content */ 10166 u8 *pCellIdx; /* Next element of the cell pointer array */ 10167 BtShared *pBt; /* The BtShared object that owns pPage */ 10168 u32 pc; /* Address of a cell */ 10169 u32 usableSize; /* Usable size of the page */ 10170 u32 contentOffset; /* Offset to the start of the cell content area */ 10171 u32 *heap = 0; /* Min-heap used for checking cell coverage */ 10172 u32 x, prev = 0; /* Next and previous entry on the min-heap */ 10173 const char *saved_zPfx = pCheck->zPfx; 10174 int saved_v1 = pCheck->v1; 10175 int saved_v2 = pCheck->v2; 10176 u8 savedIsInit = 0; 10177 10178 /* Check that the page exists 10179 */ 10180 pBt = pCheck->pBt; 10181 usableSize = pBt->usableSize; 10182 if( iPage==0 ) return 0; 10183 if( checkRef(pCheck, iPage) ) return 0; 10184 pCheck->zPfx = "Page %u: "; 10185 pCheck->v1 = iPage; 10186 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){ 10187 checkAppendMsg(pCheck, 10188 "unable to get the page. error code=%d", rc); 10189 goto end_of_check; 10190 } 10191 10192 /* Clear MemPage.isInit to make sure the corruption detection code in 10193 ** btreeInitPage() is executed. */ 10194 savedIsInit = pPage->isInit; 10195 pPage->isInit = 0; 10196 if( (rc = btreeInitPage(pPage))!=0 ){ 10197 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ 10198 checkAppendMsg(pCheck, 10199 "btreeInitPage() returns error code %d", rc); 10200 goto end_of_check; 10201 } 10202 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){ 10203 assert( rc==SQLITE_CORRUPT ); 10204 checkAppendMsg(pCheck, "free space corruption", rc); 10205 goto end_of_check; 10206 } 10207 data = pPage->aData; 10208 hdr = pPage->hdrOffset; 10209 10210 /* Set up for cell analysis */ 10211 pCheck->zPfx = "On tree page %u cell %d: "; 10212 contentOffset = get2byteNotZero(&data[hdr+5]); 10213 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ 10214 10215 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 10216 ** number of cells on the page. */ 10217 nCell = get2byte(&data[hdr+3]); 10218 assert( pPage->nCell==nCell ); 10219 10220 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page 10221 ** immediately follows the b-tree page header. */ 10222 cellStart = hdr + 12 - 4*pPage->leaf; 10223 assert( pPage->aCellIdx==&data[cellStart] ); 10224 pCellIdx = &data[cellStart + 2*(nCell-1)]; 10225 10226 if( !pPage->leaf ){ 10227 /* Analyze the right-child page of internal pages */ 10228 pgno = get4byte(&data[hdr+8]); 10229 #ifndef SQLITE_OMIT_AUTOVACUUM 10230 if( pBt->autoVacuum ){ 10231 pCheck->zPfx = "On page %u at right child: "; 10232 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 10233 } 10234 #endif 10235 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); 10236 keyCanBeEqual = 0; 10237 }else{ 10238 /* For leaf pages, the coverage check will occur in the same loop 10239 ** as the other cell checks, so initialize the heap. */ 10240 heap = pCheck->heap; 10241 heap[0] = 0; 10242 } 10243 10244 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte 10245 ** integer offsets to the cell contents. */ 10246 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ 10247 CellInfo info; 10248 10249 /* Check cell size */ 10250 pCheck->v2 = i; 10251 assert( pCellIdx==&data[cellStart + i*2] ); 10252 pc = get2byteAligned(pCellIdx); 10253 pCellIdx -= 2; 10254 if( pc<contentOffset || pc>usableSize-4 ){ 10255 checkAppendMsg(pCheck, "Offset %d out of range %d..%d", 10256 pc, contentOffset, usableSize-4); 10257 doCoverageCheck = 0; 10258 continue; 10259 } 10260 pCell = &data[pc]; 10261 pPage->xParseCell(pPage, pCell, &info); 10262 if( pc+info.nSize>usableSize ){ 10263 checkAppendMsg(pCheck, "Extends off end of page"); 10264 doCoverageCheck = 0; 10265 continue; 10266 } 10267 10268 /* Check for integer primary key out of range */ 10269 if( pPage->intKey ){ 10270 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ 10271 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); 10272 } 10273 maxKey = info.nKey; 10274 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */ 10275 } 10276 10277 /* Check the content overflow list */ 10278 if( info.nPayload>info.nLocal ){ 10279 u32 nPage; /* Number of pages on the overflow chain */ 10280 Pgno pgnoOvfl; /* First page of the overflow chain */ 10281 assert( pc + info.nSize - 4 <= usableSize ); 10282 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); 10283 pgnoOvfl = get4byte(&pCell[info.nSize - 4]); 10284 #ifndef SQLITE_OMIT_AUTOVACUUM 10285 if( pBt->autoVacuum ){ 10286 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); 10287 } 10288 #endif 10289 checkList(pCheck, 0, pgnoOvfl, nPage); 10290 } 10291 10292 if( !pPage->leaf ){ 10293 /* Check sanity of left child page for internal pages */ 10294 pgno = get4byte(pCell); 10295 #ifndef SQLITE_OMIT_AUTOVACUUM 10296 if( pBt->autoVacuum ){ 10297 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 10298 } 10299 #endif 10300 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); 10301 keyCanBeEqual = 0; 10302 if( d2!=depth ){ 10303 checkAppendMsg(pCheck, "Child page depth differs"); 10304 depth = d2; 10305 } 10306 }else{ 10307 /* Populate the coverage-checking heap for leaf pages */ 10308 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); 10309 } 10310 } 10311 *piMinKey = maxKey; 10312 10313 /* Check for complete coverage of the page 10314 */ 10315 pCheck->zPfx = 0; 10316 if( doCoverageCheck && pCheck->mxErr>0 ){ 10317 /* For leaf pages, the min-heap has already been initialized and the 10318 ** cells have already been inserted. But for internal pages, that has 10319 ** not yet been done, so do it now */ 10320 if( !pPage->leaf ){ 10321 heap = pCheck->heap; 10322 heap[0] = 0; 10323 for(i=nCell-1; i>=0; i--){ 10324 u32 size; 10325 pc = get2byteAligned(&data[cellStart+i*2]); 10326 size = pPage->xCellSize(pPage, &data[pc]); 10327 btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); 10328 } 10329 } 10330 /* Add the freeblocks to the min-heap 10331 ** 10332 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header 10333 ** is the offset of the first freeblock, or zero if there are no 10334 ** freeblocks on the page. 10335 */ 10336 i = get2byte(&data[hdr+1]); 10337 while( i>0 ){ 10338 int size, j; 10339 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ 10340 size = get2byte(&data[i+2]); 10341 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */ 10342 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); 10343 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a 10344 ** big-endian integer which is the offset in the b-tree page of the next 10345 ** freeblock in the chain, or zero if the freeblock is the last on the 10346 ** chain. */ 10347 j = get2byte(&data[i]); 10348 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of 10349 ** increasing offset. */ 10350 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */ 10351 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ 10352 i = j; 10353 } 10354 /* Analyze the min-heap looking for overlap between cells and/or 10355 ** freeblocks, and counting the number of untracked bytes in nFrag. 10356 ** 10357 ** Each min-heap entry is of the form: (start_address<<16)|end_address. 10358 ** There is an implied first entry the covers the page header, the cell 10359 ** pointer index, and the gap between the cell pointer index and the start 10360 ** of cell content. 10361 ** 10362 ** The loop below pulls entries from the min-heap in order and compares 10363 ** the start_address against the previous end_address. If there is an 10364 ** overlap, that means bytes are used multiple times. If there is a gap, 10365 ** that gap is added to the fragmentation count. 10366 */ 10367 nFrag = 0; 10368 prev = contentOffset - 1; /* Implied first min-heap entry */ 10369 while( btreeHeapPull(heap,&x) ){ 10370 if( (prev&0xffff)>=(x>>16) ){ 10371 checkAppendMsg(pCheck, 10372 "Multiple uses for byte %u of page %u", x>>16, iPage); 10373 break; 10374 }else{ 10375 nFrag += (x>>16) - (prev&0xffff) - 1; 10376 prev = x; 10377 } 10378 } 10379 nFrag += usableSize - (prev&0xffff) - 1; 10380 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments 10381 ** is stored in the fifth field of the b-tree page header. 10382 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the 10383 ** number of fragmented free bytes within the cell content area. 10384 */ 10385 if( heap[0]==0 && nFrag!=data[hdr+7] ){ 10386 checkAppendMsg(pCheck, 10387 "Fragmentation of %d bytes reported as %d on page %u", 10388 nFrag, data[hdr+7], iPage); 10389 } 10390 } 10391 10392 end_of_check: 10393 if( !doCoverageCheck ) pPage->isInit = savedIsInit; 10394 releasePage(pPage); 10395 pCheck->zPfx = saved_zPfx; 10396 pCheck->v1 = saved_v1; 10397 pCheck->v2 = saved_v2; 10398 return depth+1; 10399 } 10400 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 10401 10402 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 10403 /* 10404 ** This routine does a complete check of the given BTree file. aRoot[] is 10405 ** an array of pages numbers were each page number is the root page of 10406 ** a table. nRoot is the number of entries in aRoot. 10407 ** 10408 ** A read-only or read-write transaction must be opened before calling 10409 ** this function. 10410 ** 10411 ** Write the number of error seen in *pnErr. Except for some memory 10412 ** allocation errors, an error message held in memory obtained from 10413 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is 10414 ** returned. If a memory allocation error occurs, NULL is returned. 10415 ** 10416 ** If the first entry in aRoot[] is 0, that indicates that the list of 10417 ** root pages is incomplete. This is a "partial integrity-check". This 10418 ** happens when performing an integrity check on a single table. The 10419 ** zero is skipped, of course. But in addition, the freelist checks 10420 ** and the checks to make sure every page is referenced are also skipped, 10421 ** since obviously it is not possible to know which pages are covered by 10422 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist 10423 ** checks are still performed. 10424 */ 10425 char *sqlite3BtreeIntegrityCheck( 10426 sqlite3 *db, /* Database connection that is running the check */ 10427 Btree *p, /* The btree to be checked */ 10428 Pgno *aRoot, /* An array of root pages numbers for individual trees */ 10429 int nRoot, /* Number of entries in aRoot[] */ 10430 int mxErr, /* Stop reporting errors after this many */ 10431 int *pnErr /* Write number of errors seen to this variable */ 10432 ){ 10433 Pgno i; 10434 IntegrityCk sCheck; 10435 BtShared *pBt = p->pBt; 10436 u64 savedDbFlags = pBt->db->flags; 10437 char zErr[100]; 10438 int bPartial = 0; /* True if not checking all btrees */ 10439 int bCkFreelist = 1; /* True to scan the freelist */ 10440 VVA_ONLY( int nRef ); 10441 assert( nRoot>0 ); 10442 10443 /* aRoot[0]==0 means this is a partial check */ 10444 if( aRoot[0]==0 ){ 10445 assert( nRoot>1 ); 10446 bPartial = 1; 10447 if( aRoot[1]!=1 ) bCkFreelist = 0; 10448 } 10449 10450 sqlite3BtreeEnter(p); 10451 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); 10452 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); 10453 assert( nRef>=0 ); 10454 sCheck.db = db; 10455 sCheck.pBt = pBt; 10456 sCheck.pPager = pBt->pPager; 10457 sCheck.nPage = btreePagecount(sCheck.pBt); 10458 sCheck.mxErr = mxErr; 10459 sCheck.nErr = 0; 10460 sCheck.bOomFault = 0; 10461 sCheck.zPfx = 0; 10462 sCheck.v1 = 0; 10463 sCheck.v2 = 0; 10464 sCheck.aPgRef = 0; 10465 sCheck.heap = 0; 10466 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); 10467 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; 10468 if( sCheck.nPage==0 ){ 10469 goto integrity_ck_cleanup; 10470 } 10471 10472 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); 10473 if( !sCheck.aPgRef ){ 10474 sCheck.bOomFault = 1; 10475 goto integrity_ck_cleanup; 10476 } 10477 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); 10478 if( sCheck.heap==0 ){ 10479 sCheck.bOomFault = 1; 10480 goto integrity_ck_cleanup; 10481 } 10482 10483 i = PENDING_BYTE_PAGE(pBt); 10484 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); 10485 10486 /* Check the integrity of the freelist 10487 */ 10488 if( bCkFreelist ){ 10489 sCheck.zPfx = "Main freelist: "; 10490 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), 10491 get4byte(&pBt->pPage1->aData[36])); 10492 sCheck.zPfx = 0; 10493 } 10494 10495 /* Check all the tables. 10496 */ 10497 #ifndef SQLITE_OMIT_AUTOVACUUM 10498 if( !bPartial ){ 10499 if( pBt->autoVacuum ){ 10500 Pgno mx = 0; 10501 Pgno mxInHdr; 10502 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i]; 10503 mxInHdr = get4byte(&pBt->pPage1->aData[52]); 10504 if( mx!=mxInHdr ){ 10505 checkAppendMsg(&sCheck, 10506 "max rootpage (%d) disagrees with header (%d)", 10507 mx, mxInHdr 10508 ); 10509 } 10510 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){ 10511 checkAppendMsg(&sCheck, 10512 "incremental_vacuum enabled with a max rootpage of zero" 10513 ); 10514 } 10515 } 10516 #endif 10517 testcase( pBt->db->flags & SQLITE_CellSizeCk ); 10518 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk; 10519 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ 10520 i64 notUsed; 10521 if( aRoot[i]==0 ) continue; 10522 #ifndef SQLITE_OMIT_AUTOVACUUM 10523 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){ 10524 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); 10525 } 10526 #endif 10527 checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64); 10528 } 10529 pBt->db->flags = savedDbFlags; 10530 10531 /* Make sure every page in the file is referenced 10532 */ 10533 if( !bPartial ){ 10534 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ 10535 #ifdef SQLITE_OMIT_AUTOVACUUM 10536 if( getPageReferenced(&sCheck, i)==0 ){ 10537 checkAppendMsg(&sCheck, "Page %d is never used", i); 10538 } 10539 #else 10540 /* If the database supports auto-vacuum, make sure no tables contain 10541 ** references to pointer-map pages. 10542 */ 10543 if( getPageReferenced(&sCheck, i)==0 && 10544 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ 10545 checkAppendMsg(&sCheck, "Page %d is never used", i); 10546 } 10547 if( getPageReferenced(&sCheck, i)!=0 && 10548 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ 10549 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); 10550 } 10551 #endif 10552 } 10553 } 10554 10555 /* Clean up and report errors. 10556 */ 10557 integrity_ck_cleanup: 10558 sqlite3PageFree(sCheck.heap); 10559 sqlite3_free(sCheck.aPgRef); 10560 if( sCheck.bOomFault ){ 10561 sqlite3_str_reset(&sCheck.errMsg); 10562 sCheck.nErr++; 10563 } 10564 *pnErr = sCheck.nErr; 10565 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg); 10566 /* Make sure this analysis did not leave any unref() pages. */ 10567 assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); 10568 sqlite3BtreeLeave(p); 10569 return sqlite3StrAccumFinish(&sCheck.errMsg); 10570 } 10571 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 10572 10573 /* 10574 ** Return the full pathname of the underlying database file. Return 10575 ** an empty string if the database is in-memory or a TEMP database. 10576 ** 10577 ** The pager filename is invariant as long as the pager is 10578 ** open so it is safe to access without the BtShared mutex. 10579 */ 10580 const char *sqlite3BtreeGetFilename(Btree *p){ 10581 assert( p->pBt->pPager!=0 ); 10582 return sqlite3PagerFilename(p->pBt->pPager, 1); 10583 } 10584 10585 /* 10586 ** Return the pathname of the journal file for this database. The return 10587 ** value of this routine is the same regardless of whether the journal file 10588 ** has been created or not. 10589 ** 10590 ** The pager journal filename is invariant as long as the pager is 10591 ** open so it is safe to access without the BtShared mutex. 10592 */ 10593 const char *sqlite3BtreeGetJournalname(Btree *p){ 10594 assert( p->pBt->pPager!=0 ); 10595 return sqlite3PagerJournalname(p->pBt->pPager); 10596 } 10597 10598 /* 10599 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE 10600 ** to describe the current transaction state of Btree p. 10601 */ 10602 int sqlite3BtreeTxnState(Btree *p){ 10603 assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); 10604 return p ? p->inTrans : 0; 10605 } 10606 10607 #ifndef SQLITE_OMIT_WAL 10608 /* 10609 ** Run a checkpoint on the Btree passed as the first argument. 10610 ** 10611 ** Return SQLITE_LOCKED if this or any other connection has an open 10612 ** transaction on the shared-cache the argument Btree is connected to. 10613 ** 10614 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. 10615 */ 10616 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ 10617 int rc = SQLITE_OK; 10618 if( p ){ 10619 BtShared *pBt = p->pBt; 10620 sqlite3BtreeEnter(p); 10621 if( pBt->inTransaction!=TRANS_NONE ){ 10622 rc = SQLITE_LOCKED; 10623 }else{ 10624 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); 10625 } 10626 sqlite3BtreeLeave(p); 10627 } 10628 return rc; 10629 } 10630 #endif 10631 10632 /* 10633 ** Return true if there is currently a backup running on Btree p. 10634 */ 10635 int sqlite3BtreeIsInBackup(Btree *p){ 10636 assert( p ); 10637 assert( sqlite3_mutex_held(p->db->mutex) ); 10638 return p->nBackup!=0; 10639 } 10640 10641 /* 10642 ** This function returns a pointer to a blob of memory associated with 10643 ** a single shared-btree. The memory is used by client code for its own 10644 ** purposes (for example, to store a high-level schema associated with 10645 ** the shared-btree). The btree layer manages reference counting issues. 10646 ** 10647 ** The first time this is called on a shared-btree, nBytes bytes of memory 10648 ** are allocated, zeroed, and returned to the caller. For each subsequent 10649 ** call the nBytes parameter is ignored and a pointer to the same blob 10650 ** of memory returned. 10651 ** 10652 ** If the nBytes parameter is 0 and the blob of memory has not yet been 10653 ** allocated, a null pointer is returned. If the blob has already been 10654 ** allocated, it is returned as normal. 10655 ** 10656 ** Just before the shared-btree is closed, the function passed as the 10657 ** xFree argument when the memory allocation was made is invoked on the 10658 ** blob of allocated memory. The xFree function should not call sqlite3_free() 10659 ** on the memory, the btree layer does that. 10660 */ 10661 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ 10662 BtShared *pBt = p->pBt; 10663 sqlite3BtreeEnter(p); 10664 if( !pBt->pSchema && nBytes ){ 10665 pBt->pSchema = sqlite3DbMallocZero(0, nBytes); 10666 pBt->xFreeSchema = xFree; 10667 } 10668 sqlite3BtreeLeave(p); 10669 return pBt->pSchema; 10670 } 10671 10672 /* 10673 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 10674 ** btree as the argument handle holds an exclusive lock on the 10675 ** sqlite_schema table. Otherwise SQLITE_OK. 10676 */ 10677 int sqlite3BtreeSchemaLocked(Btree *p){ 10678 int rc; 10679 assert( sqlite3_mutex_held(p->db->mutex) ); 10680 sqlite3BtreeEnter(p); 10681 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); 10682 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); 10683 sqlite3BtreeLeave(p); 10684 return rc; 10685 } 10686 10687 10688 #ifndef SQLITE_OMIT_SHARED_CACHE 10689 /* 10690 ** Obtain a lock on the table whose root page is iTab. The 10691 ** lock is a write lock if isWritelock is true or a read lock 10692 ** if it is false. 10693 */ 10694 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ 10695 int rc = SQLITE_OK; 10696 assert( p->inTrans!=TRANS_NONE ); 10697 if( p->sharable ){ 10698 u8 lockType = READ_LOCK + isWriteLock; 10699 assert( READ_LOCK+1==WRITE_LOCK ); 10700 assert( isWriteLock==0 || isWriteLock==1 ); 10701 10702 sqlite3BtreeEnter(p); 10703 rc = querySharedCacheTableLock(p, iTab, lockType); 10704 if( rc==SQLITE_OK ){ 10705 rc = setSharedCacheTableLock(p, iTab, lockType); 10706 } 10707 sqlite3BtreeLeave(p); 10708 } 10709 return rc; 10710 } 10711 #endif 10712 10713 #ifndef SQLITE_OMIT_INCRBLOB 10714 /* 10715 ** Argument pCsr must be a cursor opened for writing on an 10716 ** INTKEY table currently pointing at a valid table entry. 10717 ** This function modifies the data stored as part of that entry. 10718 ** 10719 ** Only the data content may only be modified, it is not possible to 10720 ** change the length of the data stored. If this function is called with 10721 ** parameters that attempt to write past the end of the existing data, 10722 ** no modifications are made and SQLITE_CORRUPT is returned. 10723 */ 10724 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ 10725 int rc; 10726 assert( cursorOwnsBtShared(pCsr) ); 10727 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); 10728 assert( pCsr->curFlags & BTCF_Incrblob ); 10729 10730 rc = restoreCursorPosition(pCsr); 10731 if( rc!=SQLITE_OK ){ 10732 return rc; 10733 } 10734 assert( pCsr->eState!=CURSOR_REQUIRESEEK ); 10735 if( pCsr->eState!=CURSOR_VALID ){ 10736 return SQLITE_ABORT; 10737 } 10738 10739 /* Save the positions of all other cursors open on this table. This is 10740 ** required in case any of them are holding references to an xFetch 10741 ** version of the b-tree page modified by the accessPayload call below. 10742 ** 10743 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() 10744 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence 10745 ** saveAllCursors can only return SQLITE_OK. 10746 */ 10747 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); 10748 assert( rc==SQLITE_OK ); 10749 10750 /* Check some assumptions: 10751 ** (a) the cursor is open for writing, 10752 ** (b) there is a read/write transaction open, 10753 ** (c) the connection holds a write-lock on the table (if required), 10754 ** (d) there are no conflicting read-locks, and 10755 ** (e) the cursor points at a valid row of an intKey table. 10756 */ 10757 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ 10758 return SQLITE_READONLY; 10759 } 10760 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 10761 && pCsr->pBt->inTransaction==TRANS_WRITE ); 10762 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); 10763 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); 10764 assert( pCsr->pPage->intKey ); 10765 10766 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); 10767 } 10768 10769 /* 10770 ** Mark this cursor as an incremental blob cursor. 10771 */ 10772 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ 10773 pCur->curFlags |= BTCF_Incrblob; 10774 pCur->pBtree->hasIncrblobCur = 1; 10775 } 10776 #endif 10777 10778 /* 10779 ** Set both the "read version" (single byte at byte offset 18) and 10780 ** "write version" (single byte at byte offset 19) fields in the database 10781 ** header to iVersion. 10782 */ 10783 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ 10784 BtShared *pBt = pBtree->pBt; 10785 int rc; /* Return code */ 10786 10787 assert( iVersion==1 || iVersion==2 ); 10788 10789 /* If setting the version fields to 1, do not automatically open the 10790 ** WAL connection, even if the version fields are currently set to 2. 10791 */ 10792 pBt->btsFlags &= ~BTS_NO_WAL; 10793 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; 10794 10795 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0); 10796 if( rc==SQLITE_OK ){ 10797 u8 *aData = pBt->pPage1->aData; 10798 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ 10799 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0); 10800 if( rc==SQLITE_OK ){ 10801 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 10802 if( rc==SQLITE_OK ){ 10803 aData[18] = (u8)iVersion; 10804 aData[19] = (u8)iVersion; 10805 } 10806 } 10807 } 10808 } 10809 10810 pBt->btsFlags &= ~BTS_NO_WAL; 10811 return rc; 10812 } 10813 10814 /* 10815 ** Return true if the cursor has a hint specified. This routine is 10816 ** only used from within assert() statements 10817 */ 10818 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ 10819 return (pCsr->hints & mask)!=0; 10820 } 10821 10822 /* 10823 ** Return true if the given Btree is read-only. 10824 */ 10825 int sqlite3BtreeIsReadonly(Btree *p){ 10826 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; 10827 } 10828 10829 /* 10830 ** Return the size of the header added to each page by this module. 10831 */ 10832 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } 10833 10834 #if !defined(SQLITE_OMIT_SHARED_CACHE) 10835 /* 10836 ** Return true if the Btree passed as the only argument is sharable. 10837 */ 10838 int sqlite3BtreeSharable(Btree *p){ 10839 return p->sharable; 10840 } 10841 10842 /* 10843 ** Return the number of connections to the BtShared object accessed by 10844 ** the Btree handle passed as the only argument. For private caches 10845 ** this is always 1. For shared caches it may be 1 or greater. 10846 */ 10847 int sqlite3BtreeConnectionCount(Btree *p){ 10848 testcase( p->sharable ); 10849 return p->pBt->nRef; 10850 } 10851 #endif 10852