1 /* 2 ** 2004 April 6 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** This file implements an external (disk-based) database using BTrees. 13 ** See the header comment on "btreeInt.h" for additional information. 14 ** Including a description of file format and an overview of operation. 15 */ 16 #include "btreeInt.h" 17 18 /* 19 ** The header string that appears at the beginning of every 20 ** SQLite database. 21 */ 22 static const char zMagicHeader[] = SQLITE_FILE_HEADER; 23 24 /* 25 ** Set this global variable to 1 to enable tracing using the TRACE 26 ** macro. 27 */ 28 #if 0 29 int sqlite3BtreeTrace=1; /* True to enable tracing */ 30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} 31 #else 32 # define TRACE(X) 33 #endif 34 35 /* 36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes. 37 ** But if the value is zero, make it 65536. 38 ** 39 ** This routine is used to extract the "offset to cell content area" value 40 ** from the header of a btree page. If the page size is 65536 and the page 41 ** is empty, the offset should be 65536, but the 2-byte value stores zero. 42 ** This routine makes the necessary adjustment to 65536. 43 */ 44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) 45 46 /* 47 ** Values passed as the 5th argument to allocateBtreePage() 48 */ 49 #define BTALLOC_ANY 0 /* Allocate any page */ 50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */ 51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */ 52 53 /* 54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 55 ** defined, or 0 if it is. For example: 56 ** 57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); 58 */ 59 #ifndef SQLITE_OMIT_AUTOVACUUM 60 #define IfNotOmitAV(expr) (expr) 61 #else 62 #define IfNotOmitAV(expr) 0 63 #endif 64 65 #ifndef SQLITE_OMIT_SHARED_CACHE 66 /* 67 ** A list of BtShared objects that are eligible for participation 68 ** in shared cache. This variable has file scope during normal builds, 69 ** but the test harness needs to access it so we make it global for 70 ** test builds. 71 ** 72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. 73 */ 74 #ifdef SQLITE_TEST 75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; 76 #else 77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; 78 #endif 79 #endif /* SQLITE_OMIT_SHARED_CACHE */ 80 81 #ifndef SQLITE_OMIT_SHARED_CACHE 82 /* 83 ** Enable or disable the shared pager and schema features. 84 ** 85 ** This routine has no effect on existing database connections. 86 ** The shared cache setting effects only future calls to 87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). 88 */ 89 int sqlite3_enable_shared_cache(int enable){ 90 sqlite3GlobalConfig.sharedCacheEnabled = enable; 91 return SQLITE_OK; 92 } 93 #endif 94 95 96 97 #ifdef SQLITE_OMIT_SHARED_CACHE 98 /* 99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), 100 ** and clearAllSharedCacheTableLocks() 101 ** manipulate entries in the BtShared.pLock linked list used to store 102 ** shared-cache table level locks. If the library is compiled with the 103 ** shared-cache feature disabled, then there is only ever one user 104 ** of each BtShared structure and so this locking is not necessary. 105 ** So define the lock related functions as no-ops. 106 */ 107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK 108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK 109 #define clearAllSharedCacheTableLocks(a) 110 #define downgradeAllSharedCacheTableLocks(a) 111 #define hasSharedCacheTableLock(a,b,c,d) 1 112 #define hasReadConflicts(a, b) 0 113 #endif 114 115 /* 116 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single 117 ** (MemPage*) as an argument. The (MemPage*) must not be NULL. 118 ** 119 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to 120 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message 121 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented 122 ** with the page number and filename associated with the (MemPage*). 123 */ 124 #ifdef SQLITE_DEBUG 125 int corruptPageError(int lineno, MemPage *p){ 126 char *zMsg; 127 sqlite3BeginBenignMalloc(); 128 zMsg = sqlite3_mprintf("database corruption page %d of %s", 129 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0) 130 ); 131 sqlite3EndBenignMalloc(); 132 if( zMsg ){ 133 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); 134 } 135 sqlite3_free(zMsg); 136 return SQLITE_CORRUPT_BKPT; 137 } 138 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage) 139 #else 140 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno) 141 #endif 142 143 #ifndef SQLITE_OMIT_SHARED_CACHE 144 145 #ifdef SQLITE_DEBUG 146 /* 147 **** This function is only used as part of an assert() statement. *** 148 ** 149 ** Check to see if pBtree holds the required locks to read or write to the 150 ** table with root page iRoot. Return 1 if it does and 0 if not. 151 ** 152 ** For example, when writing to a table with root-page iRoot via 153 ** Btree connection pBtree: 154 ** 155 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); 156 ** 157 ** When writing to an index that resides in a sharable database, the 158 ** caller should have first obtained a lock specifying the root page of 159 ** the corresponding table. This makes things a bit more complicated, 160 ** as this module treats each table as a separate structure. To determine 161 ** the table corresponding to the index being written, this 162 ** function has to search through the database schema. 163 ** 164 ** Instead of a lock on the table/index rooted at page iRoot, the caller may 165 ** hold a write-lock on the schema table (root page 1). This is also 166 ** acceptable. 167 */ 168 static int hasSharedCacheTableLock( 169 Btree *pBtree, /* Handle that must hold lock */ 170 Pgno iRoot, /* Root page of b-tree */ 171 int isIndex, /* True if iRoot is the root of an index b-tree */ 172 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ 173 ){ 174 Schema *pSchema = (Schema *)pBtree->pBt->pSchema; 175 Pgno iTab = 0; 176 BtLock *pLock; 177 178 /* If this database is not shareable, or if the client is reading 179 ** and has the read-uncommitted flag set, then no lock is required. 180 ** Return true immediately. 181 */ 182 if( (pBtree->sharable==0) 183 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit)) 184 ){ 185 return 1; 186 } 187 188 /* If the client is reading or writing an index and the schema is 189 ** not loaded, then it is too difficult to actually check to see if 190 ** the correct locks are held. So do not bother - just return true. 191 ** This case does not come up very often anyhow. 192 */ 193 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ 194 return 1; 195 } 196 197 /* Figure out the root-page that the lock should be held on. For table 198 ** b-trees, this is just the root page of the b-tree being read or 199 ** written. For index b-trees, it is the root page of the associated 200 ** table. */ 201 if( isIndex ){ 202 HashElem *p; 203 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ 204 Index *pIdx = (Index *)sqliteHashData(p); 205 if( pIdx->tnum==(int)iRoot ){ 206 if( iTab ){ 207 /* Two or more indexes share the same root page. There must 208 ** be imposter tables. So just return true. The assert is not 209 ** useful in that case. */ 210 return 1; 211 } 212 iTab = pIdx->pTable->tnum; 213 } 214 } 215 }else{ 216 iTab = iRoot; 217 } 218 219 /* Search for the required lock. Either a write-lock on root-page iTab, a 220 ** write-lock on the schema table, or (if the client is reading) a 221 ** read-lock on iTab will suffice. Return 1 if any of these are found. */ 222 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ 223 if( pLock->pBtree==pBtree 224 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) 225 && pLock->eLock>=eLockType 226 ){ 227 return 1; 228 } 229 } 230 231 /* Failed to find the required lock. */ 232 return 0; 233 } 234 #endif /* SQLITE_DEBUG */ 235 236 #ifdef SQLITE_DEBUG 237 /* 238 **** This function may be used as part of assert() statements only. **** 239 ** 240 ** Return true if it would be illegal for pBtree to write into the 241 ** table or index rooted at iRoot because other shared connections are 242 ** simultaneously reading that same table or index. 243 ** 244 ** It is illegal for pBtree to write if some other Btree object that 245 ** shares the same BtShared object is currently reading or writing 246 ** the iRoot table. Except, if the other Btree object has the 247 ** read-uncommitted flag set, then it is OK for the other object to 248 ** have a read cursor. 249 ** 250 ** For example, before writing to any part of the table or index 251 ** rooted at page iRoot, one should call: 252 ** 253 ** assert( !hasReadConflicts(pBtree, iRoot) ); 254 */ 255 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ 256 BtCursor *p; 257 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 258 if( p->pgnoRoot==iRoot 259 && p->pBtree!=pBtree 260 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit) 261 ){ 262 return 1; 263 } 264 } 265 return 0; 266 } 267 #endif /* #ifdef SQLITE_DEBUG */ 268 269 /* 270 ** Query to see if Btree handle p may obtain a lock of type eLock 271 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return 272 ** SQLITE_OK if the lock may be obtained (by calling 273 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. 274 */ 275 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ 276 BtShared *pBt = p->pBt; 277 BtLock *pIter; 278 279 assert( sqlite3BtreeHoldsMutex(p) ); 280 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 281 assert( p->db!=0 ); 282 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 ); 283 284 /* If requesting a write-lock, then the Btree must have an open write 285 ** transaction on this file. And, obviously, for this to be so there 286 ** must be an open write transaction on the file itself. 287 */ 288 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); 289 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); 290 291 /* This routine is a no-op if the shared-cache is not enabled */ 292 if( !p->sharable ){ 293 return SQLITE_OK; 294 } 295 296 /* If some other connection is holding an exclusive lock, the 297 ** requested lock may not be obtained. 298 */ 299 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ 300 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); 301 return SQLITE_LOCKED_SHAREDCACHE; 302 } 303 304 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 305 /* The condition (pIter->eLock!=eLock) in the following if(...) 306 ** statement is a simplification of: 307 ** 308 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) 309 ** 310 ** since we know that if eLock==WRITE_LOCK, then no other connection 311 ** may hold a WRITE_LOCK on any table in this file (since there can 312 ** only be a single writer). 313 */ 314 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); 315 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); 316 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ 317 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); 318 if( eLock==WRITE_LOCK ){ 319 assert( p==pBt->pWriter ); 320 pBt->btsFlags |= BTS_PENDING; 321 } 322 return SQLITE_LOCKED_SHAREDCACHE; 323 } 324 } 325 return SQLITE_OK; 326 } 327 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 328 329 #ifndef SQLITE_OMIT_SHARED_CACHE 330 /* 331 ** Add a lock on the table with root-page iTable to the shared-btree used 332 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 333 ** WRITE_LOCK. 334 ** 335 ** This function assumes the following: 336 ** 337 ** (a) The specified Btree object p is connected to a sharable 338 ** database (one with the BtShared.sharable flag set), and 339 ** 340 ** (b) No other Btree objects hold a lock that conflicts 341 ** with the requested lock (i.e. querySharedCacheTableLock() has 342 ** already been called and returned SQLITE_OK). 343 ** 344 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 345 ** is returned if a malloc attempt fails. 346 */ 347 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ 348 BtShared *pBt = p->pBt; 349 BtLock *pLock = 0; 350 BtLock *pIter; 351 352 assert( sqlite3BtreeHoldsMutex(p) ); 353 assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); 354 assert( p->db!=0 ); 355 356 /* A connection with the read-uncommitted flag set will never try to 357 ** obtain a read-lock using this function. The only read-lock obtained 358 ** by a connection in read-uncommitted mode is on the sqlite_master 359 ** table, and that lock is obtained in BtreeBeginTrans(). */ 360 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK ); 361 362 /* This function should only be called on a sharable b-tree after it 363 ** has been determined that no other b-tree holds a conflicting lock. */ 364 assert( p->sharable ); 365 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); 366 367 /* First search the list for an existing lock on this table. */ 368 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 369 if( pIter->iTable==iTable && pIter->pBtree==p ){ 370 pLock = pIter; 371 break; 372 } 373 } 374 375 /* If the above search did not find a BtLock struct associating Btree p 376 ** with table iTable, allocate one and link it into the list. 377 */ 378 if( !pLock ){ 379 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); 380 if( !pLock ){ 381 return SQLITE_NOMEM_BKPT; 382 } 383 pLock->iTable = iTable; 384 pLock->pBtree = p; 385 pLock->pNext = pBt->pLock; 386 pBt->pLock = pLock; 387 } 388 389 /* Set the BtLock.eLock variable to the maximum of the current lock 390 ** and the requested lock. This means if a write-lock was already held 391 ** and a read-lock requested, we don't incorrectly downgrade the lock. 392 */ 393 assert( WRITE_LOCK>READ_LOCK ); 394 if( eLock>pLock->eLock ){ 395 pLock->eLock = eLock; 396 } 397 398 return SQLITE_OK; 399 } 400 #endif /* !SQLITE_OMIT_SHARED_CACHE */ 401 402 #ifndef SQLITE_OMIT_SHARED_CACHE 403 /* 404 ** Release all the table locks (locks obtained via calls to 405 ** the setSharedCacheTableLock() procedure) held by Btree object p. 406 ** 407 ** This function assumes that Btree p has an open read or write 408 ** transaction. If it does not, then the BTS_PENDING flag 409 ** may be incorrectly cleared. 410 */ 411 static void clearAllSharedCacheTableLocks(Btree *p){ 412 BtShared *pBt = p->pBt; 413 BtLock **ppIter = &pBt->pLock; 414 415 assert( sqlite3BtreeHoldsMutex(p) ); 416 assert( p->sharable || 0==*ppIter ); 417 assert( p->inTrans>0 ); 418 419 while( *ppIter ){ 420 BtLock *pLock = *ppIter; 421 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); 422 assert( pLock->pBtree->inTrans>=pLock->eLock ); 423 if( pLock->pBtree==p ){ 424 *ppIter = pLock->pNext; 425 assert( pLock->iTable!=1 || pLock==&p->lock ); 426 if( pLock->iTable!=1 ){ 427 sqlite3_free(pLock); 428 } 429 }else{ 430 ppIter = &pLock->pNext; 431 } 432 } 433 434 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); 435 if( pBt->pWriter==p ){ 436 pBt->pWriter = 0; 437 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 438 }else if( pBt->nTransaction==2 ){ 439 /* This function is called when Btree p is concluding its 440 ** transaction. If there currently exists a writer, and p is not 441 ** that writer, then the number of locks held by connections other 442 ** than the writer must be about to drop to zero. In this case 443 ** set the BTS_PENDING flag to 0. 444 ** 445 ** If there is not currently a writer, then BTS_PENDING must 446 ** be zero already. So this next line is harmless in that case. 447 */ 448 pBt->btsFlags &= ~BTS_PENDING; 449 } 450 } 451 452 /* 453 ** This function changes all write-locks held by Btree p into read-locks. 454 */ 455 static void downgradeAllSharedCacheTableLocks(Btree *p){ 456 BtShared *pBt = p->pBt; 457 if( pBt->pWriter==p ){ 458 BtLock *pLock; 459 pBt->pWriter = 0; 460 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); 461 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ 462 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); 463 pLock->eLock = READ_LOCK; 464 } 465 } 466 } 467 468 #endif /* SQLITE_OMIT_SHARED_CACHE */ 469 470 static void releasePage(MemPage *pPage); /* Forward reference */ 471 static void releasePageOne(MemPage *pPage); /* Forward reference */ 472 static void releasePageNotNull(MemPage *pPage); /* Forward reference */ 473 474 /* 475 ***** This routine is used inside of assert() only **** 476 ** 477 ** Verify that the cursor holds the mutex on its BtShared 478 */ 479 #ifdef SQLITE_DEBUG 480 static int cursorHoldsMutex(BtCursor *p){ 481 return sqlite3_mutex_held(p->pBt->mutex); 482 } 483 484 /* Verify that the cursor and the BtShared agree about what is the current 485 ** database connetion. This is important in shared-cache mode. If the database 486 ** connection pointers get out-of-sync, it is possible for routines like 487 ** btreeInitPage() to reference an stale connection pointer that references a 488 ** a connection that has already closed. This routine is used inside assert() 489 ** statements only and for the purpose of double-checking that the btree code 490 ** does keep the database connection pointers up-to-date. 491 */ 492 static int cursorOwnsBtShared(BtCursor *p){ 493 assert( cursorHoldsMutex(p) ); 494 return (p->pBtree->db==p->pBt->db); 495 } 496 #endif 497 498 /* 499 ** Invalidate the overflow cache of the cursor passed as the first argument. 500 ** on the shared btree structure pBt. 501 */ 502 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) 503 504 /* 505 ** Invalidate the overflow page-list cache for all cursors opened 506 ** on the shared btree structure pBt. 507 */ 508 static void invalidateAllOverflowCache(BtShared *pBt){ 509 BtCursor *p; 510 assert( sqlite3_mutex_held(pBt->mutex) ); 511 for(p=pBt->pCursor; p; p=p->pNext){ 512 invalidateOverflowCache(p); 513 } 514 } 515 516 #ifndef SQLITE_OMIT_INCRBLOB 517 /* 518 ** This function is called before modifying the contents of a table 519 ** to invalidate any incrblob cursors that are open on the 520 ** row or one of the rows being modified. 521 ** 522 ** If argument isClearTable is true, then the entire contents of the 523 ** table is about to be deleted. In this case invalidate all incrblob 524 ** cursors open on any row within the table with root-page pgnoRoot. 525 ** 526 ** Otherwise, if argument isClearTable is false, then the row with 527 ** rowid iRow is being replaced or deleted. In this case invalidate 528 ** only those incrblob cursors open on that specific row. 529 */ 530 static void invalidateIncrblobCursors( 531 Btree *pBtree, /* The database file to check */ 532 Pgno pgnoRoot, /* The table that might be changing */ 533 i64 iRow, /* The rowid that might be changing */ 534 int isClearTable /* True if all rows are being deleted */ 535 ){ 536 BtCursor *p; 537 if( pBtree->hasIncrblobCur==0 ) return; 538 assert( sqlite3BtreeHoldsMutex(pBtree) ); 539 pBtree->hasIncrblobCur = 0; 540 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 541 if( (p->curFlags & BTCF_Incrblob)!=0 ){ 542 pBtree->hasIncrblobCur = 1; 543 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){ 544 p->eState = CURSOR_INVALID; 545 } 546 } 547 } 548 } 549 550 #else 551 /* Stub function when INCRBLOB is omitted */ 552 #define invalidateIncrblobCursors(w,x,y,z) 553 #endif /* SQLITE_OMIT_INCRBLOB */ 554 555 /* 556 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 557 ** when a page that previously contained data becomes a free-list leaf 558 ** page. 559 ** 560 ** The BtShared.pHasContent bitvec exists to work around an obscure 561 ** bug caused by the interaction of two useful IO optimizations surrounding 562 ** free-list leaf pages: 563 ** 564 ** 1) When all data is deleted from a page and the page becomes 565 ** a free-list leaf page, the page is not written to the database 566 ** (as free-list leaf pages contain no meaningful data). Sometimes 567 ** such a page is not even journalled (as it will not be modified, 568 ** why bother journalling it?). 569 ** 570 ** 2) When a free-list leaf page is reused, its content is not read 571 ** from the database or written to the journal file (why should it 572 ** be, if it is not at all meaningful?). 573 ** 574 ** By themselves, these optimizations work fine and provide a handy 575 ** performance boost to bulk delete or insert operations. However, if 576 ** a page is moved to the free-list and then reused within the same 577 ** transaction, a problem comes up. If the page is not journalled when 578 ** it is moved to the free-list and it is also not journalled when it 579 ** is extracted from the free-list and reused, then the original data 580 ** may be lost. In the event of a rollback, it may not be possible 581 ** to restore the database to its original configuration. 582 ** 583 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 584 ** moved to become a free-list leaf page, the corresponding bit is 585 ** set in the bitvec. Whenever a leaf page is extracted from the free-list, 586 ** optimization 2 above is omitted if the corresponding bit is already 587 ** set in BtShared.pHasContent. The contents of the bitvec are cleared 588 ** at the end of every transaction. 589 */ 590 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ 591 int rc = SQLITE_OK; 592 if( !pBt->pHasContent ){ 593 assert( pgno<=pBt->nPage ); 594 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); 595 if( !pBt->pHasContent ){ 596 rc = SQLITE_NOMEM_BKPT; 597 } 598 } 599 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ 600 rc = sqlite3BitvecSet(pBt->pHasContent, pgno); 601 } 602 return rc; 603 } 604 605 /* 606 ** Query the BtShared.pHasContent vector. 607 ** 608 ** This function is called when a free-list leaf page is removed from the 609 ** free-list for reuse. It returns false if it is safe to retrieve the 610 ** page from the pager layer with the 'no-content' flag set. True otherwise. 611 */ 612 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ 613 Bitvec *p = pBt->pHasContent; 614 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno)); 615 } 616 617 /* 618 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be 619 ** invoked at the conclusion of each write-transaction. 620 */ 621 static void btreeClearHasContent(BtShared *pBt){ 622 sqlite3BitvecDestroy(pBt->pHasContent); 623 pBt->pHasContent = 0; 624 } 625 626 /* 627 ** Release all of the apPage[] pages for a cursor. 628 */ 629 static void btreeReleaseAllCursorPages(BtCursor *pCur){ 630 int i; 631 if( pCur->iPage>=0 ){ 632 for(i=0; i<pCur->iPage; i++){ 633 releasePageNotNull(pCur->apPage[i]); 634 } 635 releasePageNotNull(pCur->pPage); 636 pCur->iPage = -1; 637 } 638 } 639 640 /* 641 ** The cursor passed as the only argument must point to a valid entry 642 ** when this function is called (i.e. have eState==CURSOR_VALID). This 643 ** function saves the current cursor key in variables pCur->nKey and 644 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 645 ** code otherwise. 646 ** 647 ** If the cursor is open on an intkey table, then the integer key 648 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to 649 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 650 ** set to point to a malloced buffer pCur->nKey bytes in size containing 651 ** the key. 652 */ 653 static int saveCursorKey(BtCursor *pCur){ 654 int rc = SQLITE_OK; 655 assert( CURSOR_VALID==pCur->eState ); 656 assert( 0==pCur->pKey ); 657 assert( cursorHoldsMutex(pCur) ); 658 659 if( pCur->curIntKey ){ 660 /* Only the rowid is required for a table btree */ 661 pCur->nKey = sqlite3BtreeIntegerKey(pCur); 662 }else{ 663 /* For an index btree, save the complete key content. It is possible 664 ** that the current key is corrupt. In that case, it is possible that 665 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by 666 ** up to the size of 1 varint plus 1 8-byte value when the cursor 667 ** position is restored. Hence the 17 bytes of padding allocated 668 ** below. */ 669 void *pKey; 670 pCur->nKey = sqlite3BtreePayloadSize(pCur); 671 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 ); 672 if( pKey ){ 673 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); 674 if( rc==SQLITE_OK ){ 675 memset(((u8*)pKey)+pCur->nKey, 0, 9+8); 676 pCur->pKey = pKey; 677 }else{ 678 sqlite3_free(pKey); 679 } 680 }else{ 681 rc = SQLITE_NOMEM_BKPT; 682 } 683 } 684 assert( !pCur->curIntKey || !pCur->pKey ); 685 return rc; 686 } 687 688 /* 689 ** Save the current cursor position in the variables BtCursor.nKey 690 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. 691 ** 692 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) 693 ** prior to calling this routine. 694 */ 695 static int saveCursorPosition(BtCursor *pCur){ 696 int rc; 697 698 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); 699 assert( 0==pCur->pKey ); 700 assert( cursorHoldsMutex(pCur) ); 701 702 if( pCur->curFlags & BTCF_Pinned ){ 703 return SQLITE_CONSTRAINT_PINNED; 704 } 705 if( pCur->eState==CURSOR_SKIPNEXT ){ 706 pCur->eState = CURSOR_VALID; 707 }else{ 708 pCur->skipNext = 0; 709 } 710 711 rc = saveCursorKey(pCur); 712 if( rc==SQLITE_OK ){ 713 btreeReleaseAllCursorPages(pCur); 714 pCur->eState = CURSOR_REQUIRESEEK; 715 } 716 717 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); 718 return rc; 719 } 720 721 /* Forward reference */ 722 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); 723 724 /* 725 ** Save the positions of all cursors (except pExcept) that are open on 726 ** the table with root-page iRoot. "Saving the cursor position" means that 727 ** the location in the btree is remembered in such a way that it can be 728 ** moved back to the same spot after the btree has been modified. This 729 ** routine is called just before cursor pExcept is used to modify the 730 ** table, for example in BtreeDelete() or BtreeInsert(). 731 ** 732 ** If there are two or more cursors on the same btree, then all such 733 ** cursors should have their BTCF_Multiple flag set. The btreeCursor() 734 ** routine enforces that rule. This routine only needs to be called in 735 ** the uncommon case when pExpect has the BTCF_Multiple flag set. 736 ** 737 ** If pExpect!=NULL and if no other cursors are found on the same root-page, 738 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another 739 ** pointless call to this routine. 740 ** 741 ** Implementation note: This routine merely checks to see if any cursors 742 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) 743 ** event that cursors are in need to being saved. 744 */ 745 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ 746 BtCursor *p; 747 assert( sqlite3_mutex_held(pBt->mutex) ); 748 assert( pExcept==0 || pExcept->pBt==pBt ); 749 for(p=pBt->pCursor; p; p=p->pNext){ 750 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; 751 } 752 if( p ) return saveCursorsOnList(p, iRoot, pExcept); 753 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; 754 return SQLITE_OK; 755 } 756 757 /* This helper routine to saveAllCursors does the actual work of saving 758 ** the cursors if and when a cursor is found that actually requires saving. 759 ** The common case is that no cursors need to be saved, so this routine is 760 ** broken out from its caller to avoid unnecessary stack pointer movement. 761 */ 762 static int SQLITE_NOINLINE saveCursorsOnList( 763 BtCursor *p, /* The first cursor that needs saving */ 764 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ 765 BtCursor *pExcept /* Do not save this cursor */ 766 ){ 767 do{ 768 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ 769 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 770 int rc = saveCursorPosition(p); 771 if( SQLITE_OK!=rc ){ 772 return rc; 773 } 774 }else{ 775 testcase( p->iPage>=0 ); 776 btreeReleaseAllCursorPages(p); 777 } 778 } 779 p = p->pNext; 780 }while( p ); 781 return SQLITE_OK; 782 } 783 784 /* 785 ** Clear the current cursor position. 786 */ 787 void sqlite3BtreeClearCursor(BtCursor *pCur){ 788 assert( cursorHoldsMutex(pCur) ); 789 sqlite3_free(pCur->pKey); 790 pCur->pKey = 0; 791 pCur->eState = CURSOR_INVALID; 792 } 793 794 /* 795 ** In this version of BtreeMoveto, pKey is a packed index record 796 ** such as is generated by the OP_MakeRecord opcode. Unpack the 797 ** record and then call BtreeMovetoUnpacked() to do the work. 798 */ 799 static int btreeMoveto( 800 BtCursor *pCur, /* Cursor open on the btree to be searched */ 801 const void *pKey, /* Packed key if the btree is an index */ 802 i64 nKey, /* Integer key for tables. Size of pKey for indices */ 803 int bias, /* Bias search to the high end */ 804 int *pRes /* Write search results here */ 805 ){ 806 int rc; /* Status code */ 807 UnpackedRecord *pIdxKey; /* Unpacked index key */ 808 809 if( pKey ){ 810 KeyInfo *pKeyInfo = pCur->pKeyInfo; 811 assert( nKey==(i64)(int)nKey ); 812 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); 813 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; 814 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); 815 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ 816 rc = SQLITE_CORRUPT_BKPT; 817 goto moveto_done; 818 } 819 }else{ 820 pIdxKey = 0; 821 } 822 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); 823 moveto_done: 824 if( pIdxKey ){ 825 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); 826 } 827 return rc; 828 } 829 830 /* 831 ** Restore the cursor to the position it was in (or as close to as possible) 832 ** when saveCursorPosition() was called. Note that this call deletes the 833 ** saved position info stored by saveCursorPosition(), so there can be 834 ** at most one effective restoreCursorPosition() call after each 835 ** saveCursorPosition(). 836 */ 837 static int btreeRestoreCursorPosition(BtCursor *pCur){ 838 int rc; 839 int skipNext = 0; 840 assert( cursorOwnsBtShared(pCur) ); 841 assert( pCur->eState>=CURSOR_REQUIRESEEK ); 842 if( pCur->eState==CURSOR_FAULT ){ 843 return pCur->skipNext; 844 } 845 pCur->eState = CURSOR_INVALID; 846 if( sqlite3FaultSim(410) ){ 847 rc = SQLITE_IOERR; 848 }else{ 849 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); 850 } 851 if( rc==SQLITE_OK ){ 852 sqlite3_free(pCur->pKey); 853 pCur->pKey = 0; 854 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); 855 if( skipNext ) pCur->skipNext = skipNext; 856 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ 857 pCur->eState = CURSOR_SKIPNEXT; 858 } 859 } 860 return rc; 861 } 862 863 #define restoreCursorPosition(p) \ 864 (p->eState>=CURSOR_REQUIRESEEK ? \ 865 btreeRestoreCursorPosition(p) : \ 866 SQLITE_OK) 867 868 /* 869 ** Determine whether or not a cursor has moved from the position where 870 ** it was last placed, or has been invalidated for any other reason. 871 ** Cursors can move when the row they are pointing at is deleted out 872 ** from under them, for example. Cursor might also move if a btree 873 ** is rebalanced. 874 ** 875 ** Calling this routine with a NULL cursor pointer returns false. 876 ** 877 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor 878 ** back to where it ought to be if this routine returns true. 879 */ 880 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ 881 assert( EIGHT_BYTE_ALIGNMENT(pCur) 882 || pCur==sqlite3BtreeFakeValidCursor() ); 883 assert( offsetof(BtCursor, eState)==0 ); 884 assert( sizeof(pCur->eState)==1 ); 885 return CURSOR_VALID != *(u8*)pCur; 886 } 887 888 /* 889 ** Return a pointer to a fake BtCursor object that will always answer 890 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake 891 ** cursor returned must not be used with any other Btree interface. 892 */ 893 BtCursor *sqlite3BtreeFakeValidCursor(void){ 894 static u8 fakeCursor = CURSOR_VALID; 895 assert( offsetof(BtCursor, eState)==0 ); 896 return (BtCursor*)&fakeCursor; 897 } 898 899 /* 900 ** This routine restores a cursor back to its original position after it 901 ** has been moved by some outside activity (such as a btree rebalance or 902 ** a row having been deleted out from under the cursor). 903 ** 904 ** On success, the *pDifferentRow parameter is false if the cursor is left 905 ** pointing at exactly the same row. *pDifferntRow is the row the cursor 906 ** was pointing to has been deleted, forcing the cursor to point to some 907 ** nearby row. 908 ** 909 ** This routine should only be called for a cursor that just returned 910 ** TRUE from sqlite3BtreeCursorHasMoved(). 911 */ 912 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ 913 int rc; 914 915 assert( pCur!=0 ); 916 assert( pCur->eState!=CURSOR_VALID ); 917 rc = restoreCursorPosition(pCur); 918 if( rc ){ 919 *pDifferentRow = 1; 920 return rc; 921 } 922 if( pCur->eState!=CURSOR_VALID ){ 923 *pDifferentRow = 1; 924 }else{ 925 *pDifferentRow = 0; 926 } 927 return SQLITE_OK; 928 } 929 930 #ifdef SQLITE_ENABLE_CURSOR_HINTS 931 /* 932 ** Provide hints to the cursor. The particular hint given (and the type 933 ** and number of the varargs parameters) is determined by the eHintType 934 ** parameter. See the definitions of the BTREE_HINT_* macros for details. 935 */ 936 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ 937 /* Used only by system that substitute their own storage engine */ 938 } 939 #endif 940 941 /* 942 ** Provide flag hints to the cursor. 943 */ 944 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ 945 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); 946 pCur->hints = x; 947 } 948 949 950 #ifndef SQLITE_OMIT_AUTOVACUUM 951 /* 952 ** Given a page number of a regular database page, return the page 953 ** number for the pointer-map page that contains the entry for the 954 ** input page number. 955 ** 956 ** Return 0 (not a valid page) for pgno==1 since there is 957 ** no pointer map associated with page 1. The integrity_check logic 958 ** requires that ptrmapPageno(*,1)!=1. 959 */ 960 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ 961 int nPagesPerMapPage; 962 Pgno iPtrMap, ret; 963 assert( sqlite3_mutex_held(pBt->mutex) ); 964 if( pgno<2 ) return 0; 965 nPagesPerMapPage = (pBt->usableSize/5)+1; 966 iPtrMap = (pgno-2)/nPagesPerMapPage; 967 ret = (iPtrMap*nPagesPerMapPage) + 2; 968 if( ret==PENDING_BYTE_PAGE(pBt) ){ 969 ret++; 970 } 971 return ret; 972 } 973 974 /* 975 ** Write an entry into the pointer map. 976 ** 977 ** This routine updates the pointer map entry for page number 'key' 978 ** so that it maps to type 'eType' and parent page number 'pgno'. 979 ** 980 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is 981 ** a no-op. If an error occurs, the appropriate error code is written 982 ** into *pRC. 983 */ 984 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ 985 DbPage *pDbPage; /* The pointer map page */ 986 u8 *pPtrmap; /* The pointer map data */ 987 Pgno iPtrmap; /* The pointer map page number */ 988 int offset; /* Offset in pointer map page */ 989 int rc; /* Return code from subfunctions */ 990 991 if( *pRC ) return; 992 993 assert( sqlite3_mutex_held(pBt->mutex) ); 994 /* The master-journal page number must never be used as a pointer map page */ 995 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); 996 997 assert( pBt->autoVacuum ); 998 if( key==0 ){ 999 *pRC = SQLITE_CORRUPT_BKPT; 1000 return; 1001 } 1002 iPtrmap = PTRMAP_PAGENO(pBt, key); 1003 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); 1004 if( rc!=SQLITE_OK ){ 1005 *pRC = rc; 1006 return; 1007 } 1008 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){ 1009 /* The first byte of the extra data is the MemPage.isInit byte. 1010 ** If that byte is set, it means this page is also being used 1011 ** as a btree page. */ 1012 *pRC = SQLITE_CORRUPT_BKPT; 1013 goto ptrmap_exit; 1014 } 1015 offset = PTRMAP_PTROFFSET(iPtrmap, key); 1016 if( offset<0 ){ 1017 *pRC = SQLITE_CORRUPT_BKPT; 1018 goto ptrmap_exit; 1019 } 1020 assert( offset <= (int)pBt->usableSize-5 ); 1021 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 1022 1023 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ 1024 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); 1025 *pRC= rc = sqlite3PagerWrite(pDbPage); 1026 if( rc==SQLITE_OK ){ 1027 pPtrmap[offset] = eType; 1028 put4byte(&pPtrmap[offset+1], parent); 1029 } 1030 } 1031 1032 ptrmap_exit: 1033 sqlite3PagerUnref(pDbPage); 1034 } 1035 1036 /* 1037 ** Read an entry from the pointer map. 1038 ** 1039 ** This routine retrieves the pointer map entry for page 'key', writing 1040 ** the type and parent page number to *pEType and *pPgno respectively. 1041 ** An error code is returned if something goes wrong, otherwise SQLITE_OK. 1042 */ 1043 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ 1044 DbPage *pDbPage; /* The pointer map page */ 1045 int iPtrmap; /* Pointer map page index */ 1046 u8 *pPtrmap; /* Pointer map page data */ 1047 int offset; /* Offset of entry in pointer map */ 1048 int rc; 1049 1050 assert( sqlite3_mutex_held(pBt->mutex) ); 1051 1052 iPtrmap = PTRMAP_PAGENO(pBt, key); 1053 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); 1054 if( rc!=0 ){ 1055 return rc; 1056 } 1057 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); 1058 1059 offset = PTRMAP_PTROFFSET(iPtrmap, key); 1060 if( offset<0 ){ 1061 sqlite3PagerUnref(pDbPage); 1062 return SQLITE_CORRUPT_BKPT; 1063 } 1064 assert( offset <= (int)pBt->usableSize-5 ); 1065 assert( pEType!=0 ); 1066 *pEType = pPtrmap[offset]; 1067 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); 1068 1069 sqlite3PagerUnref(pDbPage); 1070 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap); 1071 return SQLITE_OK; 1072 } 1073 1074 #else /* if defined SQLITE_OMIT_AUTOVACUUM */ 1075 #define ptrmapPut(w,x,y,z,rc) 1076 #define ptrmapGet(w,x,y,z) SQLITE_OK 1077 #define ptrmapPutOvflPtr(x, y, z, rc) 1078 #endif 1079 1080 /* 1081 ** Given a btree page and a cell index (0 means the first cell on 1082 ** the page, 1 means the second cell, and so forth) return a pointer 1083 ** to the cell content. 1084 ** 1085 ** findCellPastPtr() does the same except it skips past the initial 1086 ** 4-byte child pointer found on interior pages, if there is one. 1087 ** 1088 ** This routine works only for pages that do not contain overflow cells. 1089 */ 1090 #define findCell(P,I) \ 1091 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 1092 #define findCellPastPtr(P,I) \ 1093 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) 1094 1095 1096 /* 1097 ** This is common tail processing for btreeParseCellPtr() and 1098 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely 1099 ** on a single B-tree page. Make necessary adjustments to the CellInfo 1100 ** structure. 1101 */ 1102 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( 1103 MemPage *pPage, /* Page containing the cell */ 1104 u8 *pCell, /* Pointer to the cell text. */ 1105 CellInfo *pInfo /* Fill in this structure */ 1106 ){ 1107 /* If the payload will not fit completely on the local page, we have 1108 ** to decide how much to store locally and how much to spill onto 1109 ** overflow pages. The strategy is to minimize the amount of unused 1110 ** space on overflow pages while keeping the amount of local storage 1111 ** in between minLocal and maxLocal. 1112 ** 1113 ** Warning: changing the way overflow payload is distributed in any 1114 ** way will result in an incompatible file format. 1115 */ 1116 int minLocal; /* Minimum amount of payload held locally */ 1117 int maxLocal; /* Maximum amount of payload held locally */ 1118 int surplus; /* Overflow payload available for local storage */ 1119 1120 minLocal = pPage->minLocal; 1121 maxLocal = pPage->maxLocal; 1122 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); 1123 testcase( surplus==maxLocal ); 1124 testcase( surplus==maxLocal+1 ); 1125 if( surplus <= maxLocal ){ 1126 pInfo->nLocal = (u16)surplus; 1127 }else{ 1128 pInfo->nLocal = (u16)minLocal; 1129 } 1130 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; 1131 } 1132 1133 /* 1134 ** The following routines are implementations of the MemPage.xParseCell() 1135 ** method. 1136 ** 1137 ** Parse a cell content block and fill in the CellInfo structure. 1138 ** 1139 ** btreeParseCellPtr() => table btree leaf nodes 1140 ** btreeParseCellNoPayload() => table btree internal nodes 1141 ** btreeParseCellPtrIndex() => index btree nodes 1142 ** 1143 ** There is also a wrapper function btreeParseCell() that works for 1144 ** all MemPage types and that references the cell by index rather than 1145 ** by pointer. 1146 */ 1147 static void btreeParseCellPtrNoPayload( 1148 MemPage *pPage, /* Page containing the cell */ 1149 u8 *pCell, /* Pointer to the cell text. */ 1150 CellInfo *pInfo /* Fill in this structure */ 1151 ){ 1152 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1153 assert( pPage->leaf==0 ); 1154 assert( pPage->childPtrSize==4 ); 1155 #ifndef SQLITE_DEBUG 1156 UNUSED_PARAMETER(pPage); 1157 #endif 1158 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); 1159 pInfo->nPayload = 0; 1160 pInfo->nLocal = 0; 1161 pInfo->pPayload = 0; 1162 return; 1163 } 1164 static void btreeParseCellPtr( 1165 MemPage *pPage, /* Page containing the cell */ 1166 u8 *pCell, /* Pointer to the cell text. */ 1167 CellInfo *pInfo /* Fill in this structure */ 1168 ){ 1169 u8 *pIter; /* For scanning through pCell */ 1170 u32 nPayload; /* Number of bytes of cell payload */ 1171 u64 iKey; /* Extracted Key value */ 1172 1173 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1174 assert( pPage->leaf==0 || pPage->leaf==1 ); 1175 assert( pPage->intKeyLeaf ); 1176 assert( pPage->childPtrSize==0 ); 1177 pIter = pCell; 1178 1179 /* The next block of code is equivalent to: 1180 ** 1181 ** pIter += getVarint32(pIter, nPayload); 1182 ** 1183 ** The code is inlined to avoid a function call. 1184 */ 1185 nPayload = *pIter; 1186 if( nPayload>=0x80 ){ 1187 u8 *pEnd = &pIter[8]; 1188 nPayload &= 0x7f; 1189 do{ 1190 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1191 }while( (*pIter)>=0x80 && pIter<pEnd ); 1192 } 1193 pIter++; 1194 1195 /* The next block of code is equivalent to: 1196 ** 1197 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); 1198 ** 1199 ** The code is inlined to avoid a function call. 1200 */ 1201 iKey = *pIter; 1202 if( iKey>=0x80 ){ 1203 u8 *pEnd = &pIter[7]; 1204 iKey &= 0x7f; 1205 while(1){ 1206 iKey = (iKey<<7) | (*++pIter & 0x7f); 1207 if( (*pIter)<0x80 ) break; 1208 if( pIter>=pEnd ){ 1209 iKey = (iKey<<8) | *++pIter; 1210 break; 1211 } 1212 } 1213 } 1214 pIter++; 1215 1216 pInfo->nKey = *(i64*)&iKey; 1217 pInfo->nPayload = nPayload; 1218 pInfo->pPayload = pIter; 1219 testcase( nPayload==pPage->maxLocal ); 1220 testcase( nPayload==pPage->maxLocal+1 ); 1221 if( nPayload<=pPage->maxLocal ){ 1222 /* This is the (easy) common case where the entire payload fits 1223 ** on the local page. No overflow is required. 1224 */ 1225 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1226 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1227 pInfo->nLocal = (u16)nPayload; 1228 }else{ 1229 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1230 } 1231 } 1232 static void btreeParseCellPtrIndex( 1233 MemPage *pPage, /* Page containing the cell */ 1234 u8 *pCell, /* Pointer to the cell text. */ 1235 CellInfo *pInfo /* Fill in this structure */ 1236 ){ 1237 u8 *pIter; /* For scanning through pCell */ 1238 u32 nPayload; /* Number of bytes of cell payload */ 1239 1240 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1241 assert( pPage->leaf==0 || pPage->leaf==1 ); 1242 assert( pPage->intKeyLeaf==0 ); 1243 pIter = pCell + pPage->childPtrSize; 1244 nPayload = *pIter; 1245 if( nPayload>=0x80 ){ 1246 u8 *pEnd = &pIter[8]; 1247 nPayload &= 0x7f; 1248 do{ 1249 nPayload = (nPayload<<7) | (*++pIter & 0x7f); 1250 }while( *(pIter)>=0x80 && pIter<pEnd ); 1251 } 1252 pIter++; 1253 pInfo->nKey = nPayload; 1254 pInfo->nPayload = nPayload; 1255 pInfo->pPayload = pIter; 1256 testcase( nPayload==pPage->maxLocal ); 1257 testcase( nPayload==pPage->maxLocal+1 ); 1258 if( nPayload<=pPage->maxLocal ){ 1259 /* This is the (easy) common case where the entire payload fits 1260 ** on the local page. No overflow is required. 1261 */ 1262 pInfo->nSize = nPayload + (u16)(pIter - pCell); 1263 if( pInfo->nSize<4 ) pInfo->nSize = 4; 1264 pInfo->nLocal = (u16)nPayload; 1265 }else{ 1266 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); 1267 } 1268 } 1269 static void btreeParseCell( 1270 MemPage *pPage, /* Page containing the cell */ 1271 int iCell, /* The cell index. First cell is 0 */ 1272 CellInfo *pInfo /* Fill in this structure */ 1273 ){ 1274 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); 1275 } 1276 1277 /* 1278 ** The following routines are implementations of the MemPage.xCellSize 1279 ** method. 1280 ** 1281 ** Compute the total number of bytes that a Cell needs in the cell 1282 ** data area of the btree-page. The return number includes the cell 1283 ** data header and the local payload, but not any overflow page or 1284 ** the space used by the cell pointer. 1285 ** 1286 ** cellSizePtrNoPayload() => table internal nodes 1287 ** cellSizePtr() => all index nodes & table leaf nodes 1288 */ 1289 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ 1290 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ 1291 u8 *pEnd; /* End mark for a varint */ 1292 u32 nSize; /* Size value to return */ 1293 1294 #ifdef SQLITE_DEBUG 1295 /* The value returned by this function should always be the same as 1296 ** the (CellInfo.nSize) value found by doing a full parse of the 1297 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1298 ** this function verifies that this invariant is not violated. */ 1299 CellInfo debuginfo; 1300 pPage->xParseCell(pPage, pCell, &debuginfo); 1301 #endif 1302 1303 nSize = *pIter; 1304 if( nSize>=0x80 ){ 1305 pEnd = &pIter[8]; 1306 nSize &= 0x7f; 1307 do{ 1308 nSize = (nSize<<7) | (*++pIter & 0x7f); 1309 }while( *(pIter)>=0x80 && pIter<pEnd ); 1310 } 1311 pIter++; 1312 if( pPage->intKey ){ 1313 /* pIter now points at the 64-bit integer key value, a variable length 1314 ** integer. The following block moves pIter to point at the first byte 1315 ** past the end of the key value. */ 1316 pEnd = &pIter[9]; 1317 while( (*pIter++)&0x80 && pIter<pEnd ); 1318 } 1319 testcase( nSize==pPage->maxLocal ); 1320 testcase( nSize==pPage->maxLocal+1 ); 1321 if( nSize<=pPage->maxLocal ){ 1322 nSize += (u32)(pIter - pCell); 1323 if( nSize<4 ) nSize = 4; 1324 }else{ 1325 int minLocal = pPage->minLocal; 1326 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); 1327 testcase( nSize==pPage->maxLocal ); 1328 testcase( nSize==pPage->maxLocal+1 ); 1329 if( nSize>pPage->maxLocal ){ 1330 nSize = minLocal; 1331 } 1332 nSize += 4 + (u16)(pIter - pCell); 1333 } 1334 assert( nSize==debuginfo.nSize || CORRUPT_DB ); 1335 return (u16)nSize; 1336 } 1337 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ 1338 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ 1339 u8 *pEnd; /* End mark for a varint */ 1340 1341 #ifdef SQLITE_DEBUG 1342 /* The value returned by this function should always be the same as 1343 ** the (CellInfo.nSize) value found by doing a full parse of the 1344 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of 1345 ** this function verifies that this invariant is not violated. */ 1346 CellInfo debuginfo; 1347 pPage->xParseCell(pPage, pCell, &debuginfo); 1348 #else 1349 UNUSED_PARAMETER(pPage); 1350 #endif 1351 1352 assert( pPage->childPtrSize==4 ); 1353 pEnd = pIter + 9; 1354 while( (*pIter++)&0x80 && pIter<pEnd ); 1355 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB ); 1356 return (u16)(pIter - pCell); 1357 } 1358 1359 1360 #ifdef SQLITE_DEBUG 1361 /* This variation on cellSizePtr() is used inside of assert() statements 1362 ** only. */ 1363 static u16 cellSize(MemPage *pPage, int iCell){ 1364 return pPage->xCellSize(pPage, findCell(pPage, iCell)); 1365 } 1366 #endif 1367 1368 #ifndef SQLITE_OMIT_AUTOVACUUM 1369 /* 1370 ** The cell pCell is currently part of page pSrc but will ultimately be part 1371 ** of pPage. (pSrc and pPager are often the same.) If pCell contains a 1372 ** pointer to an overflow page, insert an entry into the pointer-map for 1373 ** the overflow page that will be valid after pCell has been moved to pPage. 1374 */ 1375 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){ 1376 CellInfo info; 1377 if( *pRC ) return; 1378 assert( pCell!=0 ); 1379 pPage->xParseCell(pPage, pCell, &info); 1380 if( info.nLocal<info.nPayload ){ 1381 Pgno ovfl; 1382 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){ 1383 testcase( pSrc!=pPage ); 1384 *pRC = SQLITE_CORRUPT_BKPT; 1385 return; 1386 } 1387 ovfl = get4byte(&pCell[info.nSize-4]); 1388 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); 1389 } 1390 } 1391 #endif 1392 1393 1394 /* 1395 ** Defragment the page given. This routine reorganizes cells within the 1396 ** page so that there are no free-blocks on the free-block list. 1397 ** 1398 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be 1399 ** present in the page after this routine returns. 1400 ** 1401 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a 1402 ** b-tree page so that there are no freeblocks or fragment bytes, all 1403 ** unused bytes are contained in the unallocated space region, and all 1404 ** cells are packed tightly at the end of the page. 1405 */ 1406 static int defragmentPage(MemPage *pPage, int nMaxFrag){ 1407 int i; /* Loop counter */ 1408 int pc; /* Address of the i-th cell */ 1409 int hdr; /* Offset to the page header */ 1410 int size; /* Size of a cell */ 1411 int usableSize; /* Number of usable bytes on a page */ 1412 int cellOffset; /* Offset to the cell pointer array */ 1413 int cbrk; /* Offset to the cell content area */ 1414 int nCell; /* Number of cells on the page */ 1415 unsigned char *data; /* The page data */ 1416 unsigned char *temp; /* Temp area for cell content */ 1417 unsigned char *src; /* Source of content */ 1418 int iCellFirst; /* First allowable cell index */ 1419 int iCellLast; /* Last possible cell index */ 1420 1421 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1422 assert( pPage->pBt!=0 ); 1423 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); 1424 assert( pPage->nOverflow==0 ); 1425 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1426 temp = 0; 1427 src = data = pPage->aData; 1428 hdr = pPage->hdrOffset; 1429 cellOffset = pPage->cellOffset; 1430 nCell = pPage->nCell; 1431 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB ); 1432 iCellFirst = cellOffset + 2*nCell; 1433 usableSize = pPage->pBt->usableSize; 1434 1435 /* This block handles pages with two or fewer free blocks and nMaxFrag 1436 ** or fewer fragmented bytes. In this case it is faster to move the 1437 ** two (or one) blocks of cells using memmove() and add the required 1438 ** offsets to each pointer in the cell-pointer array than it is to 1439 ** reconstruct the entire page. */ 1440 if( (int)data[hdr+7]<=nMaxFrag ){ 1441 int iFree = get2byte(&data[hdr+1]); 1442 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); 1443 if( iFree ){ 1444 int iFree2 = get2byte(&data[iFree]); 1445 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); 1446 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){ 1447 u8 *pEnd = &data[cellOffset + nCell*2]; 1448 u8 *pAddr; 1449 int sz2 = 0; 1450 int sz = get2byte(&data[iFree+2]); 1451 int top = get2byte(&data[hdr+5]); 1452 if( top>=iFree ){ 1453 return SQLITE_CORRUPT_PAGE(pPage); 1454 } 1455 if( iFree2 ){ 1456 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage); 1457 sz2 = get2byte(&data[iFree2+2]); 1458 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage); 1459 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); 1460 sz += sz2; 1461 }else if( NEVER(iFree+sz>usableSize) ){ 1462 return SQLITE_CORRUPT_PAGE(pPage); 1463 } 1464 1465 cbrk = top+sz; 1466 assert( cbrk+(iFree-top) <= usableSize ); 1467 memmove(&data[cbrk], &data[top], iFree-top); 1468 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){ 1469 pc = get2byte(pAddr); 1470 if( pc<iFree ){ put2byte(pAddr, pc+sz); } 1471 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); } 1472 } 1473 goto defragment_out; 1474 } 1475 } 1476 } 1477 1478 cbrk = usableSize; 1479 iCellLast = usableSize - 4; 1480 for(i=0; i<nCell; i++){ 1481 u8 *pAddr; /* The i-th cell pointer */ 1482 pAddr = &data[cellOffset + i*2]; 1483 pc = get2byte(pAddr); 1484 testcase( pc==iCellFirst ); 1485 testcase( pc==iCellLast ); 1486 /* These conditions have already been verified in btreeInitPage() 1487 ** if PRAGMA cell_size_check=ON. 1488 */ 1489 if( pc<iCellFirst || pc>iCellLast ){ 1490 return SQLITE_CORRUPT_PAGE(pPage); 1491 } 1492 assert( pc>=iCellFirst && pc<=iCellLast ); 1493 size = pPage->xCellSize(pPage, &src[pc]); 1494 cbrk -= size; 1495 if( cbrk<iCellFirst || pc+size>usableSize ){ 1496 return SQLITE_CORRUPT_PAGE(pPage); 1497 } 1498 assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); 1499 testcase( cbrk+size==usableSize ); 1500 testcase( pc+size==usableSize ); 1501 put2byte(pAddr, cbrk); 1502 if( temp==0 ){ 1503 int x; 1504 if( cbrk==pc ) continue; 1505 temp = sqlite3PagerTempSpace(pPage->pBt->pPager); 1506 x = get2byte(&data[hdr+5]); 1507 memcpy(&temp[x], &data[x], (cbrk+size) - x); 1508 src = temp; 1509 } 1510 memcpy(&data[cbrk], &src[pc], size); 1511 } 1512 data[hdr+7] = 0; 1513 1514 defragment_out: 1515 assert( pPage->nFree>=0 ); 1516 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ 1517 return SQLITE_CORRUPT_PAGE(pPage); 1518 } 1519 assert( cbrk>=iCellFirst ); 1520 put2byte(&data[hdr+5], cbrk); 1521 data[hdr+1] = 0; 1522 data[hdr+2] = 0; 1523 memset(&data[iCellFirst], 0, cbrk-iCellFirst); 1524 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1525 return SQLITE_OK; 1526 } 1527 1528 /* 1529 ** Search the free-list on page pPg for space to store a cell nByte bytes in 1530 ** size. If one can be found, return a pointer to the space and remove it 1531 ** from the free-list. 1532 ** 1533 ** If no suitable space can be found on the free-list, return NULL. 1534 ** 1535 ** This function may detect corruption within pPg. If corruption is 1536 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. 1537 ** 1538 ** Slots on the free list that are between 1 and 3 bytes larger than nByte 1539 ** will be ignored if adding the extra space to the fragmentation count 1540 ** causes the fragmentation count to exceed 60. 1541 */ 1542 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ 1543 const int hdr = pPg->hdrOffset; /* Offset to page header */ 1544 u8 * const aData = pPg->aData; /* Page data */ 1545 int iAddr = hdr + 1; /* Address of ptr to pc */ 1546 int pc = get2byte(&aData[iAddr]); /* Address of a free slot */ 1547 int x; /* Excess size of the slot */ 1548 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */ 1549 int size; /* Size of the free slot */ 1550 1551 assert( pc>0 ); 1552 while( pc<=maxPC ){ 1553 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each 1554 ** freeblock form a big-endian integer which is the size of the freeblock 1555 ** in bytes, including the 4-byte header. */ 1556 size = get2byte(&aData[pc+2]); 1557 if( (x = size - nByte)>=0 ){ 1558 testcase( x==4 ); 1559 testcase( x==3 ); 1560 if( x<4 ){ 1561 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total 1562 ** number of bytes in fragments may not exceed 60. */ 1563 if( aData[hdr+7]>57 ) return 0; 1564 1565 /* Remove the slot from the free-list. Update the number of 1566 ** fragmented bytes within the page. */ 1567 memcpy(&aData[iAddr], &aData[pc], 2); 1568 aData[hdr+7] += (u8)x; 1569 }else if( x+pc > maxPC ){ 1570 /* This slot extends off the end of the usable part of the page */ 1571 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1572 return 0; 1573 }else{ 1574 /* The slot remains on the free-list. Reduce its size to account 1575 ** for the portion used by the new allocation. */ 1576 put2byte(&aData[pc+2], x); 1577 } 1578 return &aData[pc + x]; 1579 } 1580 iAddr = pc; 1581 pc = get2byte(&aData[pc]); 1582 if( pc<=iAddr+size ){ 1583 if( pc ){ 1584 /* The next slot in the chain is not past the end of the current slot */ 1585 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1586 } 1587 return 0; 1588 } 1589 } 1590 if( pc>maxPC+nByte-4 ){ 1591 /* The free slot chain extends off the end of the page */ 1592 *pRc = SQLITE_CORRUPT_PAGE(pPg); 1593 } 1594 return 0; 1595 } 1596 1597 /* 1598 ** Allocate nByte bytes of space from within the B-Tree page passed 1599 ** as the first argument. Write into *pIdx the index into pPage->aData[] 1600 ** of the first byte of allocated space. Return either SQLITE_OK or 1601 ** an error code (usually SQLITE_CORRUPT). 1602 ** 1603 ** The caller guarantees that there is sufficient space to make the 1604 ** allocation. This routine might need to defragment in order to bring 1605 ** all the space together, however. This routine will avoid using 1606 ** the first two bytes past the cell pointer area since presumably this 1607 ** allocation is being made in order to insert a new cell, so we will 1608 ** also end up needing a new cell pointer. 1609 */ 1610 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ 1611 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ 1612 u8 * const data = pPage->aData; /* Local cache of pPage->aData */ 1613 int top; /* First byte of cell content area */ 1614 int rc = SQLITE_OK; /* Integer return code */ 1615 int gap; /* First byte of gap between cell pointers and cell content */ 1616 1617 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1618 assert( pPage->pBt ); 1619 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1620 assert( nByte>=0 ); /* Minimum cell size is 4 */ 1621 assert( pPage->nFree>=nByte ); 1622 assert( pPage->nOverflow==0 ); 1623 assert( nByte < (int)(pPage->pBt->usableSize-8) ); 1624 1625 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); 1626 gap = pPage->cellOffset + 2*pPage->nCell; 1627 assert( gap<=65536 ); 1628 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size 1629 ** and the reserved space is zero (the usual value for reserved space) 1630 ** then the cell content offset of an empty page wants to be 65536. 1631 ** However, that integer is too large to be stored in a 2-byte unsigned 1632 ** integer, so a value of 0 is used in its place. */ 1633 top = get2byte(&data[hdr+5]); 1634 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */ 1635 if( gap>top ){ 1636 if( top==0 && pPage->pBt->usableSize==65536 ){ 1637 top = 65536; 1638 }else{ 1639 return SQLITE_CORRUPT_PAGE(pPage); 1640 } 1641 } 1642 1643 /* If there is enough space between gap and top for one more cell pointer, 1644 ** and if the freelist is not empty, then search the 1645 ** freelist looking for a slot big enough to satisfy the request. 1646 */ 1647 testcase( gap+2==top ); 1648 testcase( gap+1==top ); 1649 testcase( gap==top ); 1650 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ 1651 u8 *pSpace = pageFindSlot(pPage, nByte, &rc); 1652 if( pSpace ){ 1653 int g2; 1654 assert( pSpace+nByte<=data+pPage->pBt->usableSize ); 1655 *pIdx = g2 = (int)(pSpace-data); 1656 if( NEVER(g2<=gap) ){ 1657 return SQLITE_CORRUPT_PAGE(pPage); 1658 }else{ 1659 return SQLITE_OK; 1660 } 1661 }else if( rc ){ 1662 return rc; 1663 } 1664 } 1665 1666 /* The request could not be fulfilled using a freelist slot. Check 1667 ** to see if defragmentation is necessary. 1668 */ 1669 testcase( gap+2+nByte==top ); 1670 if( gap+2+nByte>top ){ 1671 assert( pPage->nCell>0 || CORRUPT_DB ); 1672 assert( pPage->nFree>=0 ); 1673 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte))); 1674 if( rc ) return rc; 1675 top = get2byteNotZero(&data[hdr+5]); 1676 assert( gap+2+nByte<=top ); 1677 } 1678 1679 1680 /* Allocate memory from the gap in between the cell pointer array 1681 ** and the cell content area. The btreeComputeFreeSpace() call has already 1682 ** validated the freelist. Given that the freelist is valid, there 1683 ** is no way that the allocation can extend off the end of the page. 1684 ** The assert() below verifies the previous sentence. 1685 */ 1686 top -= nByte; 1687 put2byte(&data[hdr+5], top); 1688 assert( top+nByte <= (int)pPage->pBt->usableSize ); 1689 *pIdx = top; 1690 return SQLITE_OK; 1691 } 1692 1693 /* 1694 ** Return a section of the pPage->aData to the freelist. 1695 ** The first byte of the new free block is pPage->aData[iStart] 1696 ** and the size of the block is iSize bytes. 1697 ** 1698 ** Adjacent freeblocks are coalesced. 1699 ** 1700 ** Even though the freeblock list was checked by btreeComputeFreeSpace(), 1701 ** that routine will not detect overlap between cells or freeblocks. Nor 1702 ** does it detect cells or freeblocks that encrouch into the reserved bytes 1703 ** at the end of the page. So do additional corruption checks inside this 1704 ** routine and return SQLITE_CORRUPT if any problems are found. 1705 */ 1706 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ 1707 u16 iPtr; /* Address of ptr to next freeblock */ 1708 u16 iFreeBlk; /* Address of the next freeblock */ 1709 u8 hdr; /* Page header size. 0 or 100 */ 1710 u8 nFrag = 0; /* Reduction in fragmentation */ 1711 u16 iOrigSize = iSize; /* Original value of iSize */ 1712 u16 x; /* Offset to cell content area */ 1713 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ 1714 unsigned char *data = pPage->aData; /* Page content */ 1715 1716 assert( pPage->pBt!=0 ); 1717 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 1718 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); 1719 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); 1720 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1721 assert( iSize>=4 ); /* Minimum cell size is 4 */ 1722 assert( iStart<=pPage->pBt->usableSize-4 ); 1723 1724 /* The list of freeblocks must be in ascending order. Find the 1725 ** spot on the list where iStart should be inserted. 1726 */ 1727 hdr = pPage->hdrOffset; 1728 iPtr = hdr + 1; 1729 if( data[iPtr+1]==0 && data[iPtr]==0 ){ 1730 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ 1731 }else{ 1732 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){ 1733 if( iFreeBlk<iPtr+4 ){ 1734 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */ 1735 return SQLITE_CORRUPT_PAGE(pPage); 1736 } 1737 iPtr = iFreeBlk; 1738 } 1739 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ 1740 return SQLITE_CORRUPT_PAGE(pPage); 1741 } 1742 assert( iFreeBlk>iPtr || iFreeBlk==0 ); 1743 1744 /* At this point: 1745 ** iFreeBlk: First freeblock after iStart, or zero if none 1746 ** iPtr: The address of a pointer to iFreeBlk 1747 ** 1748 ** Check to see if iFreeBlk should be coalesced onto the end of iStart. 1749 */ 1750 if( iFreeBlk && iEnd+3>=iFreeBlk ){ 1751 nFrag = iFreeBlk - iEnd; 1752 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage); 1753 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); 1754 if( iEnd > pPage->pBt->usableSize ){ 1755 return SQLITE_CORRUPT_PAGE(pPage); 1756 } 1757 iSize = iEnd - iStart; 1758 iFreeBlk = get2byte(&data[iFreeBlk]); 1759 } 1760 1761 /* If iPtr is another freeblock (that is, if iPtr is not the freelist 1762 ** pointer in the page header) then check to see if iStart should be 1763 ** coalesced onto the end of iPtr. 1764 */ 1765 if( iPtr>hdr+1 ){ 1766 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); 1767 if( iPtrEnd+3>=iStart ){ 1768 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage); 1769 nFrag += iStart - iPtrEnd; 1770 iSize = iEnd - iPtr; 1771 iStart = iPtr; 1772 } 1773 } 1774 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage); 1775 data[hdr+7] -= nFrag; 1776 } 1777 x = get2byte(&data[hdr+5]); 1778 if( iStart<=x ){ 1779 /* The new freeblock is at the beginning of the cell content area, 1780 ** so just extend the cell content area rather than create another 1781 ** freelist entry */ 1782 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage); 1783 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage); 1784 put2byte(&data[hdr+1], iFreeBlk); 1785 put2byte(&data[hdr+5], iEnd); 1786 }else{ 1787 /* Insert the new freeblock into the freelist */ 1788 put2byte(&data[iPtr], iStart); 1789 } 1790 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){ 1791 /* Overwrite deleted information with zeros when the secure_delete 1792 ** option is enabled */ 1793 memset(&data[iStart], 0, iSize); 1794 } 1795 put2byte(&data[iStart], iFreeBlk); 1796 put2byte(&data[iStart+2], iSize); 1797 pPage->nFree += iOrigSize; 1798 return SQLITE_OK; 1799 } 1800 1801 /* 1802 ** Decode the flags byte (the first byte of the header) for a page 1803 ** and initialize fields of the MemPage structure accordingly. 1804 ** 1805 ** Only the following combinations are supported. Anything different 1806 ** indicates a corrupt database files: 1807 ** 1808 ** PTF_ZERODATA 1809 ** PTF_ZERODATA | PTF_LEAF 1810 ** PTF_LEAFDATA | PTF_INTKEY 1811 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF 1812 */ 1813 static int decodeFlags(MemPage *pPage, int flagByte){ 1814 BtShared *pBt; /* A copy of pPage->pBt */ 1815 1816 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); 1817 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1818 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); 1819 flagByte &= ~PTF_LEAF; 1820 pPage->childPtrSize = 4-4*pPage->leaf; 1821 pPage->xCellSize = cellSizePtr; 1822 pBt = pPage->pBt; 1823 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ 1824 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an 1825 ** interior table b-tree page. */ 1826 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); 1827 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a 1828 ** leaf table b-tree page. */ 1829 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); 1830 pPage->intKey = 1; 1831 if( pPage->leaf ){ 1832 pPage->intKeyLeaf = 1; 1833 pPage->xParseCell = btreeParseCellPtr; 1834 }else{ 1835 pPage->intKeyLeaf = 0; 1836 pPage->xCellSize = cellSizePtrNoPayload; 1837 pPage->xParseCell = btreeParseCellPtrNoPayload; 1838 } 1839 pPage->maxLocal = pBt->maxLeaf; 1840 pPage->minLocal = pBt->minLeaf; 1841 }else if( flagByte==PTF_ZERODATA ){ 1842 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an 1843 ** interior index b-tree page. */ 1844 assert( (PTF_ZERODATA)==2 ); 1845 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a 1846 ** leaf index b-tree page. */ 1847 assert( (PTF_ZERODATA|PTF_LEAF)==10 ); 1848 pPage->intKey = 0; 1849 pPage->intKeyLeaf = 0; 1850 pPage->xParseCell = btreeParseCellPtrIndex; 1851 pPage->maxLocal = pBt->maxLocal; 1852 pPage->minLocal = pBt->minLocal; 1853 }else{ 1854 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is 1855 ** an error. */ 1856 return SQLITE_CORRUPT_PAGE(pPage); 1857 } 1858 pPage->max1bytePayload = pBt->max1bytePayload; 1859 return SQLITE_OK; 1860 } 1861 1862 /* 1863 ** Compute the amount of freespace on the page. In other words, fill 1864 ** in the pPage->nFree field. 1865 */ 1866 static int btreeComputeFreeSpace(MemPage *pPage){ 1867 int pc; /* Address of a freeblock within pPage->aData[] */ 1868 u8 hdr; /* Offset to beginning of page header */ 1869 u8 *data; /* Equal to pPage->aData */ 1870 int usableSize; /* Amount of usable space on each page */ 1871 int nFree; /* Number of unused bytes on the page */ 1872 int top; /* First byte of the cell content area */ 1873 int iCellFirst; /* First allowable cell or freeblock offset */ 1874 int iCellLast; /* Last possible cell or freeblock offset */ 1875 1876 assert( pPage->pBt!=0 ); 1877 assert( pPage->pBt->db!=0 ); 1878 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1879 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); 1880 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); 1881 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); 1882 assert( pPage->isInit==1 ); 1883 assert( pPage->nFree<0 ); 1884 1885 usableSize = pPage->pBt->usableSize; 1886 hdr = pPage->hdrOffset; 1887 data = pPage->aData; 1888 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates 1889 ** the start of the cell content area. A zero value for this integer is 1890 ** interpreted as 65536. */ 1891 top = get2byteNotZero(&data[hdr+5]); 1892 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell; 1893 iCellLast = usableSize - 4; 1894 1895 /* Compute the total free space on the page 1896 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the 1897 ** start of the first freeblock on the page, or is zero if there are no 1898 ** freeblocks. */ 1899 pc = get2byte(&data[hdr+1]); 1900 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ 1901 if( pc>0 ){ 1902 u32 next, size; 1903 if( pc<top ){ 1904 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will 1905 ** always be at least one cell before the first freeblock. 1906 */ 1907 return SQLITE_CORRUPT_PAGE(pPage); 1908 } 1909 while( 1 ){ 1910 if( pc>iCellLast ){ 1911 /* Freeblock off the end of the page */ 1912 return SQLITE_CORRUPT_PAGE(pPage); 1913 } 1914 next = get2byte(&data[pc]); 1915 size = get2byte(&data[pc+2]); 1916 nFree = nFree + size; 1917 if( next<=pc+size+3 ) break; 1918 pc = next; 1919 } 1920 if( next>0 ){ 1921 /* Freeblock not in ascending order */ 1922 return SQLITE_CORRUPT_PAGE(pPage); 1923 } 1924 if( pc+size>(unsigned int)usableSize ){ 1925 /* Last freeblock extends past page end */ 1926 return SQLITE_CORRUPT_PAGE(pPage); 1927 } 1928 } 1929 1930 /* At this point, nFree contains the sum of the offset to the start 1931 ** of the cell-content area plus the number of free bytes within 1932 ** the cell-content area. If this is greater than the usable-size 1933 ** of the page, then the page must be corrupted. This check also 1934 ** serves to verify that the offset to the start of the cell-content 1935 ** area, according to the page header, lies within the page. 1936 */ 1937 if( nFree>usableSize || nFree<iCellFirst ){ 1938 return SQLITE_CORRUPT_PAGE(pPage); 1939 } 1940 pPage->nFree = (u16)(nFree - iCellFirst); 1941 return SQLITE_OK; 1942 } 1943 1944 /* 1945 ** Do additional sanity check after btreeInitPage() if 1946 ** PRAGMA cell_size_check=ON 1947 */ 1948 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){ 1949 int iCellFirst; /* First allowable cell or freeblock offset */ 1950 int iCellLast; /* Last possible cell or freeblock offset */ 1951 int i; /* Index into the cell pointer array */ 1952 int sz; /* Size of a cell */ 1953 int pc; /* Address of a freeblock within pPage->aData[] */ 1954 u8 *data; /* Equal to pPage->aData */ 1955 int usableSize; /* Maximum usable space on the page */ 1956 int cellOffset; /* Start of cell content area */ 1957 1958 iCellFirst = pPage->cellOffset + 2*pPage->nCell; 1959 usableSize = pPage->pBt->usableSize; 1960 iCellLast = usableSize - 4; 1961 data = pPage->aData; 1962 cellOffset = pPage->cellOffset; 1963 if( !pPage->leaf ) iCellLast--; 1964 for(i=0; i<pPage->nCell; i++){ 1965 pc = get2byteAligned(&data[cellOffset+i*2]); 1966 testcase( pc==iCellFirst ); 1967 testcase( pc==iCellLast ); 1968 if( pc<iCellFirst || pc>iCellLast ){ 1969 return SQLITE_CORRUPT_PAGE(pPage); 1970 } 1971 sz = pPage->xCellSize(pPage, &data[pc]); 1972 testcase( pc+sz==usableSize ); 1973 if( pc+sz>usableSize ){ 1974 return SQLITE_CORRUPT_PAGE(pPage); 1975 } 1976 } 1977 return SQLITE_OK; 1978 } 1979 1980 /* 1981 ** Initialize the auxiliary information for a disk block. 1982 ** 1983 ** Return SQLITE_OK on success. If we see that the page does 1984 ** not contain a well-formed database page, then return 1985 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not 1986 ** guarantee that the page is well-formed. It only shows that 1987 ** we failed to detect any corruption. 1988 */ 1989 static int btreeInitPage(MemPage *pPage){ 1990 u8 *data; /* Equal to pPage->aData */ 1991 BtShared *pBt; /* The main btree structure */ 1992 1993 assert( pPage->pBt!=0 ); 1994 assert( pPage->pBt->db!=0 ); 1995 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 1996 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); 1997 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); 1998 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); 1999 assert( pPage->isInit==0 ); 2000 2001 pBt = pPage->pBt; 2002 data = pPage->aData + pPage->hdrOffset; 2003 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating 2004 ** the b-tree page type. */ 2005 if( decodeFlags(pPage, data[0]) ){ 2006 return SQLITE_CORRUPT_PAGE(pPage); 2007 } 2008 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 2009 pPage->maskPage = (u16)(pBt->pageSize - 1); 2010 pPage->nOverflow = 0; 2011 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize; 2012 pPage->aCellIdx = data + pPage->childPtrSize + 8; 2013 pPage->aDataEnd = pPage->aData + pBt->usableSize; 2014 pPage->aDataOfst = pPage->aData + pPage->childPtrSize; 2015 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 2016 ** number of cells on the page. */ 2017 pPage->nCell = get2byte(&data[3]); 2018 if( pPage->nCell>MX_CELL(pBt) ){ 2019 /* To many cells for a single page. The page must be corrupt */ 2020 return SQLITE_CORRUPT_PAGE(pPage); 2021 } 2022 testcase( pPage->nCell==MX_CELL(pBt) ); 2023 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only 2024 ** possible for a root page of a table that contains no rows) then the 2025 ** offset to the cell content area will equal the page size minus the 2026 ** bytes of reserved space. */ 2027 assert( pPage->nCell>0 2028 || get2byteNotZero(&data[5])==(int)pBt->usableSize 2029 || CORRUPT_DB ); 2030 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */ 2031 pPage->isInit = 1; 2032 if( pBt->db->flags & SQLITE_CellSizeCk ){ 2033 return btreeCellSizeCheck(pPage); 2034 } 2035 return SQLITE_OK; 2036 } 2037 2038 /* 2039 ** Set up a raw page so that it looks like a database page holding 2040 ** no entries. 2041 */ 2042 static void zeroPage(MemPage *pPage, int flags){ 2043 unsigned char *data = pPage->aData; 2044 BtShared *pBt = pPage->pBt; 2045 u8 hdr = pPage->hdrOffset; 2046 u16 first; 2047 2048 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); 2049 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2050 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); 2051 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 2052 assert( sqlite3_mutex_held(pBt->mutex) ); 2053 if( pBt->btsFlags & BTS_FAST_SECURE ){ 2054 memset(&data[hdr], 0, pBt->usableSize - hdr); 2055 } 2056 data[hdr] = (char)flags; 2057 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); 2058 memset(&data[hdr+1], 0, 4); 2059 data[hdr+7] = 0; 2060 put2byte(&data[hdr+5], pBt->usableSize); 2061 pPage->nFree = (u16)(pBt->usableSize - first); 2062 decodeFlags(pPage, flags); 2063 pPage->cellOffset = first; 2064 pPage->aDataEnd = &data[pBt->usableSize]; 2065 pPage->aCellIdx = &data[first]; 2066 pPage->aDataOfst = &data[pPage->childPtrSize]; 2067 pPage->nOverflow = 0; 2068 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); 2069 pPage->maskPage = (u16)(pBt->pageSize - 1); 2070 pPage->nCell = 0; 2071 pPage->isInit = 1; 2072 } 2073 2074 2075 /* 2076 ** Convert a DbPage obtained from the pager into a MemPage used by 2077 ** the btree layer. 2078 */ 2079 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ 2080 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); 2081 if( pgno!=pPage->pgno ){ 2082 pPage->aData = sqlite3PagerGetData(pDbPage); 2083 pPage->pDbPage = pDbPage; 2084 pPage->pBt = pBt; 2085 pPage->pgno = pgno; 2086 pPage->hdrOffset = pgno==1 ? 100 : 0; 2087 } 2088 assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); 2089 return pPage; 2090 } 2091 2092 /* 2093 ** Get a page from the pager. Initialize the MemPage.pBt and 2094 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). 2095 ** 2096 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care 2097 ** about the content of the page at this time. So do not go to the disk 2098 ** to fetch the content. Just fill in the content with zeros for now. 2099 ** If in the future we call sqlite3PagerWrite() on this page, that 2100 ** means we have started to be concerned about content and the disk 2101 ** read should occur at that point. 2102 */ 2103 static int btreeGetPage( 2104 BtShared *pBt, /* The btree */ 2105 Pgno pgno, /* Number of the page to fetch */ 2106 MemPage **ppPage, /* Return the page in this parameter */ 2107 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 2108 ){ 2109 int rc; 2110 DbPage *pDbPage; 2111 2112 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); 2113 assert( sqlite3_mutex_held(pBt->mutex) ); 2114 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); 2115 if( rc ) return rc; 2116 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); 2117 return SQLITE_OK; 2118 } 2119 2120 /* 2121 ** Retrieve a page from the pager cache. If the requested page is not 2122 ** already in the pager cache return NULL. Initialize the MemPage.pBt and 2123 ** MemPage.aData elements if needed. 2124 */ 2125 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ 2126 DbPage *pDbPage; 2127 assert( sqlite3_mutex_held(pBt->mutex) ); 2128 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); 2129 if( pDbPage ){ 2130 return btreePageFromDbPage(pDbPage, pgno, pBt); 2131 } 2132 return 0; 2133 } 2134 2135 /* 2136 ** Return the size of the database file in pages. If there is any kind of 2137 ** error, return ((unsigned int)-1). 2138 */ 2139 static Pgno btreePagecount(BtShared *pBt){ 2140 assert( (pBt->nPage & 0x80000000)==0 || CORRUPT_DB ); 2141 return pBt->nPage; 2142 } 2143 u32 sqlite3BtreeLastPage(Btree *p){ 2144 assert( sqlite3BtreeHoldsMutex(p) ); 2145 return btreePagecount(p->pBt) & 0x7fffffff; 2146 } 2147 2148 /* 2149 ** Get a page from the pager and initialize it. 2150 ** 2151 ** If pCur!=0 then the page is being fetched as part of a moveToChild() 2152 ** call. Do additional sanity checking on the page in this case. 2153 ** And if the fetch fails, this routine must decrement pCur->iPage. 2154 ** 2155 ** The page is fetched as read-write unless pCur is not NULL and is 2156 ** a read-only cursor. 2157 ** 2158 ** If an error occurs, then *ppPage is undefined. It 2159 ** may remain unchanged, or it may be set to an invalid value. 2160 */ 2161 static int getAndInitPage( 2162 BtShared *pBt, /* The database file */ 2163 Pgno pgno, /* Number of the page to get */ 2164 MemPage **ppPage, /* Write the page pointer here */ 2165 BtCursor *pCur, /* Cursor to receive the page, or NULL */ 2166 int bReadOnly /* True for a read-only page */ 2167 ){ 2168 int rc; 2169 DbPage *pDbPage; 2170 assert( sqlite3_mutex_held(pBt->mutex) ); 2171 assert( pCur==0 || ppPage==&pCur->pPage ); 2172 assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); 2173 assert( pCur==0 || pCur->iPage>0 ); 2174 2175 if( pgno>btreePagecount(pBt) ){ 2176 rc = SQLITE_CORRUPT_BKPT; 2177 goto getAndInitPage_error1; 2178 } 2179 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); 2180 if( rc ){ 2181 goto getAndInitPage_error1; 2182 } 2183 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); 2184 if( (*ppPage)->isInit==0 ){ 2185 btreePageFromDbPage(pDbPage, pgno, pBt); 2186 rc = btreeInitPage(*ppPage); 2187 if( rc!=SQLITE_OK ){ 2188 goto getAndInitPage_error2; 2189 } 2190 } 2191 assert( (*ppPage)->pgno==pgno ); 2192 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); 2193 2194 /* If obtaining a child page for a cursor, we must verify that the page is 2195 ** compatible with the root page. */ 2196 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ 2197 rc = SQLITE_CORRUPT_PGNO(pgno); 2198 goto getAndInitPage_error2; 2199 } 2200 return SQLITE_OK; 2201 2202 getAndInitPage_error2: 2203 releasePage(*ppPage); 2204 getAndInitPage_error1: 2205 if( pCur ){ 2206 pCur->iPage--; 2207 pCur->pPage = pCur->apPage[pCur->iPage]; 2208 } 2209 testcase( pgno==0 ); 2210 assert( pgno!=0 || rc==SQLITE_CORRUPT ); 2211 return rc; 2212 } 2213 2214 /* 2215 ** Release a MemPage. This should be called once for each prior 2216 ** call to btreeGetPage. 2217 ** 2218 ** Page1 is a special case and must be released using releasePageOne(). 2219 */ 2220 static void releasePageNotNull(MemPage *pPage){ 2221 assert( pPage->aData ); 2222 assert( pPage->pBt ); 2223 assert( pPage->pDbPage!=0 ); 2224 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2225 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); 2226 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2227 sqlite3PagerUnrefNotNull(pPage->pDbPage); 2228 } 2229 static void releasePage(MemPage *pPage){ 2230 if( pPage ) releasePageNotNull(pPage); 2231 } 2232 static void releasePageOne(MemPage *pPage){ 2233 assert( pPage!=0 ); 2234 assert( pPage->aData ); 2235 assert( pPage->pBt ); 2236 assert( pPage->pDbPage!=0 ); 2237 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 2238 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); 2239 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2240 sqlite3PagerUnrefPageOne(pPage->pDbPage); 2241 } 2242 2243 /* 2244 ** Get an unused page. 2245 ** 2246 ** This works just like btreeGetPage() with the addition: 2247 ** 2248 ** * If the page is already in use for some other purpose, immediately 2249 ** release it and return an SQLITE_CURRUPT error. 2250 ** * Make sure the isInit flag is clear 2251 */ 2252 static int btreeGetUnusedPage( 2253 BtShared *pBt, /* The btree */ 2254 Pgno pgno, /* Number of the page to fetch */ 2255 MemPage **ppPage, /* Return the page in this parameter */ 2256 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ 2257 ){ 2258 int rc = btreeGetPage(pBt, pgno, ppPage, flags); 2259 if( rc==SQLITE_OK ){ 2260 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ 2261 releasePage(*ppPage); 2262 *ppPage = 0; 2263 return SQLITE_CORRUPT_BKPT; 2264 } 2265 (*ppPage)->isInit = 0; 2266 }else{ 2267 *ppPage = 0; 2268 } 2269 return rc; 2270 } 2271 2272 2273 /* 2274 ** During a rollback, when the pager reloads information into the cache 2275 ** so that the cache is restored to its original state at the start of 2276 ** the transaction, for each page restored this routine is called. 2277 ** 2278 ** This routine needs to reset the extra data section at the end of the 2279 ** page to agree with the restored data. 2280 */ 2281 static void pageReinit(DbPage *pData){ 2282 MemPage *pPage; 2283 pPage = (MemPage *)sqlite3PagerGetExtra(pData); 2284 assert( sqlite3PagerPageRefcount(pData)>0 ); 2285 if( pPage->isInit ){ 2286 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 2287 pPage->isInit = 0; 2288 if( sqlite3PagerPageRefcount(pData)>1 ){ 2289 /* pPage might not be a btree page; it might be an overflow page 2290 ** or ptrmap page or a free page. In those cases, the following 2291 ** call to btreeInitPage() will likely return SQLITE_CORRUPT. 2292 ** But no harm is done by this. And it is very important that 2293 ** btreeInitPage() be called on every btree page so we make 2294 ** the call for every page that comes in for re-initing. */ 2295 btreeInitPage(pPage); 2296 } 2297 } 2298 } 2299 2300 /* 2301 ** Invoke the busy handler for a btree. 2302 */ 2303 static int btreeInvokeBusyHandler(void *pArg){ 2304 BtShared *pBt = (BtShared*)pArg; 2305 assert( pBt->db ); 2306 assert( sqlite3_mutex_held(pBt->db->mutex) ); 2307 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); 2308 } 2309 2310 /* 2311 ** Open a database file. 2312 ** 2313 ** zFilename is the name of the database file. If zFilename is NULL 2314 ** then an ephemeral database is created. The ephemeral database might 2315 ** be exclusively in memory, or it might use a disk-based memory cache. 2316 ** Either way, the ephemeral database will be automatically deleted 2317 ** when sqlite3BtreeClose() is called. 2318 ** 2319 ** If zFilename is ":memory:" then an in-memory database is created 2320 ** that is automatically destroyed when it is closed. 2321 ** 2322 ** The "flags" parameter is a bitmask that might contain bits like 2323 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. 2324 ** 2325 ** If the database is already opened in the same database connection 2326 ** and we are in shared cache mode, then the open will fail with an 2327 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared 2328 ** objects in the same database connection since doing so will lead 2329 ** to problems with locking. 2330 */ 2331 int sqlite3BtreeOpen( 2332 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ 2333 const char *zFilename, /* Name of the file containing the BTree database */ 2334 sqlite3 *db, /* Associated database handle */ 2335 Btree **ppBtree, /* Pointer to new Btree object written here */ 2336 int flags, /* Options */ 2337 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ 2338 ){ 2339 BtShared *pBt = 0; /* Shared part of btree structure */ 2340 Btree *p; /* Handle to return */ 2341 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ 2342 int rc = SQLITE_OK; /* Result code from this function */ 2343 u8 nReserve; /* Byte of unused space on each page */ 2344 unsigned char zDbHeader[100]; /* Database header content */ 2345 2346 /* True if opening an ephemeral, temporary database */ 2347 const int isTempDb = zFilename==0 || zFilename[0]==0; 2348 2349 /* Set the variable isMemdb to true for an in-memory database, or 2350 ** false for a file-based database. 2351 */ 2352 #ifdef SQLITE_OMIT_MEMORYDB 2353 const int isMemdb = 0; 2354 #else 2355 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) 2356 || (isTempDb && sqlite3TempInMemory(db)) 2357 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; 2358 #endif 2359 2360 assert( db!=0 ); 2361 assert( pVfs!=0 ); 2362 assert( sqlite3_mutex_held(db->mutex) ); 2363 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ 2364 2365 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ 2366 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); 2367 2368 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ 2369 assert( (flags & BTREE_SINGLE)==0 || isTempDb ); 2370 2371 if( isMemdb ){ 2372 flags |= BTREE_MEMORY; 2373 } 2374 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ 2375 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; 2376 } 2377 p = sqlite3MallocZero(sizeof(Btree)); 2378 if( !p ){ 2379 return SQLITE_NOMEM_BKPT; 2380 } 2381 p->inTrans = TRANS_NONE; 2382 p->db = db; 2383 #ifndef SQLITE_OMIT_SHARED_CACHE 2384 p->lock.pBtree = p; 2385 p->lock.iTable = 1; 2386 #endif 2387 2388 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2389 /* 2390 ** If this Btree is a candidate for shared cache, try to find an 2391 ** existing BtShared object that we can share with 2392 */ 2393 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ 2394 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ 2395 int nFilename = sqlite3Strlen30(zFilename)+1; 2396 int nFullPathname = pVfs->mxPathname+1; 2397 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); 2398 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2399 2400 p->sharable = 1; 2401 if( !zFullPathname ){ 2402 sqlite3_free(p); 2403 return SQLITE_NOMEM_BKPT; 2404 } 2405 if( isMemdb ){ 2406 memcpy(zFullPathname, zFilename, nFilename); 2407 }else{ 2408 rc = sqlite3OsFullPathname(pVfs, zFilename, 2409 nFullPathname, zFullPathname); 2410 if( rc ){ 2411 if( rc==SQLITE_OK_SYMLINK ){ 2412 rc = SQLITE_OK; 2413 }else{ 2414 sqlite3_free(zFullPathname); 2415 sqlite3_free(p); 2416 return rc; 2417 } 2418 } 2419 } 2420 #if SQLITE_THREADSAFE 2421 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); 2422 sqlite3_mutex_enter(mutexOpen); 2423 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); 2424 sqlite3_mutex_enter(mutexShared); 2425 #endif 2426 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ 2427 assert( pBt->nRef>0 ); 2428 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) 2429 && sqlite3PagerVfs(pBt->pPager)==pVfs ){ 2430 int iDb; 2431 for(iDb=db->nDb-1; iDb>=0; iDb--){ 2432 Btree *pExisting = db->aDb[iDb].pBt; 2433 if( pExisting && pExisting->pBt==pBt ){ 2434 sqlite3_mutex_leave(mutexShared); 2435 sqlite3_mutex_leave(mutexOpen); 2436 sqlite3_free(zFullPathname); 2437 sqlite3_free(p); 2438 return SQLITE_CONSTRAINT; 2439 } 2440 } 2441 p->pBt = pBt; 2442 pBt->nRef++; 2443 break; 2444 } 2445 } 2446 sqlite3_mutex_leave(mutexShared); 2447 sqlite3_free(zFullPathname); 2448 } 2449 #ifdef SQLITE_DEBUG 2450 else{ 2451 /* In debug mode, we mark all persistent databases as sharable 2452 ** even when they are not. This exercises the locking code and 2453 ** gives more opportunity for asserts(sqlite3_mutex_held()) 2454 ** statements to find locking problems. 2455 */ 2456 p->sharable = 1; 2457 } 2458 #endif 2459 } 2460 #endif 2461 if( pBt==0 ){ 2462 /* 2463 ** The following asserts make sure that structures used by the btree are 2464 ** the right size. This is to guard against size changes that result 2465 ** when compiling on a different architecture. 2466 */ 2467 assert( sizeof(i64)==8 ); 2468 assert( sizeof(u64)==8 ); 2469 assert( sizeof(u32)==4 ); 2470 assert( sizeof(u16)==2 ); 2471 assert( sizeof(Pgno)==4 ); 2472 2473 pBt = sqlite3MallocZero( sizeof(*pBt) ); 2474 if( pBt==0 ){ 2475 rc = SQLITE_NOMEM_BKPT; 2476 goto btree_open_out; 2477 } 2478 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, 2479 sizeof(MemPage), flags, vfsFlags, pageReinit); 2480 if( rc==SQLITE_OK ){ 2481 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); 2482 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); 2483 } 2484 if( rc!=SQLITE_OK ){ 2485 goto btree_open_out; 2486 } 2487 pBt->openFlags = (u8)flags; 2488 pBt->db = db; 2489 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt); 2490 p->pBt = pBt; 2491 2492 pBt->pCursor = 0; 2493 pBt->pPage1 = 0; 2494 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; 2495 #if defined(SQLITE_SECURE_DELETE) 2496 pBt->btsFlags |= BTS_SECURE_DELETE; 2497 #elif defined(SQLITE_FAST_SECURE_DELETE) 2498 pBt->btsFlags |= BTS_OVERWRITE; 2499 #endif 2500 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 2501 ** determined by the 2-byte integer located at an offset of 16 bytes from 2502 ** the beginning of the database file. */ 2503 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); 2504 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE 2505 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ 2506 pBt->pageSize = 0; 2507 #ifndef SQLITE_OMIT_AUTOVACUUM 2508 /* If the magic name ":memory:" will create an in-memory database, then 2509 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if 2510 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if 2511 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a 2512 ** regular file-name. In this case the auto-vacuum applies as per normal. 2513 */ 2514 if( zFilename && !isMemdb ){ 2515 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); 2516 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); 2517 } 2518 #endif 2519 nReserve = 0; 2520 }else{ 2521 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is 2522 ** determined by the one-byte unsigned integer found at an offset of 20 2523 ** into the database file header. */ 2524 nReserve = zDbHeader[20]; 2525 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2526 #ifndef SQLITE_OMIT_AUTOVACUUM 2527 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); 2528 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); 2529 #endif 2530 } 2531 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2532 if( rc ) goto btree_open_out; 2533 pBt->usableSize = pBt->pageSize - nReserve; 2534 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ 2535 2536 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2537 /* Add the new BtShared object to the linked list sharable BtShareds. 2538 */ 2539 pBt->nRef = 1; 2540 if( p->sharable ){ 2541 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) 2542 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) 2543 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ 2544 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); 2545 if( pBt->mutex==0 ){ 2546 rc = SQLITE_NOMEM_BKPT; 2547 goto btree_open_out; 2548 } 2549 } 2550 sqlite3_mutex_enter(mutexShared); 2551 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); 2552 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; 2553 sqlite3_mutex_leave(mutexShared); 2554 } 2555 #endif 2556 } 2557 2558 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) 2559 /* If the new Btree uses a sharable pBtShared, then link the new 2560 ** Btree into the list of all sharable Btrees for the same connection. 2561 ** The list is kept in ascending order by pBt address. 2562 */ 2563 if( p->sharable ){ 2564 int i; 2565 Btree *pSib; 2566 for(i=0; i<db->nDb; i++){ 2567 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ 2568 while( pSib->pPrev ){ pSib = pSib->pPrev; } 2569 if( (uptr)p->pBt<(uptr)pSib->pBt ){ 2570 p->pNext = pSib; 2571 p->pPrev = 0; 2572 pSib->pPrev = p; 2573 }else{ 2574 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ 2575 pSib = pSib->pNext; 2576 } 2577 p->pNext = pSib->pNext; 2578 p->pPrev = pSib; 2579 if( p->pNext ){ 2580 p->pNext->pPrev = p; 2581 } 2582 pSib->pNext = p; 2583 } 2584 break; 2585 } 2586 } 2587 } 2588 #endif 2589 *ppBtree = p; 2590 2591 btree_open_out: 2592 if( rc!=SQLITE_OK ){ 2593 if( pBt && pBt->pPager ){ 2594 sqlite3PagerClose(pBt->pPager, 0); 2595 } 2596 sqlite3_free(pBt); 2597 sqlite3_free(p); 2598 *ppBtree = 0; 2599 }else{ 2600 sqlite3_file *pFile; 2601 2602 /* If the B-Tree was successfully opened, set the pager-cache size to the 2603 ** default value. Except, when opening on an existing shared pager-cache, 2604 ** do not change the pager-cache size. 2605 */ 2606 if( sqlite3BtreeSchema(p, 0, 0)==0 ){ 2607 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); 2608 } 2609 2610 pFile = sqlite3PagerFile(pBt->pPager); 2611 if( pFile->pMethods ){ 2612 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db); 2613 } 2614 } 2615 if( mutexOpen ){ 2616 assert( sqlite3_mutex_held(mutexOpen) ); 2617 sqlite3_mutex_leave(mutexOpen); 2618 } 2619 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); 2620 return rc; 2621 } 2622 2623 /* 2624 ** Decrement the BtShared.nRef counter. When it reaches zero, 2625 ** remove the BtShared structure from the sharing list. Return 2626 ** true if the BtShared.nRef counter reaches zero and return 2627 ** false if it is still positive. 2628 */ 2629 static int removeFromSharingList(BtShared *pBt){ 2630 #ifndef SQLITE_OMIT_SHARED_CACHE 2631 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) 2632 BtShared *pList; 2633 int removed = 0; 2634 2635 assert( sqlite3_mutex_notheld(pBt->mutex) ); 2636 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) 2637 sqlite3_mutex_enter(pMaster); 2638 pBt->nRef--; 2639 if( pBt->nRef<=0 ){ 2640 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ 2641 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; 2642 }else{ 2643 pList = GLOBAL(BtShared*,sqlite3SharedCacheList); 2644 while( ALWAYS(pList) && pList->pNext!=pBt ){ 2645 pList=pList->pNext; 2646 } 2647 if( ALWAYS(pList) ){ 2648 pList->pNext = pBt->pNext; 2649 } 2650 } 2651 if( SQLITE_THREADSAFE ){ 2652 sqlite3_mutex_free(pBt->mutex); 2653 } 2654 removed = 1; 2655 } 2656 sqlite3_mutex_leave(pMaster); 2657 return removed; 2658 #else 2659 return 1; 2660 #endif 2661 } 2662 2663 /* 2664 ** Make sure pBt->pTmpSpace points to an allocation of 2665 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child 2666 ** pointer. 2667 */ 2668 static void allocateTempSpace(BtShared *pBt){ 2669 if( !pBt->pTmpSpace ){ 2670 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); 2671 2672 /* One of the uses of pBt->pTmpSpace is to format cells before 2673 ** inserting them into a leaf page (function fillInCell()). If 2674 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes 2675 ** by the various routines that manipulate binary cells. Which 2676 ** can mean that fillInCell() only initializes the first 2 or 3 2677 ** bytes of pTmpSpace, but that the first 4 bytes are copied from 2678 ** it into a database page. This is not actually a problem, but it 2679 ** does cause a valgrind error when the 1 or 2 bytes of unitialized 2680 ** data is passed to system call write(). So to avoid this error, 2681 ** zero the first 4 bytes of temp space here. 2682 ** 2683 ** Also: Provide four bytes of initialized space before the 2684 ** beginning of pTmpSpace as an area available to prepend the 2685 ** left-child pointer to the beginning of a cell. 2686 */ 2687 if( pBt->pTmpSpace ){ 2688 memset(pBt->pTmpSpace, 0, 8); 2689 pBt->pTmpSpace += 4; 2690 } 2691 } 2692 } 2693 2694 /* 2695 ** Free the pBt->pTmpSpace allocation 2696 */ 2697 static void freeTempSpace(BtShared *pBt){ 2698 if( pBt->pTmpSpace ){ 2699 pBt->pTmpSpace -= 4; 2700 sqlite3PageFree(pBt->pTmpSpace); 2701 pBt->pTmpSpace = 0; 2702 } 2703 } 2704 2705 /* 2706 ** Close an open database and invalidate all cursors. 2707 */ 2708 int sqlite3BtreeClose(Btree *p){ 2709 BtShared *pBt = p->pBt; 2710 BtCursor *pCur; 2711 2712 /* Close all cursors opened via this handle. */ 2713 assert( sqlite3_mutex_held(p->db->mutex) ); 2714 sqlite3BtreeEnter(p); 2715 pCur = pBt->pCursor; 2716 while( pCur ){ 2717 BtCursor *pTmp = pCur; 2718 pCur = pCur->pNext; 2719 if( pTmp->pBtree==p ){ 2720 sqlite3BtreeCloseCursor(pTmp); 2721 } 2722 } 2723 2724 /* Rollback any active transaction and free the handle structure. 2725 ** The call to sqlite3BtreeRollback() drops any table-locks held by 2726 ** this handle. 2727 */ 2728 sqlite3BtreeRollback(p, SQLITE_OK, 0); 2729 sqlite3BtreeLeave(p); 2730 2731 /* If there are still other outstanding references to the shared-btree 2732 ** structure, return now. The remainder of this procedure cleans 2733 ** up the shared-btree. 2734 */ 2735 assert( p->wantToLock==0 && p->locked==0 ); 2736 if( !p->sharable || removeFromSharingList(pBt) ){ 2737 /* The pBt is no longer on the sharing list, so we can access 2738 ** it without having to hold the mutex. 2739 ** 2740 ** Clean out and delete the BtShared object. 2741 */ 2742 assert( !pBt->pCursor ); 2743 sqlite3PagerClose(pBt->pPager, p->db); 2744 if( pBt->xFreeSchema && pBt->pSchema ){ 2745 pBt->xFreeSchema(pBt->pSchema); 2746 } 2747 sqlite3DbFree(0, pBt->pSchema); 2748 freeTempSpace(pBt); 2749 sqlite3_free(pBt); 2750 } 2751 2752 #ifndef SQLITE_OMIT_SHARED_CACHE 2753 assert( p->wantToLock==0 ); 2754 assert( p->locked==0 ); 2755 if( p->pPrev ) p->pPrev->pNext = p->pNext; 2756 if( p->pNext ) p->pNext->pPrev = p->pPrev; 2757 #endif 2758 2759 sqlite3_free(p); 2760 return SQLITE_OK; 2761 } 2762 2763 /* 2764 ** Change the "soft" limit on the number of pages in the cache. 2765 ** Unused and unmodified pages will be recycled when the number of 2766 ** pages in the cache exceeds this soft limit. But the size of the 2767 ** cache is allowed to grow larger than this limit if it contains 2768 ** dirty pages or pages still in active use. 2769 */ 2770 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ 2771 BtShared *pBt = p->pBt; 2772 assert( sqlite3_mutex_held(p->db->mutex) ); 2773 sqlite3BtreeEnter(p); 2774 sqlite3PagerSetCachesize(pBt->pPager, mxPage); 2775 sqlite3BtreeLeave(p); 2776 return SQLITE_OK; 2777 } 2778 2779 /* 2780 ** Change the "spill" limit on the number of pages in the cache. 2781 ** If the number of pages exceeds this limit during a write transaction, 2782 ** the pager might attempt to "spill" pages to the journal early in 2783 ** order to free up memory. 2784 ** 2785 ** The value returned is the current spill size. If zero is passed 2786 ** as an argument, no changes are made to the spill size setting, so 2787 ** using mxPage of 0 is a way to query the current spill size. 2788 */ 2789 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ 2790 BtShared *pBt = p->pBt; 2791 int res; 2792 assert( sqlite3_mutex_held(p->db->mutex) ); 2793 sqlite3BtreeEnter(p); 2794 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); 2795 sqlite3BtreeLeave(p); 2796 return res; 2797 } 2798 2799 #if SQLITE_MAX_MMAP_SIZE>0 2800 /* 2801 ** Change the limit on the amount of the database file that may be 2802 ** memory mapped. 2803 */ 2804 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ 2805 BtShared *pBt = p->pBt; 2806 assert( sqlite3_mutex_held(p->db->mutex) ); 2807 sqlite3BtreeEnter(p); 2808 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); 2809 sqlite3BtreeLeave(p); 2810 return SQLITE_OK; 2811 } 2812 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ 2813 2814 /* 2815 ** Change the way data is synced to disk in order to increase or decrease 2816 ** how well the database resists damage due to OS crashes and power 2817 ** failures. Level 1 is the same as asynchronous (no syncs() occur and 2818 ** there is a high probability of damage) Level 2 is the default. There 2819 ** is a very low but non-zero probability of damage. Level 3 reduces the 2820 ** probability of damage to near zero but with a write performance reduction. 2821 */ 2822 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 2823 int sqlite3BtreeSetPagerFlags( 2824 Btree *p, /* The btree to set the safety level on */ 2825 unsigned pgFlags /* Various PAGER_* flags */ 2826 ){ 2827 BtShared *pBt = p->pBt; 2828 assert( sqlite3_mutex_held(p->db->mutex) ); 2829 sqlite3BtreeEnter(p); 2830 sqlite3PagerSetFlags(pBt->pPager, pgFlags); 2831 sqlite3BtreeLeave(p); 2832 return SQLITE_OK; 2833 } 2834 #endif 2835 2836 /* 2837 ** Change the default pages size and the number of reserved bytes per page. 2838 ** Or, if the page size has already been fixed, return SQLITE_READONLY 2839 ** without changing anything. 2840 ** 2841 ** The page size must be a power of 2 between 512 and 65536. If the page 2842 ** size supplied does not meet this constraint then the page size is not 2843 ** changed. 2844 ** 2845 ** Page sizes are constrained to be a power of two so that the region 2846 ** of the database file used for locking (beginning at PENDING_BYTE, 2847 ** the first byte past the 1GB boundary, 0x40000000) needs to occur 2848 ** at the beginning of a page. 2849 ** 2850 ** If parameter nReserve is less than zero, then the number of reserved 2851 ** bytes per page is left unchanged. 2852 ** 2853 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size 2854 ** and autovacuum mode can no longer be changed. 2855 */ 2856 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ 2857 int rc = SQLITE_OK; 2858 int x; 2859 BtShared *pBt = p->pBt; 2860 assert( nReserve>=0 && nReserve<=255 ); 2861 sqlite3BtreeEnter(p); 2862 pBt->nReserveWanted = nReserve; 2863 x = pBt->pageSize - pBt->usableSize; 2864 if( nReserve<x ) nReserve = x; 2865 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ 2866 sqlite3BtreeLeave(p); 2867 return SQLITE_READONLY; 2868 } 2869 assert( nReserve>=0 && nReserve<=255 ); 2870 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && 2871 ((pageSize-1)&pageSize)==0 ){ 2872 assert( (pageSize & 7)==0 ); 2873 assert( !pBt->pCursor ); 2874 pBt->pageSize = (u32)pageSize; 2875 freeTempSpace(pBt); 2876 } 2877 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); 2878 pBt->usableSize = pBt->pageSize - (u16)nReserve; 2879 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; 2880 sqlite3BtreeLeave(p); 2881 return rc; 2882 } 2883 2884 /* 2885 ** Return the currently defined page size 2886 */ 2887 int sqlite3BtreeGetPageSize(Btree *p){ 2888 return p->pBt->pageSize; 2889 } 2890 2891 /* 2892 ** This function is similar to sqlite3BtreeGetReserve(), except that it 2893 ** may only be called if it is guaranteed that the b-tree mutex is already 2894 ** held. 2895 ** 2896 ** This is useful in one special case in the backup API code where it is 2897 ** known that the shared b-tree mutex is held, but the mutex on the 2898 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() 2899 ** were to be called, it might collide with some other operation on the 2900 ** database handle that owns *p, causing undefined behavior. 2901 */ 2902 int sqlite3BtreeGetReserveNoMutex(Btree *p){ 2903 int n; 2904 assert( sqlite3_mutex_held(p->pBt->mutex) ); 2905 n = p->pBt->pageSize - p->pBt->usableSize; 2906 return n; 2907 } 2908 2909 /* 2910 ** Return the number of bytes of space at the end of every page that 2911 ** are intentually left unused. This is the "reserved" space that is 2912 ** sometimes used by extensions. 2913 ** 2914 ** The value returned is the larger of the current reserve size and 2915 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES. 2916 ** The amount of reserve can only grow - never shrink. 2917 */ 2918 int sqlite3BtreeGetRequestedReserve(Btree *p){ 2919 int n1, n2; 2920 sqlite3BtreeEnter(p); 2921 n1 = (int)p->pBt->nReserveWanted; 2922 n2 = sqlite3BtreeGetReserveNoMutex(p); 2923 sqlite3BtreeLeave(p); 2924 return n1>n2 ? n1 : n2; 2925 } 2926 2927 2928 /* 2929 ** Set the maximum page count for a database if mxPage is positive. 2930 ** No changes are made if mxPage is 0 or negative. 2931 ** Regardless of the value of mxPage, return the maximum page count. 2932 */ 2933 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ 2934 int n; 2935 sqlite3BtreeEnter(p); 2936 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); 2937 sqlite3BtreeLeave(p); 2938 return n; 2939 } 2940 2941 /* 2942 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags: 2943 ** 2944 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared 2945 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared 2946 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set 2947 ** newFlag==(-1) No changes 2948 ** 2949 ** This routine acts as a query if newFlag is less than zero 2950 ** 2951 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but 2952 ** freelist leaf pages are not written back to the database. Thus in-page 2953 ** deleted content is cleared, but freelist deleted content is not. 2954 ** 2955 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition 2956 ** that freelist leaf pages are written back into the database, increasing 2957 ** the amount of disk I/O. 2958 */ 2959 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ 2960 int b; 2961 if( p==0 ) return 0; 2962 sqlite3BtreeEnter(p); 2963 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 ); 2964 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) ); 2965 if( newFlag>=0 ){ 2966 p->pBt->btsFlags &= ~BTS_FAST_SECURE; 2967 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag; 2968 } 2969 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE; 2970 sqlite3BtreeLeave(p); 2971 return b; 2972 } 2973 2974 /* 2975 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' 2976 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it 2977 ** is disabled. The default value for the auto-vacuum property is 2978 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. 2979 */ 2980 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ 2981 #ifdef SQLITE_OMIT_AUTOVACUUM 2982 return SQLITE_READONLY; 2983 #else 2984 BtShared *pBt = p->pBt; 2985 int rc = SQLITE_OK; 2986 u8 av = (u8)autoVacuum; 2987 2988 sqlite3BtreeEnter(p); 2989 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ 2990 rc = SQLITE_READONLY; 2991 }else{ 2992 pBt->autoVacuum = av ?1:0; 2993 pBt->incrVacuum = av==2 ?1:0; 2994 } 2995 sqlite3BtreeLeave(p); 2996 return rc; 2997 #endif 2998 } 2999 3000 /* 3001 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 3002 ** enabled 1 is returned. Otherwise 0. 3003 */ 3004 int sqlite3BtreeGetAutoVacuum(Btree *p){ 3005 #ifdef SQLITE_OMIT_AUTOVACUUM 3006 return BTREE_AUTOVACUUM_NONE; 3007 #else 3008 int rc; 3009 sqlite3BtreeEnter(p); 3010 rc = ( 3011 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: 3012 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: 3013 BTREE_AUTOVACUUM_INCR 3014 ); 3015 sqlite3BtreeLeave(p); 3016 return rc; 3017 #endif 3018 } 3019 3020 /* 3021 ** If the user has not set the safety-level for this database connection 3022 ** using "PRAGMA synchronous", and if the safety-level is not already 3023 ** set to the value passed to this function as the second parameter, 3024 ** set it so. 3025 */ 3026 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \ 3027 && !defined(SQLITE_OMIT_WAL) 3028 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){ 3029 sqlite3 *db; 3030 Db *pDb; 3031 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ 3032 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } 3033 if( pDb->bSyncSet==0 3034 && pDb->safety_level!=safety_level 3035 && pDb!=&db->aDb[1] 3036 ){ 3037 pDb->safety_level = safety_level; 3038 sqlite3PagerSetFlags(pBt->pPager, 3039 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); 3040 } 3041 } 3042 } 3043 #else 3044 # define setDefaultSyncFlag(pBt,safety_level) 3045 #endif 3046 3047 /* Forward declaration */ 3048 static int newDatabase(BtShared*); 3049 3050 3051 /* 3052 ** Get a reference to pPage1 of the database file. This will 3053 ** also acquire a readlock on that file. 3054 ** 3055 ** SQLITE_OK is returned on success. If the file is not a 3056 ** well-formed database file, then SQLITE_CORRUPT is returned. 3057 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM 3058 ** is returned if we run out of memory. 3059 */ 3060 static int lockBtree(BtShared *pBt){ 3061 int rc; /* Result code from subfunctions */ 3062 MemPage *pPage1; /* Page 1 of the database file */ 3063 u32 nPage; /* Number of pages in the database */ 3064 u32 nPageFile = 0; /* Number of pages in the database file */ 3065 u32 nPageHeader; /* Number of pages in the database according to hdr */ 3066 3067 assert( sqlite3_mutex_held(pBt->mutex) ); 3068 assert( pBt->pPage1==0 ); 3069 rc = sqlite3PagerSharedLock(pBt->pPager); 3070 if( rc!=SQLITE_OK ) return rc; 3071 rc = btreeGetPage(pBt, 1, &pPage1, 0); 3072 if( rc!=SQLITE_OK ) return rc; 3073 3074 /* Do some checking to help insure the file we opened really is 3075 ** a valid database file. 3076 */ 3077 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); 3078 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile); 3079 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ 3080 nPage = nPageFile; 3081 } 3082 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){ 3083 nPage = 0; 3084 } 3085 if( nPage>0 ){ 3086 u32 pageSize; 3087 u32 usableSize; 3088 u8 *page1 = pPage1->aData; 3089 rc = SQLITE_NOTADB; 3090 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins 3091 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d 3092 ** 61 74 20 33 00. */ 3093 if( memcmp(page1, zMagicHeader, 16)!=0 ){ 3094 goto page1_init_failed; 3095 } 3096 3097 #ifdef SQLITE_OMIT_WAL 3098 if( page1[18]>1 ){ 3099 pBt->btsFlags |= BTS_READ_ONLY; 3100 } 3101 if( page1[19]>1 ){ 3102 goto page1_init_failed; 3103 } 3104 #else 3105 if( page1[18]>2 ){ 3106 pBt->btsFlags |= BTS_READ_ONLY; 3107 } 3108 if( page1[19]>2 ){ 3109 goto page1_init_failed; 3110 } 3111 3112 /* If the write version is set to 2, this database should be accessed 3113 ** in WAL mode. If the log is not already open, open it now. Then 3114 ** return SQLITE_OK and return without populating BtShared.pPage1. 3115 ** The caller detects this and calls this function again. This is 3116 ** required as the version of page 1 currently in the page1 buffer 3117 ** may not be the latest version - there may be a newer one in the log 3118 ** file. 3119 */ 3120 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ 3121 int isOpen = 0; 3122 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); 3123 if( rc!=SQLITE_OK ){ 3124 goto page1_init_failed; 3125 }else{ 3126 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1); 3127 if( isOpen==0 ){ 3128 releasePageOne(pPage1); 3129 return SQLITE_OK; 3130 } 3131 } 3132 rc = SQLITE_NOTADB; 3133 }else{ 3134 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1); 3135 } 3136 #endif 3137 3138 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload 3139 ** fractions and the leaf payload fraction values must be 64, 32, and 32. 3140 ** 3141 ** The original design allowed these amounts to vary, but as of 3142 ** version 3.6.0, we require them to be fixed. 3143 */ 3144 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ 3145 goto page1_init_failed; 3146 } 3147 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is 3148 ** determined by the 2-byte integer located at an offset of 16 bytes from 3149 ** the beginning of the database file. */ 3150 pageSize = (page1[16]<<8) | (page1[17]<<16); 3151 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two 3152 ** between 512 and 65536 inclusive. */ 3153 if( ((pageSize-1)&pageSize)!=0 3154 || pageSize>SQLITE_MAX_PAGE_SIZE 3155 || pageSize<=256 3156 ){ 3157 goto page1_init_failed; 3158 } 3159 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 3160 assert( (pageSize & 7)==0 ); 3161 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte 3162 ** integer at offset 20 is the number of bytes of space at the end of 3163 ** each page to reserve for extensions. 3164 ** 3165 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is 3166 ** determined by the one-byte unsigned integer found at an offset of 20 3167 ** into the database file header. */ 3168 usableSize = pageSize - page1[20]; 3169 if( (u32)pageSize!=pBt->pageSize ){ 3170 /* After reading the first page of the database assuming a page size 3171 ** of BtShared.pageSize, we have discovered that the page-size is 3172 ** actually pageSize. Unlock the database, leave pBt->pPage1 at 3173 ** zero and return SQLITE_OK. The caller will call this function 3174 ** again with the correct page-size. 3175 */ 3176 releasePageOne(pPage1); 3177 pBt->usableSize = usableSize; 3178 pBt->pageSize = pageSize; 3179 freeTempSpace(pBt); 3180 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, 3181 pageSize-usableSize); 3182 return rc; 3183 } 3184 if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){ 3185 rc = SQLITE_CORRUPT_BKPT; 3186 goto page1_init_failed; 3187 } 3188 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to 3189 ** be less than 480. In other words, if the page size is 512, then the 3190 ** reserved space size cannot exceed 32. */ 3191 if( usableSize<480 ){ 3192 goto page1_init_failed; 3193 } 3194 pBt->pageSize = pageSize; 3195 pBt->usableSize = usableSize; 3196 #ifndef SQLITE_OMIT_AUTOVACUUM 3197 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); 3198 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); 3199 #endif 3200 } 3201 3202 /* maxLocal is the maximum amount of payload to store locally for 3203 ** a cell. Make sure it is small enough so that at least minFanout 3204 ** cells can will fit on one page. We assume a 10-byte page header. 3205 ** Besides the payload, the cell must store: 3206 ** 2-byte pointer to the cell 3207 ** 4-byte child pointer 3208 ** 9-byte nKey value 3209 ** 4-byte nData value 3210 ** 4-byte overflow page pointer 3211 ** So a cell consists of a 2-byte pointer, a header which is as much as 3212 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow 3213 ** page pointer. 3214 */ 3215 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); 3216 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); 3217 pBt->maxLeaf = (u16)(pBt->usableSize - 35); 3218 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); 3219 if( pBt->maxLocal>127 ){ 3220 pBt->max1bytePayload = 127; 3221 }else{ 3222 pBt->max1bytePayload = (u8)pBt->maxLocal; 3223 } 3224 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); 3225 pBt->pPage1 = pPage1; 3226 pBt->nPage = nPage; 3227 return SQLITE_OK; 3228 3229 page1_init_failed: 3230 releasePageOne(pPage1); 3231 pBt->pPage1 = 0; 3232 return rc; 3233 } 3234 3235 #ifndef NDEBUG 3236 /* 3237 ** Return the number of cursors open on pBt. This is for use 3238 ** in assert() expressions, so it is only compiled if NDEBUG is not 3239 ** defined. 3240 ** 3241 ** Only write cursors are counted if wrOnly is true. If wrOnly is 3242 ** false then all cursors are counted. 3243 ** 3244 ** For the purposes of this routine, a cursor is any cursor that 3245 ** is capable of reading or writing to the database. Cursors that 3246 ** have been tripped into the CURSOR_FAULT state are not counted. 3247 */ 3248 static int countValidCursors(BtShared *pBt, int wrOnly){ 3249 BtCursor *pCur; 3250 int r = 0; 3251 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ 3252 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) 3253 && pCur->eState!=CURSOR_FAULT ) r++; 3254 } 3255 return r; 3256 } 3257 #endif 3258 3259 /* 3260 ** If there are no outstanding cursors and we are not in the middle 3261 ** of a transaction but there is a read lock on the database, then 3262 ** this routine unrefs the first page of the database file which 3263 ** has the effect of releasing the read lock. 3264 ** 3265 ** If there is a transaction in progress, this routine is a no-op. 3266 */ 3267 static void unlockBtreeIfUnused(BtShared *pBt){ 3268 assert( sqlite3_mutex_held(pBt->mutex) ); 3269 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); 3270 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ 3271 MemPage *pPage1 = pBt->pPage1; 3272 assert( pPage1->aData ); 3273 assert( sqlite3PagerRefcount(pBt->pPager)==1 ); 3274 pBt->pPage1 = 0; 3275 releasePageOne(pPage1); 3276 } 3277 } 3278 3279 /* 3280 ** If pBt points to an empty file then convert that empty file 3281 ** into a new empty database by initializing the first page of 3282 ** the database. 3283 */ 3284 static int newDatabase(BtShared *pBt){ 3285 MemPage *pP1; 3286 unsigned char *data; 3287 int rc; 3288 3289 assert( sqlite3_mutex_held(pBt->mutex) ); 3290 if( pBt->nPage>0 ){ 3291 return SQLITE_OK; 3292 } 3293 pP1 = pBt->pPage1; 3294 assert( pP1!=0 ); 3295 data = pP1->aData; 3296 rc = sqlite3PagerWrite(pP1->pDbPage); 3297 if( rc ) return rc; 3298 memcpy(data, zMagicHeader, sizeof(zMagicHeader)); 3299 assert( sizeof(zMagicHeader)==16 ); 3300 data[16] = (u8)((pBt->pageSize>>8)&0xff); 3301 data[17] = (u8)((pBt->pageSize>>16)&0xff); 3302 data[18] = 1; 3303 data[19] = 1; 3304 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); 3305 data[20] = (u8)(pBt->pageSize - pBt->usableSize); 3306 data[21] = 64; 3307 data[22] = 32; 3308 data[23] = 32; 3309 memset(&data[24], 0, 100-24); 3310 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); 3311 pBt->btsFlags |= BTS_PAGESIZE_FIXED; 3312 #ifndef SQLITE_OMIT_AUTOVACUUM 3313 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); 3314 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); 3315 put4byte(&data[36 + 4*4], pBt->autoVacuum); 3316 put4byte(&data[36 + 7*4], pBt->incrVacuum); 3317 #endif 3318 pBt->nPage = 1; 3319 data[31] = 1; 3320 return SQLITE_OK; 3321 } 3322 3323 /* 3324 ** Initialize the first page of the database file (creating a database 3325 ** consisting of a single page and no schema objects). Return SQLITE_OK 3326 ** if successful, or an SQLite error code otherwise. 3327 */ 3328 int sqlite3BtreeNewDb(Btree *p){ 3329 int rc; 3330 sqlite3BtreeEnter(p); 3331 p->pBt->nPage = 0; 3332 rc = newDatabase(p->pBt); 3333 sqlite3BtreeLeave(p); 3334 return rc; 3335 } 3336 3337 /* 3338 ** Attempt to start a new transaction. A write-transaction 3339 ** is started if the second argument is nonzero, otherwise a read- 3340 ** transaction. If the second argument is 2 or more and exclusive 3341 ** transaction is started, meaning that no other process is allowed 3342 ** to access the database. A preexisting transaction may not be 3343 ** upgraded to exclusive by calling this routine a second time - the 3344 ** exclusivity flag only works for a new transaction. 3345 ** 3346 ** A write-transaction must be started before attempting any 3347 ** changes to the database. None of the following routines 3348 ** will work unless a transaction is started first: 3349 ** 3350 ** sqlite3BtreeCreateTable() 3351 ** sqlite3BtreeCreateIndex() 3352 ** sqlite3BtreeClearTable() 3353 ** sqlite3BtreeDropTable() 3354 ** sqlite3BtreeInsert() 3355 ** sqlite3BtreeDelete() 3356 ** sqlite3BtreeUpdateMeta() 3357 ** 3358 ** If an initial attempt to acquire the lock fails because of lock contention 3359 ** and the database was previously unlocked, then invoke the busy handler 3360 ** if there is one. But if there was previously a read-lock, do not 3361 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is 3362 ** returned when there is already a read-lock in order to avoid a deadlock. 3363 ** 3364 ** Suppose there are two processes A and B. A has a read lock and B has 3365 ** a reserved lock. B tries to promote to exclusive but is blocked because 3366 ** of A's read lock. A tries to promote to reserved but is blocked by B. 3367 ** One or the other of the two processes must give way or there can be 3368 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback 3369 ** when A already has a read lock, we encourage A to give up and let B 3370 ** proceed. 3371 */ 3372 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){ 3373 BtShared *pBt = p->pBt; 3374 Pager *pPager = pBt->pPager; 3375 int rc = SQLITE_OK; 3376 3377 sqlite3BtreeEnter(p); 3378 btreeIntegrity(p); 3379 3380 /* If the btree is already in a write-transaction, or it 3381 ** is already in a read-transaction and a read-transaction 3382 ** is requested, this is a no-op. 3383 */ 3384 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ 3385 goto trans_begun; 3386 } 3387 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); 3388 3389 if( (p->db->flags & SQLITE_ResetDatabase) 3390 && sqlite3PagerIsreadonly(pPager)==0 3391 ){ 3392 pBt->btsFlags &= ~BTS_READ_ONLY; 3393 } 3394 3395 /* Write transactions are not possible on a read-only database */ 3396 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ 3397 rc = SQLITE_READONLY; 3398 goto trans_begun; 3399 } 3400 3401 #ifndef SQLITE_OMIT_SHARED_CACHE 3402 { 3403 sqlite3 *pBlock = 0; 3404 /* If another database handle has already opened a write transaction 3405 ** on this shared-btree structure and a second write transaction is 3406 ** requested, return SQLITE_LOCKED. 3407 */ 3408 if( (wrflag && pBt->inTransaction==TRANS_WRITE) 3409 || (pBt->btsFlags & BTS_PENDING)!=0 3410 ){ 3411 pBlock = pBt->pWriter->db; 3412 }else if( wrflag>1 ){ 3413 BtLock *pIter; 3414 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ 3415 if( pIter->pBtree!=p ){ 3416 pBlock = pIter->pBtree->db; 3417 break; 3418 } 3419 } 3420 } 3421 if( pBlock ){ 3422 sqlite3ConnectionBlocked(p->db, pBlock); 3423 rc = SQLITE_LOCKED_SHAREDCACHE; 3424 goto trans_begun; 3425 } 3426 } 3427 #endif 3428 3429 /* Any read-only or read-write transaction implies a read-lock on 3430 ** page 1. So if some other shared-cache client already has a write-lock 3431 ** on page 1, the transaction cannot be opened. */ 3432 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); 3433 if( SQLITE_OK!=rc ) goto trans_begun; 3434 3435 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; 3436 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; 3437 do { 3438 sqlite3PagerWalDb(pPager, p->db); 3439 3440 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 3441 /* If transitioning from no transaction directly to a write transaction, 3442 ** block for the WRITER lock first if possible. */ 3443 if( pBt->pPage1==0 && wrflag ){ 3444 assert( pBt->inTransaction==TRANS_NONE ); 3445 rc = sqlite3PagerWalWriteLock(pPager, 1); 3446 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break; 3447 } 3448 #endif 3449 3450 /* Call lockBtree() until either pBt->pPage1 is populated or 3451 ** lockBtree() returns something other than SQLITE_OK. lockBtree() 3452 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after 3453 ** reading page 1 it discovers that the page-size of the database 3454 ** file is not pBt->pageSize. In this case lockBtree() will update 3455 ** pBt->pageSize to the page-size of the file on disk. 3456 */ 3457 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); 3458 3459 if( rc==SQLITE_OK && wrflag ){ 3460 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ 3461 rc = SQLITE_READONLY; 3462 }else{ 3463 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db)); 3464 if( rc==SQLITE_OK ){ 3465 rc = newDatabase(pBt); 3466 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){ 3467 /* if there was no transaction opened when this function was 3468 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error 3469 ** code to SQLITE_BUSY. */ 3470 rc = SQLITE_BUSY; 3471 } 3472 } 3473 } 3474 3475 if( rc!=SQLITE_OK ){ 3476 (void)sqlite3PagerWalWriteLock(pPager, 0); 3477 unlockBtreeIfUnused(pBt); 3478 } 3479 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && 3480 btreeInvokeBusyHandler(pBt) ); 3481 sqlite3PagerWalDb(pPager, 0); 3482 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 3483 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY; 3484 #endif 3485 3486 if( rc==SQLITE_OK ){ 3487 if( p->inTrans==TRANS_NONE ){ 3488 pBt->nTransaction++; 3489 #ifndef SQLITE_OMIT_SHARED_CACHE 3490 if( p->sharable ){ 3491 assert( p->lock.pBtree==p && p->lock.iTable==1 ); 3492 p->lock.eLock = READ_LOCK; 3493 p->lock.pNext = pBt->pLock; 3494 pBt->pLock = &p->lock; 3495 } 3496 #endif 3497 } 3498 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); 3499 if( p->inTrans>pBt->inTransaction ){ 3500 pBt->inTransaction = p->inTrans; 3501 } 3502 if( wrflag ){ 3503 MemPage *pPage1 = pBt->pPage1; 3504 #ifndef SQLITE_OMIT_SHARED_CACHE 3505 assert( !pBt->pWriter ); 3506 pBt->pWriter = p; 3507 pBt->btsFlags &= ~BTS_EXCLUSIVE; 3508 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; 3509 #endif 3510 3511 /* If the db-size header field is incorrect (as it may be if an old 3512 ** client has been writing the database file), update it now. Doing 3513 ** this sooner rather than later means the database size can safely 3514 ** re-read the database size from page 1 if a savepoint or transaction 3515 ** rollback occurs within the transaction. 3516 */ 3517 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ 3518 rc = sqlite3PagerWrite(pPage1->pDbPage); 3519 if( rc==SQLITE_OK ){ 3520 put4byte(&pPage1->aData[28], pBt->nPage); 3521 } 3522 } 3523 } 3524 } 3525 3526 trans_begun: 3527 if( rc==SQLITE_OK ){ 3528 if( pSchemaVersion ){ 3529 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]); 3530 } 3531 if( wrflag ){ 3532 /* This call makes sure that the pager has the correct number of 3533 ** open savepoints. If the second parameter is greater than 0 and 3534 ** the sub-journal is not already open, then it will be opened here. 3535 */ 3536 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint); 3537 } 3538 } 3539 3540 btreeIntegrity(p); 3541 sqlite3BtreeLeave(p); 3542 return rc; 3543 } 3544 3545 #ifndef SQLITE_OMIT_AUTOVACUUM 3546 3547 /* 3548 ** Set the pointer-map entries for all children of page pPage. Also, if 3549 ** pPage contains cells that point to overflow pages, set the pointer 3550 ** map entries for the overflow pages as well. 3551 */ 3552 static int setChildPtrmaps(MemPage *pPage){ 3553 int i; /* Counter variable */ 3554 int nCell; /* Number of cells in page pPage */ 3555 int rc; /* Return code */ 3556 BtShared *pBt = pPage->pBt; 3557 Pgno pgno = pPage->pgno; 3558 3559 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3560 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); 3561 if( rc!=SQLITE_OK ) return rc; 3562 nCell = pPage->nCell; 3563 3564 for(i=0; i<nCell; i++){ 3565 u8 *pCell = findCell(pPage, i); 3566 3567 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc); 3568 3569 if( !pPage->leaf ){ 3570 Pgno childPgno = get4byte(pCell); 3571 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3572 } 3573 } 3574 3575 if( !pPage->leaf ){ 3576 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 3577 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); 3578 } 3579 3580 return rc; 3581 } 3582 3583 /* 3584 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so 3585 ** that it points to iTo. Parameter eType describes the type of pointer to 3586 ** be modified, as follows: 3587 ** 3588 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child 3589 ** page of pPage. 3590 ** 3591 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow 3592 ** page pointed to by one of the cells on pPage. 3593 ** 3594 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next 3595 ** overflow page in the list. 3596 */ 3597 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ 3598 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 3599 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 3600 if( eType==PTRMAP_OVERFLOW2 ){ 3601 /* The pointer is always the first 4 bytes of the page in this case. */ 3602 if( get4byte(pPage->aData)!=iFrom ){ 3603 return SQLITE_CORRUPT_PAGE(pPage); 3604 } 3605 put4byte(pPage->aData, iTo); 3606 }else{ 3607 int i; 3608 int nCell; 3609 int rc; 3610 3611 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); 3612 if( rc ) return rc; 3613 nCell = pPage->nCell; 3614 3615 for(i=0; i<nCell; i++){ 3616 u8 *pCell = findCell(pPage, i); 3617 if( eType==PTRMAP_OVERFLOW1 ){ 3618 CellInfo info; 3619 pPage->xParseCell(pPage, pCell, &info); 3620 if( info.nLocal<info.nPayload ){ 3621 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){ 3622 return SQLITE_CORRUPT_PAGE(pPage); 3623 } 3624 if( iFrom==get4byte(pCell+info.nSize-4) ){ 3625 put4byte(pCell+info.nSize-4, iTo); 3626 break; 3627 } 3628 } 3629 }else{ 3630 if( get4byte(pCell)==iFrom ){ 3631 put4byte(pCell, iTo); 3632 break; 3633 } 3634 } 3635 } 3636 3637 if( i==nCell ){ 3638 if( eType!=PTRMAP_BTREE || 3639 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ 3640 return SQLITE_CORRUPT_PAGE(pPage); 3641 } 3642 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); 3643 } 3644 } 3645 return SQLITE_OK; 3646 } 3647 3648 3649 /* 3650 ** Move the open database page pDbPage to location iFreePage in the 3651 ** database. The pDbPage reference remains valid. 3652 ** 3653 ** The isCommit flag indicates that there is no need to remember that 3654 ** the journal needs to be sync()ed before database page pDbPage->pgno 3655 ** can be written to. The caller has already promised not to write to that 3656 ** page. 3657 */ 3658 static int relocatePage( 3659 BtShared *pBt, /* Btree */ 3660 MemPage *pDbPage, /* Open page to move */ 3661 u8 eType, /* Pointer map 'type' entry for pDbPage */ 3662 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ 3663 Pgno iFreePage, /* The location to move pDbPage to */ 3664 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ 3665 ){ 3666 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ 3667 Pgno iDbPage = pDbPage->pgno; 3668 Pager *pPager = pBt->pPager; 3669 int rc; 3670 3671 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 3672 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); 3673 assert( sqlite3_mutex_held(pBt->mutex) ); 3674 assert( pDbPage->pBt==pBt ); 3675 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT; 3676 3677 /* Move page iDbPage from its current location to page number iFreePage */ 3678 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 3679 iDbPage, iFreePage, iPtrPage, eType)); 3680 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); 3681 if( rc!=SQLITE_OK ){ 3682 return rc; 3683 } 3684 pDbPage->pgno = iFreePage; 3685 3686 /* If pDbPage was a btree-page, then it may have child pages and/or cells 3687 ** that point to overflow pages. The pointer map entries for all these 3688 ** pages need to be changed. 3689 ** 3690 ** If pDbPage is an overflow page, then the first 4 bytes may store a 3691 ** pointer to a subsequent overflow page. If this is the case, then 3692 ** the pointer map needs to be updated for the subsequent overflow page. 3693 */ 3694 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ 3695 rc = setChildPtrmaps(pDbPage); 3696 if( rc!=SQLITE_OK ){ 3697 return rc; 3698 } 3699 }else{ 3700 Pgno nextOvfl = get4byte(pDbPage->aData); 3701 if( nextOvfl!=0 ){ 3702 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); 3703 if( rc!=SQLITE_OK ){ 3704 return rc; 3705 } 3706 } 3707 } 3708 3709 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so 3710 ** that it points at iFreePage. Also fix the pointer map entry for 3711 ** iPtrPage. 3712 */ 3713 if( eType!=PTRMAP_ROOTPAGE ){ 3714 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); 3715 if( rc!=SQLITE_OK ){ 3716 return rc; 3717 } 3718 rc = sqlite3PagerWrite(pPtrPage->pDbPage); 3719 if( rc!=SQLITE_OK ){ 3720 releasePage(pPtrPage); 3721 return rc; 3722 } 3723 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); 3724 releasePage(pPtrPage); 3725 if( rc==SQLITE_OK ){ 3726 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); 3727 } 3728 } 3729 return rc; 3730 } 3731 3732 /* Forward declaration required by incrVacuumStep(). */ 3733 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); 3734 3735 /* 3736 ** Perform a single step of an incremental-vacuum. If successful, return 3737 ** SQLITE_OK. If there is no work to do (and therefore no point in 3738 ** calling this function again), return SQLITE_DONE. Or, if an error 3739 ** occurs, return some other error code. 3740 ** 3741 ** More specifically, this function attempts to re-organize the database so 3742 ** that the last page of the file currently in use is no longer in use. 3743 ** 3744 ** Parameter nFin is the number of pages that this database would contain 3745 ** were this function called until it returns SQLITE_DONE. 3746 ** 3747 ** If the bCommit parameter is non-zero, this function assumes that the 3748 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 3749 ** or an error. bCommit is passed true for an auto-vacuum-on-commit 3750 ** operation, or false for an incremental vacuum. 3751 */ 3752 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ 3753 Pgno nFreeList; /* Number of pages still on the free-list */ 3754 int rc; 3755 3756 assert( sqlite3_mutex_held(pBt->mutex) ); 3757 assert( iLastPg>nFin ); 3758 3759 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ 3760 u8 eType; 3761 Pgno iPtrPage; 3762 3763 nFreeList = get4byte(&pBt->pPage1->aData[36]); 3764 if( nFreeList==0 ){ 3765 return SQLITE_DONE; 3766 } 3767 3768 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); 3769 if( rc!=SQLITE_OK ){ 3770 return rc; 3771 } 3772 if( eType==PTRMAP_ROOTPAGE ){ 3773 return SQLITE_CORRUPT_BKPT; 3774 } 3775 3776 if( eType==PTRMAP_FREEPAGE ){ 3777 if( bCommit==0 ){ 3778 /* Remove the page from the files free-list. This is not required 3779 ** if bCommit is non-zero. In that case, the free-list will be 3780 ** truncated to zero after this function returns, so it doesn't 3781 ** matter if it still contains some garbage entries. 3782 */ 3783 Pgno iFreePg; 3784 MemPage *pFreePg; 3785 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); 3786 if( rc!=SQLITE_OK ){ 3787 return rc; 3788 } 3789 assert( iFreePg==iLastPg ); 3790 releasePage(pFreePg); 3791 } 3792 } else { 3793 Pgno iFreePg; /* Index of free page to move pLastPg to */ 3794 MemPage *pLastPg; 3795 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ 3796 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ 3797 3798 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); 3799 if( rc!=SQLITE_OK ){ 3800 return rc; 3801 } 3802 3803 /* If bCommit is zero, this loop runs exactly once and page pLastPg 3804 ** is swapped with the first free page pulled off the free list. 3805 ** 3806 ** On the other hand, if bCommit is greater than zero, then keep 3807 ** looping until a free-page located within the first nFin pages 3808 ** of the file is found. 3809 */ 3810 if( bCommit==0 ){ 3811 eMode = BTALLOC_LE; 3812 iNear = nFin; 3813 } 3814 do { 3815 MemPage *pFreePg; 3816 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); 3817 if( rc!=SQLITE_OK ){ 3818 releasePage(pLastPg); 3819 return rc; 3820 } 3821 releasePage(pFreePg); 3822 }while( bCommit && iFreePg>nFin ); 3823 assert( iFreePg<iLastPg ); 3824 3825 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); 3826 releasePage(pLastPg); 3827 if( rc!=SQLITE_OK ){ 3828 return rc; 3829 } 3830 } 3831 } 3832 3833 if( bCommit==0 ){ 3834 do { 3835 iLastPg--; 3836 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) ); 3837 pBt->bDoTruncate = 1; 3838 pBt->nPage = iLastPg; 3839 } 3840 return SQLITE_OK; 3841 } 3842 3843 /* 3844 ** The database opened by the first argument is an auto-vacuum database 3845 ** nOrig pages in size containing nFree free pages. Return the expected 3846 ** size of the database in pages following an auto-vacuum operation. 3847 */ 3848 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ 3849 int nEntry; /* Number of entries on one ptrmap page */ 3850 Pgno nPtrmap; /* Number of PtrMap pages to be freed */ 3851 Pgno nFin; /* Return value */ 3852 3853 nEntry = pBt->usableSize/5; 3854 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; 3855 nFin = nOrig - nFree - nPtrmap; 3856 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ 3857 nFin--; 3858 } 3859 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ 3860 nFin--; 3861 } 3862 3863 return nFin; 3864 } 3865 3866 /* 3867 ** A write-transaction must be opened before calling this function. 3868 ** It performs a single unit of work towards an incremental vacuum. 3869 ** 3870 ** If the incremental vacuum is finished after this function has run, 3871 ** SQLITE_DONE is returned. If it is not finished, but no error occurred, 3872 ** SQLITE_OK is returned. Otherwise an SQLite error code. 3873 */ 3874 int sqlite3BtreeIncrVacuum(Btree *p){ 3875 int rc; 3876 BtShared *pBt = p->pBt; 3877 3878 sqlite3BtreeEnter(p); 3879 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); 3880 if( !pBt->autoVacuum ){ 3881 rc = SQLITE_DONE; 3882 }else{ 3883 Pgno nOrig = btreePagecount(pBt); 3884 Pgno nFree = get4byte(&pBt->pPage1->aData[36]); 3885 Pgno nFin = finalDbSize(pBt, nOrig, nFree); 3886 3887 if( nOrig<nFin ){ 3888 rc = SQLITE_CORRUPT_BKPT; 3889 }else if( nFree>0 ){ 3890 rc = saveAllCursors(pBt, 0, 0); 3891 if( rc==SQLITE_OK ){ 3892 invalidateAllOverflowCache(pBt); 3893 rc = incrVacuumStep(pBt, nFin, nOrig, 0); 3894 } 3895 if( rc==SQLITE_OK ){ 3896 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3897 put4byte(&pBt->pPage1->aData[28], pBt->nPage); 3898 } 3899 }else{ 3900 rc = SQLITE_DONE; 3901 } 3902 } 3903 sqlite3BtreeLeave(p); 3904 return rc; 3905 } 3906 3907 /* 3908 ** This routine is called prior to sqlite3PagerCommit when a transaction 3909 ** is committed for an auto-vacuum database. 3910 ** 3911 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages 3912 ** the database file should be truncated to during the commit process. 3913 ** i.e. the database has been reorganized so that only the first *pnTrunc 3914 ** pages are in use. 3915 */ 3916 static int autoVacuumCommit(BtShared *pBt){ 3917 int rc = SQLITE_OK; 3918 Pager *pPager = pBt->pPager; 3919 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) 3920 3921 assert( sqlite3_mutex_held(pBt->mutex) ); 3922 invalidateAllOverflowCache(pBt); 3923 assert(pBt->autoVacuum); 3924 if( !pBt->incrVacuum ){ 3925 Pgno nFin; /* Number of pages in database after autovacuuming */ 3926 Pgno nFree; /* Number of pages on the freelist initially */ 3927 Pgno iFree; /* The next page to be freed */ 3928 Pgno nOrig; /* Database size before freeing */ 3929 3930 nOrig = btreePagecount(pBt); 3931 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ 3932 /* It is not possible to create a database for which the final page 3933 ** is either a pointer-map page or the pending-byte page. If one 3934 ** is encountered, this indicates corruption. 3935 */ 3936 return SQLITE_CORRUPT_BKPT; 3937 } 3938 3939 nFree = get4byte(&pBt->pPage1->aData[36]); 3940 nFin = finalDbSize(pBt, nOrig, nFree); 3941 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; 3942 if( nFin<nOrig ){ 3943 rc = saveAllCursors(pBt, 0, 0); 3944 } 3945 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ 3946 rc = incrVacuumStep(pBt, nFin, iFree, 1); 3947 } 3948 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ 3949 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 3950 put4byte(&pBt->pPage1->aData[32], 0); 3951 put4byte(&pBt->pPage1->aData[36], 0); 3952 put4byte(&pBt->pPage1->aData[28], nFin); 3953 pBt->bDoTruncate = 1; 3954 pBt->nPage = nFin; 3955 } 3956 if( rc!=SQLITE_OK ){ 3957 sqlite3PagerRollback(pPager); 3958 } 3959 } 3960 3961 assert( nRef>=sqlite3PagerRefcount(pPager) ); 3962 return rc; 3963 } 3964 3965 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ 3966 # define setChildPtrmaps(x) SQLITE_OK 3967 #endif 3968 3969 /* 3970 ** This routine does the first phase of a two-phase commit. This routine 3971 ** causes a rollback journal to be created (if it does not already exist) 3972 ** and populated with enough information so that if a power loss occurs 3973 ** the database can be restored to its original state by playing back 3974 ** the journal. Then the contents of the journal are flushed out to 3975 ** the disk. After the journal is safely on oxide, the changes to the 3976 ** database are written into the database file and flushed to oxide. 3977 ** At the end of this call, the rollback journal still exists on the 3978 ** disk and we are still holding all locks, so the transaction has not 3979 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the 3980 ** commit process. 3981 ** 3982 ** This call is a no-op if no write-transaction is currently active on pBt. 3983 ** 3984 ** Otherwise, sync the database file for the btree pBt. zMaster points to 3985 ** the name of a master journal file that should be written into the 3986 ** individual journal file, or is NULL, indicating no master journal file 3987 ** (single database transaction). 3988 ** 3989 ** When this is called, the master journal should already have been 3990 ** created, populated with this journal pointer and synced to disk. 3991 ** 3992 ** Once this is routine has returned, the only thing required to commit 3993 ** the write-transaction for this database file is to delete the journal. 3994 */ 3995 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ 3996 int rc = SQLITE_OK; 3997 if( p->inTrans==TRANS_WRITE ){ 3998 BtShared *pBt = p->pBt; 3999 sqlite3BtreeEnter(p); 4000 #ifndef SQLITE_OMIT_AUTOVACUUM 4001 if( pBt->autoVacuum ){ 4002 rc = autoVacuumCommit(pBt); 4003 if( rc!=SQLITE_OK ){ 4004 sqlite3BtreeLeave(p); 4005 return rc; 4006 } 4007 } 4008 if( pBt->bDoTruncate ){ 4009 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); 4010 } 4011 #endif 4012 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); 4013 sqlite3BtreeLeave(p); 4014 } 4015 return rc; 4016 } 4017 4018 /* 4019 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() 4020 ** at the conclusion of a transaction. 4021 */ 4022 static void btreeEndTransaction(Btree *p){ 4023 BtShared *pBt = p->pBt; 4024 sqlite3 *db = p->db; 4025 assert( sqlite3BtreeHoldsMutex(p) ); 4026 4027 #ifndef SQLITE_OMIT_AUTOVACUUM 4028 pBt->bDoTruncate = 0; 4029 #endif 4030 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ 4031 /* If there are other active statements that belong to this database 4032 ** handle, downgrade to a read-only transaction. The other statements 4033 ** may still be reading from the database. */ 4034 downgradeAllSharedCacheTableLocks(p); 4035 p->inTrans = TRANS_READ; 4036 }else{ 4037 /* If the handle had any kind of transaction open, decrement the 4038 ** transaction count of the shared btree. If the transaction count 4039 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() 4040 ** call below will unlock the pager. */ 4041 if( p->inTrans!=TRANS_NONE ){ 4042 clearAllSharedCacheTableLocks(p); 4043 pBt->nTransaction--; 4044 if( 0==pBt->nTransaction ){ 4045 pBt->inTransaction = TRANS_NONE; 4046 } 4047 } 4048 4049 /* Set the current transaction state to TRANS_NONE and unlock the 4050 ** pager if this call closed the only read or write transaction. */ 4051 p->inTrans = TRANS_NONE; 4052 unlockBtreeIfUnused(pBt); 4053 } 4054 4055 btreeIntegrity(p); 4056 } 4057 4058 /* 4059 ** Commit the transaction currently in progress. 4060 ** 4061 ** This routine implements the second phase of a 2-phase commit. The 4062 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should 4063 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() 4064 ** routine did all the work of writing information out to disk and flushing the 4065 ** contents so that they are written onto the disk platter. All this 4066 ** routine has to do is delete or truncate or zero the header in the 4067 ** the rollback journal (which causes the transaction to commit) and 4068 ** drop locks. 4069 ** 4070 ** Normally, if an error occurs while the pager layer is attempting to 4071 ** finalize the underlying journal file, this function returns an error and 4072 ** the upper layer will attempt a rollback. However, if the second argument 4073 ** is non-zero then this b-tree transaction is part of a multi-file 4074 ** transaction. In this case, the transaction has already been committed 4075 ** (by deleting a master journal file) and the caller will ignore this 4076 ** functions return code. So, even if an error occurs in the pager layer, 4077 ** reset the b-tree objects internal state to indicate that the write 4078 ** transaction has been closed. This is quite safe, as the pager will have 4079 ** transitioned to the error state. 4080 ** 4081 ** This will release the write lock on the database file. If there 4082 ** are no active cursors, it also releases the read lock. 4083 */ 4084 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ 4085 4086 if( p->inTrans==TRANS_NONE ) return SQLITE_OK; 4087 sqlite3BtreeEnter(p); 4088 btreeIntegrity(p); 4089 4090 /* If the handle has a write-transaction open, commit the shared-btrees 4091 ** transaction and set the shared state to TRANS_READ. 4092 */ 4093 if( p->inTrans==TRANS_WRITE ){ 4094 int rc; 4095 BtShared *pBt = p->pBt; 4096 assert( pBt->inTransaction==TRANS_WRITE ); 4097 assert( pBt->nTransaction>0 ); 4098 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); 4099 if( rc!=SQLITE_OK && bCleanup==0 ){ 4100 sqlite3BtreeLeave(p); 4101 return rc; 4102 } 4103 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ 4104 pBt->inTransaction = TRANS_READ; 4105 btreeClearHasContent(pBt); 4106 } 4107 4108 btreeEndTransaction(p); 4109 sqlite3BtreeLeave(p); 4110 return SQLITE_OK; 4111 } 4112 4113 /* 4114 ** Do both phases of a commit. 4115 */ 4116 int sqlite3BtreeCommit(Btree *p){ 4117 int rc; 4118 sqlite3BtreeEnter(p); 4119 rc = sqlite3BtreeCommitPhaseOne(p, 0); 4120 if( rc==SQLITE_OK ){ 4121 rc = sqlite3BtreeCommitPhaseTwo(p, 0); 4122 } 4123 sqlite3BtreeLeave(p); 4124 return rc; 4125 } 4126 4127 /* 4128 ** This routine sets the state to CURSOR_FAULT and the error 4129 ** code to errCode for every cursor on any BtShared that pBtree 4130 ** references. Or if the writeOnly flag is set to 1, then only 4131 ** trip write cursors and leave read cursors unchanged. 4132 ** 4133 ** Every cursor is a candidate to be tripped, including cursors 4134 ** that belong to other database connections that happen to be 4135 ** sharing the cache with pBtree. 4136 ** 4137 ** This routine gets called when a rollback occurs. If the writeOnly 4138 ** flag is true, then only write-cursors need be tripped - read-only 4139 ** cursors save their current positions so that they may continue 4140 ** following the rollback. Or, if writeOnly is false, all cursors are 4141 ** tripped. In general, writeOnly is false if the transaction being 4142 ** rolled back modified the database schema. In this case b-tree root 4143 ** pages may be moved or deleted from the database altogether, making 4144 ** it unsafe for read cursors to continue. 4145 ** 4146 ** If the writeOnly flag is true and an error is encountered while 4147 ** saving the current position of a read-only cursor, all cursors, 4148 ** including all read-cursors are tripped. 4149 ** 4150 ** SQLITE_OK is returned if successful, or if an error occurs while 4151 ** saving a cursor position, an SQLite error code. 4152 */ 4153 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ 4154 BtCursor *p; 4155 int rc = SQLITE_OK; 4156 4157 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); 4158 if( pBtree ){ 4159 sqlite3BtreeEnter(pBtree); 4160 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ 4161 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ 4162 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ 4163 rc = saveCursorPosition(p); 4164 if( rc!=SQLITE_OK ){ 4165 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); 4166 break; 4167 } 4168 } 4169 }else{ 4170 sqlite3BtreeClearCursor(p); 4171 p->eState = CURSOR_FAULT; 4172 p->skipNext = errCode; 4173 } 4174 btreeReleaseAllCursorPages(p); 4175 } 4176 sqlite3BtreeLeave(pBtree); 4177 } 4178 return rc; 4179 } 4180 4181 /* 4182 ** Set the pBt->nPage field correctly, according to the current 4183 ** state of the database. Assume pBt->pPage1 is valid. 4184 */ 4185 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){ 4186 int nPage = get4byte(&pPage1->aData[28]); 4187 testcase( nPage==0 ); 4188 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); 4189 testcase( pBt->nPage!=nPage ); 4190 pBt->nPage = nPage; 4191 } 4192 4193 /* 4194 ** Rollback the transaction in progress. 4195 ** 4196 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). 4197 ** Only write cursors are tripped if writeOnly is true but all cursors are 4198 ** tripped if writeOnly is false. Any attempt to use 4199 ** a tripped cursor will result in an error. 4200 ** 4201 ** This will release the write lock on the database file. If there 4202 ** are no active cursors, it also releases the read lock. 4203 */ 4204 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ 4205 int rc; 4206 BtShared *pBt = p->pBt; 4207 MemPage *pPage1; 4208 4209 assert( writeOnly==1 || writeOnly==0 ); 4210 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); 4211 sqlite3BtreeEnter(p); 4212 if( tripCode==SQLITE_OK ){ 4213 rc = tripCode = saveAllCursors(pBt, 0, 0); 4214 if( rc ) writeOnly = 0; 4215 }else{ 4216 rc = SQLITE_OK; 4217 } 4218 if( tripCode ){ 4219 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); 4220 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); 4221 if( rc2!=SQLITE_OK ) rc = rc2; 4222 } 4223 btreeIntegrity(p); 4224 4225 if( p->inTrans==TRANS_WRITE ){ 4226 int rc2; 4227 4228 assert( TRANS_WRITE==pBt->inTransaction ); 4229 rc2 = sqlite3PagerRollback(pBt->pPager); 4230 if( rc2!=SQLITE_OK ){ 4231 rc = rc2; 4232 } 4233 4234 /* The rollback may have destroyed the pPage1->aData value. So 4235 ** call btreeGetPage() on page 1 again to make 4236 ** sure pPage1->aData is set correctly. */ 4237 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ 4238 btreeSetNPage(pBt, pPage1); 4239 releasePageOne(pPage1); 4240 } 4241 assert( countValidCursors(pBt, 1)==0 ); 4242 pBt->inTransaction = TRANS_READ; 4243 btreeClearHasContent(pBt); 4244 } 4245 4246 btreeEndTransaction(p); 4247 sqlite3BtreeLeave(p); 4248 return rc; 4249 } 4250 4251 /* 4252 ** Start a statement subtransaction. The subtransaction can be rolled 4253 ** back independently of the main transaction. You must start a transaction 4254 ** before starting a subtransaction. The subtransaction is ended automatically 4255 ** if the main transaction commits or rolls back. 4256 ** 4257 ** Statement subtransactions are used around individual SQL statements 4258 ** that are contained within a BEGIN...COMMIT block. If a constraint 4259 ** error occurs within the statement, the effect of that one statement 4260 ** can be rolled back without having to rollback the entire transaction. 4261 ** 4262 ** A statement sub-transaction is implemented as an anonymous savepoint. The 4263 ** value passed as the second parameter is the total number of savepoints, 4264 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there 4265 ** are no active savepoints and no other statement-transactions open, 4266 ** iStatement is 1. This anonymous savepoint can be released or rolled back 4267 ** using the sqlite3BtreeSavepoint() function. 4268 */ 4269 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ 4270 int rc; 4271 BtShared *pBt = p->pBt; 4272 sqlite3BtreeEnter(p); 4273 assert( p->inTrans==TRANS_WRITE ); 4274 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 4275 assert( iStatement>0 ); 4276 assert( iStatement>p->db->nSavepoint ); 4277 assert( pBt->inTransaction==TRANS_WRITE ); 4278 /* At the pager level, a statement transaction is a savepoint with 4279 ** an index greater than all savepoints created explicitly using 4280 ** SQL statements. It is illegal to open, release or rollback any 4281 ** such savepoints while the statement transaction savepoint is active. 4282 */ 4283 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); 4284 sqlite3BtreeLeave(p); 4285 return rc; 4286 } 4287 4288 /* 4289 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK 4290 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the 4291 ** savepoint identified by parameter iSavepoint, depending on the value 4292 ** of op. 4293 ** 4294 ** Normally, iSavepoint is greater than or equal to zero. However, if op is 4295 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 4296 ** contents of the entire transaction are rolled back. This is different 4297 ** from a normal transaction rollback, as no locks are released and the 4298 ** transaction remains open. 4299 */ 4300 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ 4301 int rc = SQLITE_OK; 4302 if( p && p->inTrans==TRANS_WRITE ){ 4303 BtShared *pBt = p->pBt; 4304 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); 4305 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); 4306 sqlite3BtreeEnter(p); 4307 if( op==SAVEPOINT_ROLLBACK ){ 4308 rc = saveAllCursors(pBt, 0, 0); 4309 } 4310 if( rc==SQLITE_OK ){ 4311 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); 4312 } 4313 if( rc==SQLITE_OK ){ 4314 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ 4315 pBt->nPage = 0; 4316 } 4317 rc = newDatabase(pBt); 4318 btreeSetNPage(pBt, pBt->pPage1); 4319 4320 /* pBt->nPage might be zero if the database was corrupt when 4321 ** the transaction was started. Otherwise, it must be at least 1. */ 4322 assert( CORRUPT_DB || pBt->nPage>0 ); 4323 } 4324 sqlite3BtreeLeave(p); 4325 } 4326 return rc; 4327 } 4328 4329 /* 4330 ** Create a new cursor for the BTree whose root is on the page 4331 ** iTable. If a read-only cursor is requested, it is assumed that 4332 ** the caller already has at least a read-only transaction open 4333 ** on the database already. If a write-cursor is requested, then 4334 ** the caller is assumed to have an open write transaction. 4335 ** 4336 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only 4337 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor 4338 ** can be used for reading or for writing if other conditions for writing 4339 ** are also met. These are the conditions that must be met in order 4340 ** for writing to be allowed: 4341 ** 4342 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR 4343 ** 4344 ** 2: Other database connections that share the same pager cache 4345 ** but which are not in the READ_UNCOMMITTED state may not have 4346 ** cursors open with wrFlag==0 on the same table. Otherwise 4347 ** the changes made by this write cursor would be visible to 4348 ** the read cursors in the other database connection. 4349 ** 4350 ** 3: The database must be writable (not on read-only media) 4351 ** 4352 ** 4: There must be an active transaction. 4353 ** 4354 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR 4355 ** is set. If FORDELETE is set, that is a hint to the implementation that 4356 ** this cursor will only be used to seek to and delete entries of an index 4357 ** as part of a larger DELETE statement. The FORDELETE hint is not used by 4358 ** this implementation. But in a hypothetical alternative storage engine 4359 ** in which index entries are automatically deleted when corresponding table 4360 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE 4361 ** operations on this cursor can be no-ops and all READ operations can 4362 ** return a null row (2-bytes: 0x01 0x00). 4363 ** 4364 ** No checking is done to make sure that page iTable really is the 4365 ** root page of a b-tree. If it is not, then the cursor acquired 4366 ** will not work correctly. 4367 ** 4368 ** It is assumed that the sqlite3BtreeCursorZero() has been called 4369 ** on pCur to initialize the memory space prior to invoking this routine. 4370 */ 4371 static int btreeCursor( 4372 Btree *p, /* The btree */ 4373 int iTable, /* Root page of table to open */ 4374 int wrFlag, /* 1 to write. 0 read-only */ 4375 struct KeyInfo *pKeyInfo, /* First arg to comparison function */ 4376 BtCursor *pCur /* Space for new cursor */ 4377 ){ 4378 BtShared *pBt = p->pBt; /* Shared b-tree handle */ 4379 BtCursor *pX; /* Looping over other all cursors */ 4380 4381 assert( sqlite3BtreeHoldsMutex(p) ); 4382 assert( wrFlag==0 4383 || wrFlag==BTREE_WRCSR 4384 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 4385 ); 4386 4387 /* The following assert statements verify that if this is a sharable 4388 ** b-tree database, the connection is holding the required table locks, 4389 ** and that no other connection has any open cursor that conflicts with 4390 ** this lock. The iTable<1 term disables the check for corrupt schemas. */ 4391 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) 4392 || iTable<1 ); 4393 assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); 4394 4395 /* Assert that the caller has opened the required transaction. */ 4396 assert( p->inTrans>TRANS_NONE ); 4397 assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); 4398 assert( pBt->pPage1 && pBt->pPage1->aData ); 4399 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); 4400 4401 if( wrFlag ){ 4402 allocateTempSpace(pBt); 4403 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; 4404 } 4405 if( iTable<=1 ){ 4406 if( iTable<1 ){ 4407 return SQLITE_CORRUPT_BKPT; 4408 }else if( btreePagecount(pBt)==0 ){ 4409 assert( wrFlag==0 ); 4410 iTable = 0; 4411 } 4412 } 4413 4414 /* Now that no other errors can occur, finish filling in the BtCursor 4415 ** variables and link the cursor into the BtShared list. */ 4416 pCur->pgnoRoot = (Pgno)iTable; 4417 pCur->iPage = -1; 4418 pCur->pKeyInfo = pKeyInfo; 4419 pCur->pBtree = p; 4420 pCur->pBt = pBt; 4421 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0; 4422 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; 4423 /* If there are two or more cursors on the same btree, then all such 4424 ** cursors *must* have the BTCF_Multiple flag set. */ 4425 for(pX=pBt->pCursor; pX; pX=pX->pNext){ 4426 if( pX->pgnoRoot==(Pgno)iTable ){ 4427 pX->curFlags |= BTCF_Multiple; 4428 pCur->curFlags |= BTCF_Multiple; 4429 } 4430 } 4431 pCur->pNext = pBt->pCursor; 4432 pBt->pCursor = pCur; 4433 pCur->eState = CURSOR_INVALID; 4434 return SQLITE_OK; 4435 } 4436 static int btreeCursorWithLock( 4437 Btree *p, /* The btree */ 4438 int iTable, /* Root page of table to open */ 4439 int wrFlag, /* 1 to write. 0 read-only */ 4440 struct KeyInfo *pKeyInfo, /* First arg to comparison function */ 4441 BtCursor *pCur /* Space for new cursor */ 4442 ){ 4443 int rc; 4444 sqlite3BtreeEnter(p); 4445 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); 4446 sqlite3BtreeLeave(p); 4447 return rc; 4448 } 4449 int sqlite3BtreeCursor( 4450 Btree *p, /* The btree */ 4451 int iTable, /* Root page of table to open */ 4452 int wrFlag, /* 1 to write. 0 read-only */ 4453 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ 4454 BtCursor *pCur /* Write new cursor here */ 4455 ){ 4456 if( p->sharable ){ 4457 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur); 4458 }else{ 4459 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); 4460 } 4461 } 4462 4463 /* 4464 ** Return the size of a BtCursor object in bytes. 4465 ** 4466 ** This interfaces is needed so that users of cursors can preallocate 4467 ** sufficient storage to hold a cursor. The BtCursor object is opaque 4468 ** to users so they cannot do the sizeof() themselves - they must call 4469 ** this routine. 4470 */ 4471 int sqlite3BtreeCursorSize(void){ 4472 return ROUND8(sizeof(BtCursor)); 4473 } 4474 4475 /* 4476 ** Initialize memory that will be converted into a BtCursor object. 4477 ** 4478 ** The simple approach here would be to memset() the entire object 4479 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays 4480 ** do not need to be zeroed and they are large, so we can save a lot 4481 ** of run-time by skipping the initialization of those elements. 4482 */ 4483 void sqlite3BtreeCursorZero(BtCursor *p){ 4484 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT)); 4485 } 4486 4487 /* 4488 ** Close a cursor. The read lock on the database file is released 4489 ** when the last cursor is closed. 4490 */ 4491 int sqlite3BtreeCloseCursor(BtCursor *pCur){ 4492 Btree *pBtree = pCur->pBtree; 4493 if( pBtree ){ 4494 BtShared *pBt = pCur->pBt; 4495 sqlite3BtreeEnter(pBtree); 4496 assert( pBt->pCursor!=0 ); 4497 if( pBt->pCursor==pCur ){ 4498 pBt->pCursor = pCur->pNext; 4499 }else{ 4500 BtCursor *pPrev = pBt->pCursor; 4501 do{ 4502 if( pPrev->pNext==pCur ){ 4503 pPrev->pNext = pCur->pNext; 4504 break; 4505 } 4506 pPrev = pPrev->pNext; 4507 }while( ALWAYS(pPrev) ); 4508 } 4509 btreeReleaseAllCursorPages(pCur); 4510 unlockBtreeIfUnused(pBt); 4511 sqlite3_free(pCur->aOverflow); 4512 sqlite3_free(pCur->pKey); 4513 sqlite3BtreeLeave(pBtree); 4514 pCur->pBtree = 0; 4515 } 4516 return SQLITE_OK; 4517 } 4518 4519 /* 4520 ** Make sure the BtCursor* given in the argument has a valid 4521 ** BtCursor.info structure. If it is not already valid, call 4522 ** btreeParseCell() to fill it in. 4523 ** 4524 ** BtCursor.info is a cache of the information in the current cell. 4525 ** Using this cache reduces the number of calls to btreeParseCell(). 4526 */ 4527 #ifndef NDEBUG 4528 static int cellInfoEqual(CellInfo *a, CellInfo *b){ 4529 if( a->nKey!=b->nKey ) return 0; 4530 if( a->pPayload!=b->pPayload ) return 0; 4531 if( a->nPayload!=b->nPayload ) return 0; 4532 if( a->nLocal!=b->nLocal ) return 0; 4533 if( a->nSize!=b->nSize ) return 0; 4534 return 1; 4535 } 4536 static void assertCellInfo(BtCursor *pCur){ 4537 CellInfo info; 4538 memset(&info, 0, sizeof(info)); 4539 btreeParseCell(pCur->pPage, pCur->ix, &info); 4540 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) ); 4541 } 4542 #else 4543 #define assertCellInfo(x) 4544 #endif 4545 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ 4546 if( pCur->info.nSize==0 ){ 4547 pCur->curFlags |= BTCF_ValidNKey; 4548 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info); 4549 }else{ 4550 assertCellInfo(pCur); 4551 } 4552 } 4553 4554 #ifndef NDEBUG /* The next routine used only within assert() statements */ 4555 /* 4556 ** Return true if the given BtCursor is valid. A valid cursor is one 4557 ** that is currently pointing to a row in a (non-empty) table. 4558 ** This is a verification routine is used only within assert() statements. 4559 */ 4560 int sqlite3BtreeCursorIsValid(BtCursor *pCur){ 4561 return pCur && pCur->eState==CURSOR_VALID; 4562 } 4563 #endif /* NDEBUG */ 4564 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){ 4565 assert( pCur!=0 ); 4566 return pCur->eState==CURSOR_VALID; 4567 } 4568 4569 /* 4570 ** Return the value of the integer key or "rowid" for a table btree. 4571 ** This routine is only valid for a cursor that is pointing into a 4572 ** ordinary table btree. If the cursor points to an index btree or 4573 ** is invalid, the result of this routine is undefined. 4574 */ 4575 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ 4576 assert( cursorHoldsMutex(pCur) ); 4577 assert( pCur->eState==CURSOR_VALID ); 4578 assert( pCur->curIntKey ); 4579 getCellInfo(pCur); 4580 return pCur->info.nKey; 4581 } 4582 4583 /* 4584 ** Pin or unpin a cursor. 4585 */ 4586 void sqlite3BtreeCursorPin(BtCursor *pCur){ 4587 assert( (pCur->curFlags & BTCF_Pinned)==0 ); 4588 pCur->curFlags |= BTCF_Pinned; 4589 } 4590 void sqlite3BtreeCursorUnpin(BtCursor *pCur){ 4591 assert( (pCur->curFlags & BTCF_Pinned)!=0 ); 4592 pCur->curFlags &= ~BTCF_Pinned; 4593 } 4594 4595 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 4596 /* 4597 ** Return the offset into the database file for the start of the 4598 ** payload to which the cursor is pointing. 4599 */ 4600 i64 sqlite3BtreeOffset(BtCursor *pCur){ 4601 assert( cursorHoldsMutex(pCur) ); 4602 assert( pCur->eState==CURSOR_VALID ); 4603 getCellInfo(pCur); 4604 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) + 4605 (i64)(pCur->info.pPayload - pCur->pPage->aData); 4606 } 4607 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ 4608 4609 /* 4610 ** Return the number of bytes of payload for the entry that pCur is 4611 ** currently pointing to. For table btrees, this will be the amount 4612 ** of data. For index btrees, this will be the size of the key. 4613 ** 4614 ** The caller must guarantee that the cursor is pointing to a non-NULL 4615 ** valid entry. In other words, the calling procedure must guarantee 4616 ** that the cursor has Cursor.eState==CURSOR_VALID. 4617 */ 4618 u32 sqlite3BtreePayloadSize(BtCursor *pCur){ 4619 assert( cursorHoldsMutex(pCur) ); 4620 assert( pCur->eState==CURSOR_VALID ); 4621 getCellInfo(pCur); 4622 return pCur->info.nPayload; 4623 } 4624 4625 /* 4626 ** Return an upper bound on the size of any record for the table 4627 ** that the cursor is pointing into. 4628 ** 4629 ** This is an optimization. Everything will still work if this 4630 ** routine always returns 2147483647 (which is the largest record 4631 ** that SQLite can handle) or more. But returning a smaller value might 4632 ** prevent large memory allocations when trying to interpret a 4633 ** corrupt datrabase. 4634 ** 4635 ** The current implementation merely returns the size of the underlying 4636 ** database file. 4637 */ 4638 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){ 4639 assert( cursorHoldsMutex(pCur) ); 4640 assert( pCur->eState==CURSOR_VALID ); 4641 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage; 4642 } 4643 4644 /* 4645 ** Given the page number of an overflow page in the database (parameter 4646 ** ovfl), this function finds the page number of the next page in the 4647 ** linked list of overflow pages. If possible, it uses the auto-vacuum 4648 ** pointer-map data instead of reading the content of page ovfl to do so. 4649 ** 4650 ** If an error occurs an SQLite error code is returned. Otherwise: 4651 ** 4652 ** The page number of the next overflow page in the linked list is 4653 ** written to *pPgnoNext. If page ovfl is the last page in its linked 4654 ** list, *pPgnoNext is set to zero. 4655 ** 4656 ** If ppPage is not NULL, and a reference to the MemPage object corresponding 4657 ** to page number pOvfl was obtained, then *ppPage is set to point to that 4658 ** reference. It is the responsibility of the caller to call releasePage() 4659 ** on *ppPage to free the reference. In no reference was obtained (because 4660 ** the pointer-map was used to obtain the value for *pPgnoNext), then 4661 ** *ppPage is set to zero. 4662 */ 4663 static int getOverflowPage( 4664 BtShared *pBt, /* The database file */ 4665 Pgno ovfl, /* Current overflow page number */ 4666 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ 4667 Pgno *pPgnoNext /* OUT: Next overflow page number */ 4668 ){ 4669 Pgno next = 0; 4670 MemPage *pPage = 0; 4671 int rc = SQLITE_OK; 4672 4673 assert( sqlite3_mutex_held(pBt->mutex) ); 4674 assert(pPgnoNext); 4675 4676 #ifndef SQLITE_OMIT_AUTOVACUUM 4677 /* Try to find the next page in the overflow list using the 4678 ** autovacuum pointer-map pages. Guess that the next page in 4679 ** the overflow list is page number (ovfl+1). If that guess turns 4680 ** out to be wrong, fall back to loading the data of page 4681 ** number ovfl to determine the next page number. 4682 */ 4683 if( pBt->autoVacuum ){ 4684 Pgno pgno; 4685 Pgno iGuess = ovfl+1; 4686 u8 eType; 4687 4688 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ 4689 iGuess++; 4690 } 4691 4692 if( iGuess<=btreePagecount(pBt) ){ 4693 rc = ptrmapGet(pBt, iGuess, &eType, &pgno); 4694 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ 4695 next = iGuess; 4696 rc = SQLITE_DONE; 4697 } 4698 } 4699 } 4700 #endif 4701 4702 assert( next==0 || rc==SQLITE_DONE ); 4703 if( rc==SQLITE_OK ){ 4704 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); 4705 assert( rc==SQLITE_OK || pPage==0 ); 4706 if( rc==SQLITE_OK ){ 4707 next = get4byte(pPage->aData); 4708 } 4709 } 4710 4711 *pPgnoNext = next; 4712 if( ppPage ){ 4713 *ppPage = pPage; 4714 }else{ 4715 releasePage(pPage); 4716 } 4717 return (rc==SQLITE_DONE ? SQLITE_OK : rc); 4718 } 4719 4720 /* 4721 ** Copy data from a buffer to a page, or from a page to a buffer. 4722 ** 4723 ** pPayload is a pointer to data stored on database page pDbPage. 4724 ** If argument eOp is false, then nByte bytes of data are copied 4725 ** from pPayload to the buffer pointed at by pBuf. If eOp is true, 4726 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes 4727 ** of data are copied from the buffer pBuf to pPayload. 4728 ** 4729 ** SQLITE_OK is returned on success, otherwise an error code. 4730 */ 4731 static int copyPayload( 4732 void *pPayload, /* Pointer to page data */ 4733 void *pBuf, /* Pointer to buffer */ 4734 int nByte, /* Number of bytes to copy */ 4735 int eOp, /* 0 -> copy from page, 1 -> copy to page */ 4736 DbPage *pDbPage /* Page containing pPayload */ 4737 ){ 4738 if( eOp ){ 4739 /* Copy data from buffer to page (a write operation) */ 4740 int rc = sqlite3PagerWrite(pDbPage); 4741 if( rc!=SQLITE_OK ){ 4742 return rc; 4743 } 4744 memcpy(pPayload, pBuf, nByte); 4745 }else{ 4746 /* Copy data from page to buffer (a read operation) */ 4747 memcpy(pBuf, pPayload, nByte); 4748 } 4749 return SQLITE_OK; 4750 } 4751 4752 /* 4753 ** This function is used to read or overwrite payload information 4754 ** for the entry that the pCur cursor is pointing to. The eOp 4755 ** argument is interpreted as follows: 4756 ** 4757 ** 0: The operation is a read. Populate the overflow cache. 4758 ** 1: The operation is a write. Populate the overflow cache. 4759 ** 4760 ** A total of "amt" bytes are read or written beginning at "offset". 4761 ** Data is read to or from the buffer pBuf. 4762 ** 4763 ** The content being read or written might appear on the main page 4764 ** or be scattered out on multiple overflow pages. 4765 ** 4766 ** If the current cursor entry uses one or more overflow pages 4767 ** this function may allocate space for and lazily populate 4768 ** the overflow page-list cache array (BtCursor.aOverflow). 4769 ** Subsequent calls use this cache to make seeking to the supplied offset 4770 ** more efficient. 4771 ** 4772 ** Once an overflow page-list cache has been allocated, it must be 4773 ** invalidated if some other cursor writes to the same table, or if 4774 ** the cursor is moved to a different row. Additionally, in auto-vacuum 4775 ** mode, the following events may invalidate an overflow page-list cache. 4776 ** 4777 ** * An incremental vacuum, 4778 ** * A commit in auto_vacuum="full" mode, 4779 ** * Creating a table (may require moving an overflow page). 4780 */ 4781 static int accessPayload( 4782 BtCursor *pCur, /* Cursor pointing to entry to read from */ 4783 u32 offset, /* Begin reading this far into payload */ 4784 u32 amt, /* Read this many bytes */ 4785 unsigned char *pBuf, /* Write the bytes into this buffer */ 4786 int eOp /* zero to read. non-zero to write. */ 4787 ){ 4788 unsigned char *aPayload; 4789 int rc = SQLITE_OK; 4790 int iIdx = 0; 4791 MemPage *pPage = pCur->pPage; /* Btree page of current entry */ 4792 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ 4793 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4794 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ 4795 #endif 4796 4797 assert( pPage ); 4798 assert( eOp==0 || eOp==1 ); 4799 assert( pCur->eState==CURSOR_VALID ); 4800 assert( pCur->ix<pPage->nCell ); 4801 assert( cursorHoldsMutex(pCur) ); 4802 4803 getCellInfo(pCur); 4804 aPayload = pCur->info.pPayload; 4805 assert( offset+amt <= pCur->info.nPayload ); 4806 4807 assert( aPayload > pPage->aData ); 4808 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ 4809 /* Trying to read or write past the end of the data is an error. The 4810 ** conditional above is really: 4811 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] 4812 ** but is recast into its current form to avoid integer overflow problems 4813 */ 4814 return SQLITE_CORRUPT_PAGE(pPage); 4815 } 4816 4817 /* Check if data must be read/written to/from the btree page itself. */ 4818 if( offset<pCur->info.nLocal ){ 4819 int a = amt; 4820 if( a+offset>pCur->info.nLocal ){ 4821 a = pCur->info.nLocal - offset; 4822 } 4823 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); 4824 offset = 0; 4825 pBuf += a; 4826 amt -= a; 4827 }else{ 4828 offset -= pCur->info.nLocal; 4829 } 4830 4831 4832 if( rc==SQLITE_OK && amt>0 ){ 4833 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ 4834 Pgno nextPage; 4835 4836 nextPage = get4byte(&aPayload[pCur->info.nLocal]); 4837 4838 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. 4839 ** 4840 ** The aOverflow[] array is sized at one entry for each overflow page 4841 ** in the overflow chain. The page number of the first overflow page is 4842 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array 4843 ** means "not yet known" (the cache is lazily populated). 4844 */ 4845 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ 4846 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; 4847 if( pCur->aOverflow==0 4848 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) 4849 ){ 4850 Pgno *aNew = (Pgno*)sqlite3Realloc( 4851 pCur->aOverflow, nOvfl*2*sizeof(Pgno) 4852 ); 4853 if( aNew==0 ){ 4854 return SQLITE_NOMEM_BKPT; 4855 }else{ 4856 pCur->aOverflow = aNew; 4857 } 4858 } 4859 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); 4860 pCur->curFlags |= BTCF_ValidOvfl; 4861 }else{ 4862 /* If the overflow page-list cache has been allocated and the 4863 ** entry for the first required overflow page is valid, skip 4864 ** directly to it. 4865 */ 4866 if( pCur->aOverflow[offset/ovflSize] ){ 4867 iIdx = (offset/ovflSize); 4868 nextPage = pCur->aOverflow[iIdx]; 4869 offset = (offset%ovflSize); 4870 } 4871 } 4872 4873 assert( rc==SQLITE_OK && amt>0 ); 4874 while( nextPage ){ 4875 /* If required, populate the overflow page-list cache. */ 4876 assert( pCur->aOverflow[iIdx]==0 4877 || pCur->aOverflow[iIdx]==nextPage 4878 || CORRUPT_DB ); 4879 pCur->aOverflow[iIdx] = nextPage; 4880 4881 if( offset>=ovflSize ){ 4882 /* The only reason to read this page is to obtain the page 4883 ** number for the next page in the overflow chain. The page 4884 ** data is not required. So first try to lookup the overflow 4885 ** page-list cache, if any, then fall back to the getOverflowPage() 4886 ** function. 4887 */ 4888 assert( pCur->curFlags & BTCF_ValidOvfl ); 4889 assert( pCur->pBtree->db==pBt->db ); 4890 if( pCur->aOverflow[iIdx+1] ){ 4891 nextPage = pCur->aOverflow[iIdx+1]; 4892 }else{ 4893 rc = getOverflowPage(pBt, nextPage, 0, &nextPage); 4894 } 4895 offset -= ovflSize; 4896 }else{ 4897 /* Need to read this page properly. It contains some of the 4898 ** range of data that is being read (eOp==0) or written (eOp!=0). 4899 */ 4900 int a = amt; 4901 if( a + offset > ovflSize ){ 4902 a = ovflSize - offset; 4903 } 4904 4905 #ifdef SQLITE_DIRECT_OVERFLOW_READ 4906 /* If all the following are true: 4907 ** 4908 ** 1) this is a read operation, and 4909 ** 2) data is required from the start of this overflow page, and 4910 ** 3) there are no dirty pages in the page-cache 4911 ** 4) the database is file-backed, and 4912 ** 5) the page is not in the WAL file 4913 ** 6) at least 4 bytes have already been read into the output buffer 4914 ** 4915 ** then data can be read directly from the database file into the 4916 ** output buffer, bypassing the page-cache altogether. This speeds 4917 ** up loading large records that span many overflow pages. 4918 */ 4919 if( eOp==0 /* (1) */ 4920 && offset==0 /* (2) */ 4921 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ 4922 && &pBuf[-4]>=pBufStart /* (6) */ 4923 ){ 4924 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); 4925 u8 aSave[4]; 4926 u8 *aWrite = &pBuf[-4]; 4927 assert( aWrite>=pBufStart ); /* due to (6) */ 4928 memcpy(aSave, aWrite, 4); 4929 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); 4930 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT; 4931 nextPage = get4byte(aWrite); 4932 memcpy(aWrite, aSave, 4); 4933 }else 4934 #endif 4935 4936 { 4937 DbPage *pDbPage; 4938 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, 4939 (eOp==0 ? PAGER_GET_READONLY : 0) 4940 ); 4941 if( rc==SQLITE_OK ){ 4942 aPayload = sqlite3PagerGetData(pDbPage); 4943 nextPage = get4byte(aPayload); 4944 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); 4945 sqlite3PagerUnref(pDbPage); 4946 offset = 0; 4947 } 4948 } 4949 amt -= a; 4950 if( amt==0 ) return rc; 4951 pBuf += a; 4952 } 4953 if( rc ) break; 4954 iIdx++; 4955 } 4956 } 4957 4958 if( rc==SQLITE_OK && amt>0 ){ 4959 /* Overflow chain ends prematurely */ 4960 return SQLITE_CORRUPT_PAGE(pPage); 4961 } 4962 return rc; 4963 } 4964 4965 /* 4966 ** Read part of the payload for the row at which that cursor pCur is currently 4967 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer 4968 ** begins at "offset". 4969 ** 4970 ** pCur can be pointing to either a table or an index b-tree. 4971 ** If pointing to a table btree, then the content section is read. If 4972 ** pCur is pointing to an index b-tree then the key section is read. 4973 ** 4974 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing 4975 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the 4976 ** cursor might be invalid or might need to be restored before being read. 4977 ** 4978 ** Return SQLITE_OK on success or an error code if anything goes 4979 ** wrong. An error is returned if "offset+amt" is larger than 4980 ** the available payload. 4981 */ 4982 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 4983 assert( cursorHoldsMutex(pCur) ); 4984 assert( pCur->eState==CURSOR_VALID ); 4985 assert( pCur->iPage>=0 && pCur->pPage ); 4986 assert( pCur->ix<pCur->pPage->nCell ); 4987 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); 4988 } 4989 4990 /* 4991 ** This variant of sqlite3BtreePayload() works even if the cursor has not 4992 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read() 4993 ** interface. 4994 */ 4995 #ifndef SQLITE_OMIT_INCRBLOB 4996 static SQLITE_NOINLINE int accessPayloadChecked( 4997 BtCursor *pCur, 4998 u32 offset, 4999 u32 amt, 5000 void *pBuf 5001 ){ 5002 int rc; 5003 if ( pCur->eState==CURSOR_INVALID ){ 5004 return SQLITE_ABORT; 5005 } 5006 assert( cursorOwnsBtShared(pCur) ); 5007 rc = btreeRestoreCursorPosition(pCur); 5008 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); 5009 } 5010 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ 5011 if( pCur->eState==CURSOR_VALID ){ 5012 assert( cursorOwnsBtShared(pCur) ); 5013 return accessPayload(pCur, offset, amt, pBuf, 0); 5014 }else{ 5015 return accessPayloadChecked(pCur, offset, amt, pBuf); 5016 } 5017 } 5018 #endif /* SQLITE_OMIT_INCRBLOB */ 5019 5020 /* 5021 ** Return a pointer to payload information from the entry that the 5022 ** pCur cursor is pointing to. The pointer is to the beginning of 5023 ** the key if index btrees (pPage->intKey==0) and is the data for 5024 ** table btrees (pPage->intKey==1). The number of bytes of available 5025 ** key/data is written into *pAmt. If *pAmt==0, then the value 5026 ** returned will not be a valid pointer. 5027 ** 5028 ** This routine is an optimization. It is common for the entire key 5029 ** and data to fit on the local page and for there to be no overflow 5030 ** pages. When that is so, this routine can be used to access the 5031 ** key and data without making a copy. If the key and/or data spills 5032 ** onto overflow pages, then accessPayload() must be used to reassemble 5033 ** the key/data and copy it into a preallocated buffer. 5034 ** 5035 ** The pointer returned by this routine looks directly into the cached 5036 ** page of the database. The data might change or move the next time 5037 ** any btree routine is called. 5038 */ 5039 static const void *fetchPayload( 5040 BtCursor *pCur, /* Cursor pointing to entry to read from */ 5041 u32 *pAmt /* Write the number of available bytes here */ 5042 ){ 5043 int amt; 5044 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage); 5045 assert( pCur->eState==CURSOR_VALID ); 5046 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5047 assert( cursorOwnsBtShared(pCur) ); 5048 assert( pCur->ix<pCur->pPage->nCell ); 5049 assert( pCur->info.nSize>0 ); 5050 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB ); 5051 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB); 5052 amt = pCur->info.nLocal; 5053 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){ 5054 /* There is too little space on the page for the expected amount 5055 ** of local content. Database must be corrupt. */ 5056 assert( CORRUPT_DB ); 5057 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload)); 5058 } 5059 *pAmt = (u32)amt; 5060 return (void*)pCur->info.pPayload; 5061 } 5062 5063 5064 /* 5065 ** For the entry that cursor pCur is point to, return as 5066 ** many bytes of the key or data as are available on the local 5067 ** b-tree page. Write the number of available bytes into *pAmt. 5068 ** 5069 ** The pointer returned is ephemeral. The key/data may move 5070 ** or be destroyed on the next call to any Btree routine, 5071 ** including calls from other threads against the same cache. 5072 ** Hence, a mutex on the BtShared should be held prior to calling 5073 ** this routine. 5074 ** 5075 ** These routines is used to get quick access to key and data 5076 ** in the common case where no overflow pages are used. 5077 */ 5078 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ 5079 return fetchPayload(pCur, pAmt); 5080 } 5081 5082 5083 /* 5084 ** Move the cursor down to a new child page. The newPgno argument is the 5085 ** page number of the child page to move to. 5086 ** 5087 ** This function returns SQLITE_CORRUPT if the page-header flags field of 5088 ** the new child page does not match the flags field of the parent (i.e. 5089 ** if an intkey page appears to be the parent of a non-intkey page, or 5090 ** vice-versa). 5091 */ 5092 static int moveToChild(BtCursor *pCur, u32 newPgno){ 5093 BtShared *pBt = pCur->pBt; 5094 5095 assert( cursorOwnsBtShared(pCur) ); 5096 assert( pCur->eState==CURSOR_VALID ); 5097 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); 5098 assert( pCur->iPage>=0 ); 5099 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ 5100 return SQLITE_CORRUPT_BKPT; 5101 } 5102 pCur->info.nSize = 0; 5103 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5104 pCur->aiIdx[pCur->iPage] = pCur->ix; 5105 pCur->apPage[pCur->iPage] = pCur->pPage; 5106 pCur->ix = 0; 5107 pCur->iPage++; 5108 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags); 5109 } 5110 5111 #ifdef SQLITE_DEBUG 5112 /* 5113 ** Page pParent is an internal (non-leaf) tree page. This function 5114 ** asserts that page number iChild is the left-child if the iIdx'th 5115 ** cell in page pParent. Or, if iIdx is equal to the total number of 5116 ** cells in pParent, that page number iChild is the right-child of 5117 ** the page. 5118 */ 5119 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ 5120 if( CORRUPT_DB ) return; /* The conditions tested below might not be true 5121 ** in a corrupt database */ 5122 assert( iIdx<=pParent->nCell ); 5123 if( iIdx==pParent->nCell ){ 5124 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); 5125 }else{ 5126 assert( get4byte(findCell(pParent, iIdx))==iChild ); 5127 } 5128 } 5129 #else 5130 # define assertParentIndex(x,y,z) 5131 #endif 5132 5133 /* 5134 ** Move the cursor up to the parent page. 5135 ** 5136 ** pCur->idx is set to the cell index that contains the pointer 5137 ** to the page we are coming from. If we are coming from the 5138 ** right-most child page then pCur->idx is set to one more than 5139 ** the largest cell index. 5140 */ 5141 static void moveToParent(BtCursor *pCur){ 5142 MemPage *pLeaf; 5143 assert( cursorOwnsBtShared(pCur) ); 5144 assert( pCur->eState==CURSOR_VALID ); 5145 assert( pCur->iPage>0 ); 5146 assert( pCur->pPage ); 5147 assertParentIndex( 5148 pCur->apPage[pCur->iPage-1], 5149 pCur->aiIdx[pCur->iPage-1], 5150 pCur->pPage->pgno 5151 ); 5152 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); 5153 pCur->info.nSize = 0; 5154 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5155 pCur->ix = pCur->aiIdx[pCur->iPage-1]; 5156 pLeaf = pCur->pPage; 5157 pCur->pPage = pCur->apPage[--pCur->iPage]; 5158 releasePageNotNull(pLeaf); 5159 } 5160 5161 /* 5162 ** Move the cursor to point to the root page of its b-tree structure. 5163 ** 5164 ** If the table has a virtual root page, then the cursor is moved to point 5165 ** to the virtual root page instead of the actual root page. A table has a 5166 ** virtual root page when the actual root page contains no cells and a 5167 ** single child page. This can only happen with the table rooted at page 1. 5168 ** 5169 ** If the b-tree structure is empty, the cursor state is set to 5170 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise, 5171 ** the cursor is set to point to the first cell located on the root 5172 ** (or virtual root) page and the cursor state is set to CURSOR_VALID. 5173 ** 5174 ** If this function returns successfully, it may be assumed that the 5175 ** page-header flags indicate that the [virtual] root-page is the expected 5176 ** kind of b-tree page (i.e. if when opening the cursor the caller did not 5177 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, 5178 ** indicating a table b-tree, or if the caller did specify a KeyInfo 5179 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index 5180 ** b-tree). 5181 */ 5182 static int moveToRoot(BtCursor *pCur){ 5183 MemPage *pRoot; 5184 int rc = SQLITE_OK; 5185 5186 assert( cursorOwnsBtShared(pCur) ); 5187 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); 5188 assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); 5189 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); 5190 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 ); 5191 assert( pCur->pgnoRoot>0 || pCur->iPage<0 ); 5192 5193 if( pCur->iPage>=0 ){ 5194 if( pCur->iPage ){ 5195 releasePageNotNull(pCur->pPage); 5196 while( --pCur->iPage ){ 5197 releasePageNotNull(pCur->apPage[pCur->iPage]); 5198 } 5199 pCur->pPage = pCur->apPage[0]; 5200 goto skip_init; 5201 } 5202 }else if( pCur->pgnoRoot==0 ){ 5203 pCur->eState = CURSOR_INVALID; 5204 return SQLITE_EMPTY; 5205 }else{ 5206 assert( pCur->iPage==(-1) ); 5207 if( pCur->eState>=CURSOR_REQUIRESEEK ){ 5208 if( pCur->eState==CURSOR_FAULT ){ 5209 assert( pCur->skipNext!=SQLITE_OK ); 5210 return pCur->skipNext; 5211 } 5212 sqlite3BtreeClearCursor(pCur); 5213 } 5214 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage, 5215 0, pCur->curPagerFlags); 5216 if( rc!=SQLITE_OK ){ 5217 pCur->eState = CURSOR_INVALID; 5218 return rc; 5219 } 5220 pCur->iPage = 0; 5221 pCur->curIntKey = pCur->pPage->intKey; 5222 } 5223 pRoot = pCur->pPage; 5224 assert( pRoot->pgno==pCur->pgnoRoot ); 5225 5226 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor 5227 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is 5228 ** NULL, the caller expects a table b-tree. If this is not the case, 5229 ** return an SQLITE_CORRUPT error. 5230 ** 5231 ** Earlier versions of SQLite assumed that this test could not fail 5232 ** if the root page was already loaded when this function was called (i.e. 5233 ** if pCur->iPage>=0). But this is not so if the database is corrupted 5234 ** in such a way that page pRoot is linked into a second b-tree table 5235 ** (or the freelist). */ 5236 assert( pRoot->intKey==1 || pRoot->intKey==0 ); 5237 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ 5238 return SQLITE_CORRUPT_PAGE(pCur->pPage); 5239 } 5240 5241 skip_init: 5242 pCur->ix = 0; 5243 pCur->info.nSize = 0; 5244 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); 5245 5246 pRoot = pCur->pPage; 5247 if( pRoot->nCell>0 ){ 5248 pCur->eState = CURSOR_VALID; 5249 }else if( !pRoot->leaf ){ 5250 Pgno subpage; 5251 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; 5252 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); 5253 pCur->eState = CURSOR_VALID; 5254 rc = moveToChild(pCur, subpage); 5255 }else{ 5256 pCur->eState = CURSOR_INVALID; 5257 rc = SQLITE_EMPTY; 5258 } 5259 return rc; 5260 } 5261 5262 /* 5263 ** Move the cursor down to the left-most leaf entry beneath the 5264 ** entry to which it is currently pointing. 5265 ** 5266 ** The left-most leaf is the one with the smallest key - the first 5267 ** in ascending order. 5268 */ 5269 static int moveToLeftmost(BtCursor *pCur){ 5270 Pgno pgno; 5271 int rc = SQLITE_OK; 5272 MemPage *pPage; 5273 5274 assert( cursorOwnsBtShared(pCur) ); 5275 assert( pCur->eState==CURSOR_VALID ); 5276 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ 5277 assert( pCur->ix<pPage->nCell ); 5278 pgno = get4byte(findCell(pPage, pCur->ix)); 5279 rc = moveToChild(pCur, pgno); 5280 } 5281 return rc; 5282 } 5283 5284 /* 5285 ** Move the cursor down to the right-most leaf entry beneath the 5286 ** page to which it is currently pointing. Notice the difference 5287 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() 5288 ** finds the left-most entry beneath the *entry* whereas moveToRightmost() 5289 ** finds the right-most entry beneath the *page*. 5290 ** 5291 ** The right-most entry is the one with the largest key - the last 5292 ** key in ascending order. 5293 */ 5294 static int moveToRightmost(BtCursor *pCur){ 5295 Pgno pgno; 5296 int rc = SQLITE_OK; 5297 MemPage *pPage = 0; 5298 5299 assert( cursorOwnsBtShared(pCur) ); 5300 assert( pCur->eState==CURSOR_VALID ); 5301 while( !(pPage = pCur->pPage)->leaf ){ 5302 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5303 pCur->ix = pPage->nCell; 5304 rc = moveToChild(pCur, pgno); 5305 if( rc ) return rc; 5306 } 5307 pCur->ix = pPage->nCell-1; 5308 assert( pCur->info.nSize==0 ); 5309 assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); 5310 return SQLITE_OK; 5311 } 5312 5313 /* Move the cursor to the first entry in the table. Return SQLITE_OK 5314 ** on success. Set *pRes to 0 if the cursor actually points to something 5315 ** or set *pRes to 1 if the table is empty. 5316 */ 5317 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ 5318 int rc; 5319 5320 assert( cursorOwnsBtShared(pCur) ); 5321 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5322 rc = moveToRoot(pCur); 5323 if( rc==SQLITE_OK ){ 5324 assert( pCur->pPage->nCell>0 ); 5325 *pRes = 0; 5326 rc = moveToLeftmost(pCur); 5327 }else if( rc==SQLITE_EMPTY ){ 5328 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5329 *pRes = 1; 5330 rc = SQLITE_OK; 5331 } 5332 return rc; 5333 } 5334 5335 /* Move the cursor to the last entry in the table. Return SQLITE_OK 5336 ** on success. Set *pRes to 0 if the cursor actually points to something 5337 ** or set *pRes to 1 if the table is empty. 5338 */ 5339 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ 5340 int rc; 5341 5342 assert( cursorOwnsBtShared(pCur) ); 5343 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5344 5345 /* If the cursor already points to the last entry, this is a no-op. */ 5346 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ 5347 #ifdef SQLITE_DEBUG 5348 /* This block serves to assert() that the cursor really does point 5349 ** to the last entry in the b-tree. */ 5350 int ii; 5351 for(ii=0; ii<pCur->iPage; ii++){ 5352 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); 5353 } 5354 assert( pCur->ix==pCur->pPage->nCell-1 ); 5355 assert( pCur->pPage->leaf ); 5356 #endif 5357 *pRes = 0; 5358 return SQLITE_OK; 5359 } 5360 5361 rc = moveToRoot(pCur); 5362 if( rc==SQLITE_OK ){ 5363 assert( pCur->eState==CURSOR_VALID ); 5364 *pRes = 0; 5365 rc = moveToRightmost(pCur); 5366 if( rc==SQLITE_OK ){ 5367 pCur->curFlags |= BTCF_AtLast; 5368 }else{ 5369 pCur->curFlags &= ~BTCF_AtLast; 5370 } 5371 }else if( rc==SQLITE_EMPTY ){ 5372 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5373 *pRes = 1; 5374 rc = SQLITE_OK; 5375 } 5376 return rc; 5377 } 5378 5379 /* Move the cursor so that it points to an entry near the key 5380 ** specified by pIdxKey or intKey. Return a success code. 5381 ** 5382 ** For INTKEY tables, the intKey parameter is used. pIdxKey 5383 ** must be NULL. For index tables, pIdxKey is used and intKey 5384 ** is ignored. 5385 ** 5386 ** If an exact match is not found, then the cursor is always 5387 ** left pointing at a leaf page which would hold the entry if it 5388 ** were present. The cursor might point to an entry that comes 5389 ** before or after the key. 5390 ** 5391 ** An integer is written into *pRes which is the result of 5392 ** comparing the key with the entry to which the cursor is 5393 ** pointing. The meaning of the integer written into 5394 ** *pRes is as follows: 5395 ** 5396 ** *pRes<0 The cursor is left pointing at an entry that 5397 ** is smaller than intKey/pIdxKey or if the table is empty 5398 ** and the cursor is therefore left point to nothing. 5399 ** 5400 ** *pRes==0 The cursor is left pointing at an entry that 5401 ** exactly matches intKey/pIdxKey. 5402 ** 5403 ** *pRes>0 The cursor is left pointing at an entry that 5404 ** is larger than intKey/pIdxKey. 5405 ** 5406 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there 5407 ** exists an entry in the table that exactly matches pIdxKey. 5408 */ 5409 int sqlite3BtreeMovetoUnpacked( 5410 BtCursor *pCur, /* The cursor to be moved */ 5411 UnpackedRecord *pIdxKey, /* Unpacked index key */ 5412 i64 intKey, /* The table key */ 5413 int biasRight, /* If true, bias the search to the high end */ 5414 int *pRes /* Write search results here */ 5415 ){ 5416 int rc; 5417 RecordCompare xRecordCompare; 5418 5419 assert( cursorOwnsBtShared(pCur) ); 5420 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5421 assert( pRes ); 5422 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); 5423 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) ); 5424 5425 /* If the cursor is already positioned at the point we are trying 5426 ** to move to, then just return without doing any work */ 5427 if( pIdxKey==0 5428 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 5429 ){ 5430 if( pCur->info.nKey==intKey ){ 5431 *pRes = 0; 5432 return SQLITE_OK; 5433 } 5434 if( pCur->info.nKey<intKey ){ 5435 if( (pCur->curFlags & BTCF_AtLast)!=0 ){ 5436 *pRes = -1; 5437 return SQLITE_OK; 5438 } 5439 /* If the requested key is one more than the previous key, then 5440 ** try to get there using sqlite3BtreeNext() rather than a full 5441 ** binary search. This is an optimization only. The correct answer 5442 ** is still obtained without this case, only a little more slowely */ 5443 if( pCur->info.nKey+1==intKey ){ 5444 *pRes = 0; 5445 rc = sqlite3BtreeNext(pCur, 0); 5446 if( rc==SQLITE_OK ){ 5447 getCellInfo(pCur); 5448 if( pCur->info.nKey==intKey ){ 5449 return SQLITE_OK; 5450 } 5451 }else if( rc==SQLITE_DONE ){ 5452 rc = SQLITE_OK; 5453 }else{ 5454 return rc; 5455 } 5456 } 5457 } 5458 } 5459 5460 if( pIdxKey ){ 5461 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); 5462 pIdxKey->errCode = 0; 5463 assert( pIdxKey->default_rc==1 5464 || pIdxKey->default_rc==0 5465 || pIdxKey->default_rc==-1 5466 ); 5467 }else{ 5468 xRecordCompare = 0; /* All keys are integers */ 5469 } 5470 5471 rc = moveToRoot(pCur); 5472 if( rc ){ 5473 if( rc==SQLITE_EMPTY ){ 5474 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); 5475 *pRes = -1; 5476 return SQLITE_OK; 5477 } 5478 return rc; 5479 } 5480 assert( pCur->pPage ); 5481 assert( pCur->pPage->isInit ); 5482 assert( pCur->eState==CURSOR_VALID ); 5483 assert( pCur->pPage->nCell > 0 ); 5484 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey ); 5485 assert( pCur->curIntKey || pIdxKey ); 5486 for(;;){ 5487 int lwr, upr, idx, c; 5488 Pgno chldPg; 5489 MemPage *pPage = pCur->pPage; 5490 u8 *pCell; /* Pointer to current cell in pPage */ 5491 5492 /* pPage->nCell must be greater than zero. If this is the root-page 5493 ** the cursor would have been INVALID above and this for(;;) loop 5494 ** not run. If this is not the root-page, then the moveToChild() routine 5495 ** would have already detected db corruption. Similarly, pPage must 5496 ** be the right kind (index or table) of b-tree page. Otherwise 5497 ** a moveToChild() or moveToRoot() call would have detected corruption. */ 5498 assert( pPage->nCell>0 ); 5499 assert( pPage->intKey==(pIdxKey==0) ); 5500 lwr = 0; 5501 upr = pPage->nCell-1; 5502 assert( biasRight==0 || biasRight==1 ); 5503 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ 5504 pCur->ix = (u16)idx; 5505 if( xRecordCompare==0 ){ 5506 for(;;){ 5507 i64 nCellKey; 5508 pCell = findCellPastPtr(pPage, idx); 5509 if( pPage->intKeyLeaf ){ 5510 while( 0x80 <= *(pCell++) ){ 5511 if( pCell>=pPage->aDataEnd ){ 5512 return SQLITE_CORRUPT_PAGE(pPage); 5513 } 5514 } 5515 } 5516 getVarint(pCell, (u64*)&nCellKey); 5517 if( nCellKey<intKey ){ 5518 lwr = idx+1; 5519 if( lwr>upr ){ c = -1; break; } 5520 }else if( nCellKey>intKey ){ 5521 upr = idx-1; 5522 if( lwr>upr ){ c = +1; break; } 5523 }else{ 5524 assert( nCellKey==intKey ); 5525 pCur->ix = (u16)idx; 5526 if( !pPage->leaf ){ 5527 lwr = idx; 5528 goto moveto_next_layer; 5529 }else{ 5530 pCur->curFlags |= BTCF_ValidNKey; 5531 pCur->info.nKey = nCellKey; 5532 pCur->info.nSize = 0; 5533 *pRes = 0; 5534 return SQLITE_OK; 5535 } 5536 } 5537 assert( lwr+upr>=0 ); 5538 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ 5539 } 5540 }else{ 5541 for(;;){ 5542 int nCell; /* Size of the pCell cell in bytes */ 5543 pCell = findCellPastPtr(pPage, idx); 5544 5545 /* The maximum supported page-size is 65536 bytes. This means that 5546 ** the maximum number of record bytes stored on an index B-Tree 5547 ** page is less than 16384 bytes and may be stored as a 2-byte 5548 ** varint. This information is used to attempt to avoid parsing 5549 ** the entire cell by checking for the cases where the record is 5550 ** stored entirely within the b-tree page by inspecting the first 5551 ** 2 bytes of the cell. 5552 */ 5553 nCell = pCell[0]; 5554 if( nCell<=pPage->max1bytePayload ){ 5555 /* This branch runs if the record-size field of the cell is a 5556 ** single byte varint and the record fits entirely on the main 5557 ** b-tree page. */ 5558 testcase( pCell+nCell+1==pPage->aDataEnd ); 5559 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); 5560 }else if( !(pCell[1] & 0x80) 5561 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal 5562 ){ 5563 /* The record-size field is a 2 byte varint and the record 5564 ** fits entirely on the main b-tree page. */ 5565 testcase( pCell+nCell+2==pPage->aDataEnd ); 5566 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); 5567 }else{ 5568 /* The record flows over onto one or more overflow pages. In 5569 ** this case the whole cell needs to be parsed, a buffer allocated 5570 ** and accessPayload() used to retrieve the record into the 5571 ** buffer before VdbeRecordCompare() can be called. 5572 ** 5573 ** If the record is corrupt, the xRecordCompare routine may read 5574 ** up to two varints past the end of the buffer. An extra 18 5575 ** bytes of padding is allocated at the end of the buffer in 5576 ** case this happens. */ 5577 void *pCellKey; 5578 u8 * const pCellBody = pCell - pPage->childPtrSize; 5579 const int nOverrun = 18; /* Size of the overrun padding */ 5580 pPage->xParseCell(pPage, pCellBody, &pCur->info); 5581 nCell = (int)pCur->info.nKey; 5582 testcase( nCell<0 ); /* True if key size is 2^32 or more */ 5583 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ 5584 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ 5585 testcase( nCell==2 ); /* Minimum legal index key size */ 5586 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){ 5587 rc = SQLITE_CORRUPT_PAGE(pPage); 5588 goto moveto_finish; 5589 } 5590 pCellKey = sqlite3Malloc( nCell+nOverrun ); 5591 if( pCellKey==0 ){ 5592 rc = SQLITE_NOMEM_BKPT; 5593 goto moveto_finish; 5594 } 5595 pCur->ix = (u16)idx; 5596 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); 5597 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */ 5598 pCur->curFlags &= ~BTCF_ValidOvfl; 5599 if( rc ){ 5600 sqlite3_free(pCellKey); 5601 goto moveto_finish; 5602 } 5603 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); 5604 sqlite3_free(pCellKey); 5605 } 5606 assert( 5607 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) 5608 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) 5609 ); 5610 if( c<0 ){ 5611 lwr = idx+1; 5612 }else if( c>0 ){ 5613 upr = idx-1; 5614 }else{ 5615 assert( c==0 ); 5616 *pRes = 0; 5617 rc = SQLITE_OK; 5618 pCur->ix = (u16)idx; 5619 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT; 5620 goto moveto_finish; 5621 } 5622 if( lwr>upr ) break; 5623 assert( lwr+upr>=0 ); 5624 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ 5625 } 5626 } 5627 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); 5628 assert( pPage->isInit ); 5629 if( pPage->leaf ){ 5630 assert( pCur->ix<pCur->pPage->nCell ); 5631 pCur->ix = (u16)idx; 5632 *pRes = c; 5633 rc = SQLITE_OK; 5634 goto moveto_finish; 5635 } 5636 moveto_next_layer: 5637 if( lwr>=pPage->nCell ){ 5638 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); 5639 }else{ 5640 chldPg = get4byte(findCell(pPage, lwr)); 5641 } 5642 pCur->ix = (u16)lwr; 5643 rc = moveToChild(pCur, chldPg); 5644 if( rc ) break; 5645 } 5646 moveto_finish: 5647 pCur->info.nSize = 0; 5648 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5649 return rc; 5650 } 5651 5652 5653 /* 5654 ** Return TRUE if the cursor is not pointing at an entry of the table. 5655 ** 5656 ** TRUE will be returned after a call to sqlite3BtreeNext() moves 5657 ** past the last entry in the table or sqlite3BtreePrev() moves past 5658 ** the first entry. TRUE is also returned if the table is empty. 5659 */ 5660 int sqlite3BtreeEof(BtCursor *pCur){ 5661 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries 5662 ** have been deleted? This API will need to change to return an error code 5663 ** as well as the boolean result value. 5664 */ 5665 return (CURSOR_VALID!=pCur->eState); 5666 } 5667 5668 /* 5669 ** Return an estimate for the number of rows in the table that pCur is 5670 ** pointing to. Return a negative number if no estimate is currently 5671 ** available. 5672 */ 5673 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){ 5674 i64 n; 5675 u8 i; 5676 5677 assert( cursorOwnsBtShared(pCur) ); 5678 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); 5679 5680 /* Currently this interface is only called by the OP_IfSmaller 5681 ** opcode, and it that case the cursor will always be valid and 5682 ** will always point to a leaf node. */ 5683 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1; 5684 if( NEVER(pCur->pPage->leaf==0) ) return -1; 5685 5686 n = pCur->pPage->nCell; 5687 for(i=0; i<pCur->iPage; i++){ 5688 n *= pCur->apPage[i]->nCell; 5689 } 5690 return n; 5691 } 5692 5693 /* 5694 ** Advance the cursor to the next entry in the database. 5695 ** Return value: 5696 ** 5697 ** SQLITE_OK success 5698 ** SQLITE_DONE cursor is already pointing at the last element 5699 ** otherwise some kind of error occurred 5700 ** 5701 ** The main entry point is sqlite3BtreeNext(). That routine is optimized 5702 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx 5703 ** to the next cell on the current page. The (slower) btreeNext() helper 5704 ** routine is called when it is necessary to move to a different page or 5705 ** to restore the cursor. 5706 ** 5707 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the 5708 ** cursor corresponds to an SQL index and this routine could have been 5709 ** skipped if the SQL index had been a unique index. The F argument 5710 ** is a hint to the implement. SQLite btree implementation does not use 5711 ** this hint, but COMDB2 does. 5712 */ 5713 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){ 5714 int rc; 5715 int idx; 5716 MemPage *pPage; 5717 5718 assert( cursorOwnsBtShared(pCur) ); 5719 if( pCur->eState!=CURSOR_VALID ){ 5720 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); 5721 rc = restoreCursorPosition(pCur); 5722 if( rc!=SQLITE_OK ){ 5723 return rc; 5724 } 5725 if( CURSOR_INVALID==pCur->eState ){ 5726 return SQLITE_DONE; 5727 } 5728 if( pCur->eState==CURSOR_SKIPNEXT ){ 5729 pCur->eState = CURSOR_VALID; 5730 if( pCur->skipNext>0 ) return SQLITE_OK; 5731 } 5732 } 5733 5734 pPage = pCur->pPage; 5735 idx = ++pCur->ix; 5736 if( !pPage->isInit ){ 5737 /* The only known way for this to happen is for there to be a 5738 ** recursive SQL function that does a DELETE operation as part of a 5739 ** SELECT which deletes content out from under an active cursor 5740 ** in a corrupt database file where the table being DELETE-ed from 5741 ** has pages in common with the table being queried. See TH3 5742 ** module cov1/btree78.test testcase 220 (2018-06-08) for an 5743 ** example. */ 5744 return SQLITE_CORRUPT_BKPT; 5745 } 5746 5747 /* If the database file is corrupt, it is possible for the value of idx 5748 ** to be invalid here. This can only occur if a second cursor modifies 5749 ** the page while cursor pCur is holding a reference to it. Which can 5750 ** only happen if the database is corrupt in such a way as to link the 5751 ** page into more than one b-tree structure. 5752 ** 5753 ** Update 2019-12-23: appears to long longer be possible after the 5754 ** addition of anotherValidCursor() condition on balance_deeper(). */ 5755 harmless( idx>pPage->nCell ); 5756 5757 if( idx>=pPage->nCell ){ 5758 if( !pPage->leaf ){ 5759 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 5760 if( rc ) return rc; 5761 return moveToLeftmost(pCur); 5762 } 5763 do{ 5764 if( pCur->iPage==0 ){ 5765 pCur->eState = CURSOR_INVALID; 5766 return SQLITE_DONE; 5767 } 5768 moveToParent(pCur); 5769 pPage = pCur->pPage; 5770 }while( pCur->ix>=pPage->nCell ); 5771 if( pPage->intKey ){ 5772 return sqlite3BtreeNext(pCur, 0); 5773 }else{ 5774 return SQLITE_OK; 5775 } 5776 } 5777 if( pPage->leaf ){ 5778 return SQLITE_OK; 5779 }else{ 5780 return moveToLeftmost(pCur); 5781 } 5782 } 5783 int sqlite3BtreeNext(BtCursor *pCur, int flags){ 5784 MemPage *pPage; 5785 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ 5786 assert( cursorOwnsBtShared(pCur) ); 5787 assert( flags==0 || flags==1 ); 5788 pCur->info.nSize = 0; 5789 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); 5790 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur); 5791 pPage = pCur->pPage; 5792 if( (++pCur->ix)>=pPage->nCell ){ 5793 pCur->ix--; 5794 return btreeNext(pCur); 5795 } 5796 if( pPage->leaf ){ 5797 return SQLITE_OK; 5798 }else{ 5799 return moveToLeftmost(pCur); 5800 } 5801 } 5802 5803 /* 5804 ** Step the cursor to the back to the previous entry in the database. 5805 ** Return values: 5806 ** 5807 ** SQLITE_OK success 5808 ** SQLITE_DONE the cursor is already on the first element of the table 5809 ** otherwise some kind of error occurred 5810 ** 5811 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized 5812 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx 5813 ** to the previous cell on the current page. The (slower) btreePrevious() 5814 ** helper routine is called when it is necessary to move to a different page 5815 ** or to restore the cursor. 5816 ** 5817 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then 5818 ** the cursor corresponds to an SQL index and this routine could have been 5819 ** skipped if the SQL index had been a unique index. The F argument is a 5820 ** hint to the implement. The native SQLite btree implementation does not 5821 ** use this hint, but COMDB2 does. 5822 */ 5823 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){ 5824 int rc; 5825 MemPage *pPage; 5826 5827 assert( cursorOwnsBtShared(pCur) ); 5828 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); 5829 assert( pCur->info.nSize==0 ); 5830 if( pCur->eState!=CURSOR_VALID ){ 5831 rc = restoreCursorPosition(pCur); 5832 if( rc!=SQLITE_OK ){ 5833 return rc; 5834 } 5835 if( CURSOR_INVALID==pCur->eState ){ 5836 return SQLITE_DONE; 5837 } 5838 if( CURSOR_SKIPNEXT==pCur->eState ){ 5839 pCur->eState = CURSOR_VALID; 5840 if( pCur->skipNext<0 ) return SQLITE_OK; 5841 } 5842 } 5843 5844 pPage = pCur->pPage; 5845 assert( pPage->isInit ); 5846 if( !pPage->leaf ){ 5847 int idx = pCur->ix; 5848 rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); 5849 if( rc ) return rc; 5850 rc = moveToRightmost(pCur); 5851 }else{ 5852 while( pCur->ix==0 ){ 5853 if( pCur->iPage==0 ){ 5854 pCur->eState = CURSOR_INVALID; 5855 return SQLITE_DONE; 5856 } 5857 moveToParent(pCur); 5858 } 5859 assert( pCur->info.nSize==0 ); 5860 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 ); 5861 5862 pCur->ix--; 5863 pPage = pCur->pPage; 5864 if( pPage->intKey && !pPage->leaf ){ 5865 rc = sqlite3BtreePrevious(pCur, 0); 5866 }else{ 5867 rc = SQLITE_OK; 5868 } 5869 } 5870 return rc; 5871 } 5872 int sqlite3BtreePrevious(BtCursor *pCur, int flags){ 5873 assert( cursorOwnsBtShared(pCur) ); 5874 assert( flags==0 || flags==1 ); 5875 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ 5876 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); 5877 pCur->info.nSize = 0; 5878 if( pCur->eState!=CURSOR_VALID 5879 || pCur->ix==0 5880 || pCur->pPage->leaf==0 5881 ){ 5882 return btreePrevious(pCur); 5883 } 5884 pCur->ix--; 5885 return SQLITE_OK; 5886 } 5887 5888 /* 5889 ** Allocate a new page from the database file. 5890 ** 5891 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() 5892 ** has already been called on the new page.) The new page has also 5893 ** been referenced and the calling routine is responsible for calling 5894 ** sqlite3PagerUnref() on the new page when it is done. 5895 ** 5896 ** SQLITE_OK is returned on success. Any other return value indicates 5897 ** an error. *ppPage is set to NULL in the event of an error. 5898 ** 5899 ** If the "nearby" parameter is not 0, then an effort is made to 5900 ** locate a page close to the page number "nearby". This can be used in an 5901 ** attempt to keep related pages close to each other in the database file, 5902 ** which in turn can make database access faster. 5903 ** 5904 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists 5905 ** anywhere on the free-list, then it is guaranteed to be returned. If 5906 ** eMode is BTALLOC_LT then the page returned will be less than or equal 5907 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there 5908 ** are no restrictions on which page is returned. 5909 */ 5910 static int allocateBtreePage( 5911 BtShared *pBt, /* The btree */ 5912 MemPage **ppPage, /* Store pointer to the allocated page here */ 5913 Pgno *pPgno, /* Store the page number here */ 5914 Pgno nearby, /* Search for a page near this one */ 5915 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ 5916 ){ 5917 MemPage *pPage1; 5918 int rc; 5919 u32 n; /* Number of pages on the freelist */ 5920 u32 k; /* Number of leaves on the trunk of the freelist */ 5921 MemPage *pTrunk = 0; 5922 MemPage *pPrevTrunk = 0; 5923 Pgno mxPage; /* Total size of the database file */ 5924 5925 assert( sqlite3_mutex_held(pBt->mutex) ); 5926 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); 5927 pPage1 = pBt->pPage1; 5928 mxPage = btreePagecount(pBt); 5929 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 5930 ** stores stores the total number of pages on the freelist. */ 5931 n = get4byte(&pPage1->aData[36]); 5932 testcase( n==mxPage-1 ); 5933 if( n>=mxPage ){ 5934 return SQLITE_CORRUPT_BKPT; 5935 } 5936 if( n>0 ){ 5937 /* There are pages on the freelist. Reuse one of those pages. */ 5938 Pgno iTrunk; 5939 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ 5940 u32 nSearch = 0; /* Count of the number of search attempts */ 5941 5942 /* If eMode==BTALLOC_EXACT and a query of the pointer-map 5943 ** shows that the page 'nearby' is somewhere on the free-list, then 5944 ** the entire-list will be searched for that page. 5945 */ 5946 #ifndef SQLITE_OMIT_AUTOVACUUM 5947 if( eMode==BTALLOC_EXACT ){ 5948 if( nearby<=mxPage ){ 5949 u8 eType; 5950 assert( nearby>0 ); 5951 assert( pBt->autoVacuum ); 5952 rc = ptrmapGet(pBt, nearby, &eType, 0); 5953 if( rc ) return rc; 5954 if( eType==PTRMAP_FREEPAGE ){ 5955 searchList = 1; 5956 } 5957 } 5958 }else if( eMode==BTALLOC_LE ){ 5959 searchList = 1; 5960 } 5961 #endif 5962 5963 /* Decrement the free-list count by 1. Set iTrunk to the index of the 5964 ** first free-list trunk page. iPrevTrunk is initially 1. 5965 */ 5966 rc = sqlite3PagerWrite(pPage1->pDbPage); 5967 if( rc ) return rc; 5968 put4byte(&pPage1->aData[36], n-1); 5969 5970 /* The code within this loop is run only once if the 'searchList' variable 5971 ** is not true. Otherwise, it runs once for each trunk-page on the 5972 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) 5973 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) 5974 */ 5975 do { 5976 pPrevTrunk = pTrunk; 5977 if( pPrevTrunk ){ 5978 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page 5979 ** is the page number of the next freelist trunk page in the list or 5980 ** zero if this is the last freelist trunk page. */ 5981 iTrunk = get4byte(&pPrevTrunk->aData[0]); 5982 }else{ 5983 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 5984 ** stores the page number of the first page of the freelist, or zero if 5985 ** the freelist is empty. */ 5986 iTrunk = get4byte(&pPage1->aData[32]); 5987 } 5988 testcase( iTrunk==mxPage ); 5989 if( iTrunk>mxPage || nSearch++ > n ){ 5990 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1); 5991 }else{ 5992 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); 5993 } 5994 if( rc ){ 5995 pTrunk = 0; 5996 goto end_allocate_page; 5997 } 5998 assert( pTrunk!=0 ); 5999 assert( pTrunk->aData!=0 ); 6000 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page 6001 ** is the number of leaf page pointers to follow. */ 6002 k = get4byte(&pTrunk->aData[4]); 6003 if( k==0 && !searchList ){ 6004 /* The trunk has no leaves and the list is not being searched. 6005 ** So extract the trunk page itself and use it as the newly 6006 ** allocated page */ 6007 assert( pPrevTrunk==0 ); 6008 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6009 if( rc ){ 6010 goto end_allocate_page; 6011 } 6012 *pPgno = iTrunk; 6013 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 6014 *ppPage = pTrunk; 6015 pTrunk = 0; 6016 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 6017 }else if( k>(u32)(pBt->usableSize/4 - 2) ){ 6018 /* Value of k is out of range. Database corruption */ 6019 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6020 goto end_allocate_page; 6021 #ifndef SQLITE_OMIT_AUTOVACUUM 6022 }else if( searchList 6023 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 6024 ){ 6025 /* The list is being searched and this trunk page is the page 6026 ** to allocate, regardless of whether it has leaves. 6027 */ 6028 *pPgno = iTrunk; 6029 *ppPage = pTrunk; 6030 searchList = 0; 6031 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6032 if( rc ){ 6033 goto end_allocate_page; 6034 } 6035 if( k==0 ){ 6036 if( !pPrevTrunk ){ 6037 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); 6038 }else{ 6039 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 6040 if( rc!=SQLITE_OK ){ 6041 goto end_allocate_page; 6042 } 6043 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); 6044 } 6045 }else{ 6046 /* The trunk page is required by the caller but it contains 6047 ** pointers to free-list leaves. The first leaf becomes a trunk 6048 ** page in this case. 6049 */ 6050 MemPage *pNewTrunk; 6051 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); 6052 if( iNewTrunk>mxPage ){ 6053 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6054 goto end_allocate_page; 6055 } 6056 testcase( iNewTrunk==mxPage ); 6057 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); 6058 if( rc!=SQLITE_OK ){ 6059 goto end_allocate_page; 6060 } 6061 rc = sqlite3PagerWrite(pNewTrunk->pDbPage); 6062 if( rc!=SQLITE_OK ){ 6063 releasePage(pNewTrunk); 6064 goto end_allocate_page; 6065 } 6066 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); 6067 put4byte(&pNewTrunk->aData[4], k-1); 6068 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); 6069 releasePage(pNewTrunk); 6070 if( !pPrevTrunk ){ 6071 assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); 6072 put4byte(&pPage1->aData[32], iNewTrunk); 6073 }else{ 6074 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); 6075 if( rc ){ 6076 goto end_allocate_page; 6077 } 6078 put4byte(&pPrevTrunk->aData[0], iNewTrunk); 6079 } 6080 } 6081 pTrunk = 0; 6082 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); 6083 #endif 6084 }else if( k>0 ){ 6085 /* Extract a leaf from the trunk */ 6086 u32 closest; 6087 Pgno iPage; 6088 unsigned char *aData = pTrunk->aData; 6089 if( nearby>0 ){ 6090 u32 i; 6091 closest = 0; 6092 if( eMode==BTALLOC_LE ){ 6093 for(i=0; i<k; i++){ 6094 iPage = get4byte(&aData[8+i*4]); 6095 if( iPage<=nearby ){ 6096 closest = i; 6097 break; 6098 } 6099 } 6100 }else{ 6101 int dist; 6102 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); 6103 for(i=1; i<k; i++){ 6104 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); 6105 if( d2<dist ){ 6106 closest = i; 6107 dist = d2; 6108 } 6109 } 6110 } 6111 }else{ 6112 closest = 0; 6113 } 6114 6115 iPage = get4byte(&aData[8+closest*4]); 6116 testcase( iPage==mxPage ); 6117 if( iPage>mxPage ){ 6118 rc = SQLITE_CORRUPT_PGNO(iTrunk); 6119 goto end_allocate_page; 6120 } 6121 testcase( iPage==mxPage ); 6122 if( !searchList 6123 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 6124 ){ 6125 int noContent; 6126 *pPgno = iPage; 6127 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" 6128 ": %d more free pages\n", 6129 *pPgno, closest+1, k, pTrunk->pgno, n-1)); 6130 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6131 if( rc ) goto end_allocate_page; 6132 if( closest<k-1 ){ 6133 memcpy(&aData[8+closest*4], &aData[4+k*4], 4); 6134 } 6135 put4byte(&aData[4], k-1); 6136 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; 6137 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); 6138 if( rc==SQLITE_OK ){ 6139 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 6140 if( rc!=SQLITE_OK ){ 6141 releasePage(*ppPage); 6142 *ppPage = 0; 6143 } 6144 } 6145 searchList = 0; 6146 } 6147 } 6148 releasePage(pPrevTrunk); 6149 pPrevTrunk = 0; 6150 }while( searchList ); 6151 }else{ 6152 /* There are no pages on the freelist, so append a new page to the 6153 ** database image. 6154 ** 6155 ** Normally, new pages allocated by this block can be requested from the 6156 ** pager layer with the 'no-content' flag set. This prevents the pager 6157 ** from trying to read the pages content from disk. However, if the 6158 ** current transaction has already run one or more incremental-vacuum 6159 ** steps, then the page we are about to allocate may contain content 6160 ** that is required in the event of a rollback. In this case, do 6161 ** not set the no-content flag. This causes the pager to load and journal 6162 ** the current page content before overwriting it. 6163 ** 6164 ** Note that the pager will not actually attempt to load or journal 6165 ** content for any page that really does lie past the end of the database 6166 ** file on disk. So the effects of disabling the no-content optimization 6167 ** here are confined to those pages that lie between the end of the 6168 ** database image and the end of the database file. 6169 */ 6170 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; 6171 6172 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 6173 if( rc ) return rc; 6174 pBt->nPage++; 6175 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; 6176 6177 #ifndef SQLITE_OMIT_AUTOVACUUM 6178 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ 6179 /* If *pPgno refers to a pointer-map page, allocate two new pages 6180 ** at the end of the file instead of one. The first allocated page 6181 ** becomes a new pointer-map page, the second is used by the caller. 6182 */ 6183 MemPage *pPg = 0; 6184 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); 6185 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); 6186 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); 6187 if( rc==SQLITE_OK ){ 6188 rc = sqlite3PagerWrite(pPg->pDbPage); 6189 releasePage(pPg); 6190 } 6191 if( rc ) return rc; 6192 pBt->nPage++; 6193 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } 6194 } 6195 #endif 6196 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); 6197 *pPgno = pBt->nPage; 6198 6199 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); 6200 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); 6201 if( rc ) return rc; 6202 rc = sqlite3PagerWrite((*ppPage)->pDbPage); 6203 if( rc!=SQLITE_OK ){ 6204 releasePage(*ppPage); 6205 *ppPage = 0; 6206 } 6207 TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); 6208 } 6209 6210 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) ); 6211 6212 end_allocate_page: 6213 releasePage(pTrunk); 6214 releasePage(pPrevTrunk); 6215 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); 6216 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); 6217 return rc; 6218 } 6219 6220 /* 6221 ** This function is used to add page iPage to the database file free-list. 6222 ** It is assumed that the page is not already a part of the free-list. 6223 ** 6224 ** The value passed as the second argument to this function is optional. 6225 ** If the caller happens to have a pointer to the MemPage object 6226 ** corresponding to page iPage handy, it may pass it as the second value. 6227 ** Otherwise, it may pass NULL. 6228 ** 6229 ** If a pointer to a MemPage object is passed as the second argument, 6230 ** its reference count is not altered by this function. 6231 */ 6232 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ 6233 MemPage *pTrunk = 0; /* Free-list trunk page */ 6234 Pgno iTrunk = 0; /* Page number of free-list trunk page */ 6235 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ 6236 MemPage *pPage; /* Page being freed. May be NULL. */ 6237 int rc; /* Return Code */ 6238 u32 nFree; /* Initial number of pages on free-list */ 6239 6240 assert( sqlite3_mutex_held(pBt->mutex) ); 6241 assert( CORRUPT_DB || iPage>1 ); 6242 assert( !pMemPage || pMemPage->pgno==iPage ); 6243 6244 if( iPage<2 || iPage>pBt->nPage ){ 6245 return SQLITE_CORRUPT_BKPT; 6246 } 6247 if( pMemPage ){ 6248 pPage = pMemPage; 6249 sqlite3PagerRef(pPage->pDbPage); 6250 }else{ 6251 pPage = btreePageLookup(pBt, iPage); 6252 } 6253 6254 /* Increment the free page count on pPage1 */ 6255 rc = sqlite3PagerWrite(pPage1->pDbPage); 6256 if( rc ) goto freepage_out; 6257 nFree = get4byte(&pPage1->aData[36]); 6258 put4byte(&pPage1->aData[36], nFree+1); 6259 6260 if( pBt->btsFlags & BTS_SECURE_DELETE ){ 6261 /* If the secure_delete option is enabled, then 6262 ** always fully overwrite deleted information with zeros. 6263 */ 6264 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) 6265 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) 6266 ){ 6267 goto freepage_out; 6268 } 6269 memset(pPage->aData, 0, pPage->pBt->pageSize); 6270 } 6271 6272 /* If the database supports auto-vacuum, write an entry in the pointer-map 6273 ** to indicate that the page is free. 6274 */ 6275 if( ISAUTOVACUUM ){ 6276 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); 6277 if( rc ) goto freepage_out; 6278 } 6279 6280 /* Now manipulate the actual database free-list structure. There are two 6281 ** possibilities. If the free-list is currently empty, or if the first 6282 ** trunk page in the free-list is full, then this page will become a 6283 ** new free-list trunk page. Otherwise, it will become a leaf of the 6284 ** first trunk page in the current free-list. This block tests if it 6285 ** is possible to add the page as a new free-list leaf. 6286 */ 6287 if( nFree!=0 ){ 6288 u32 nLeaf; /* Initial number of leaf cells on trunk page */ 6289 6290 iTrunk = get4byte(&pPage1->aData[32]); 6291 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); 6292 if( rc!=SQLITE_OK ){ 6293 goto freepage_out; 6294 } 6295 6296 nLeaf = get4byte(&pTrunk->aData[4]); 6297 assert( pBt->usableSize>32 ); 6298 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ 6299 rc = SQLITE_CORRUPT_BKPT; 6300 goto freepage_out; 6301 } 6302 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ 6303 /* In this case there is room on the trunk page to insert the page 6304 ** being freed as a new leaf. 6305 ** 6306 ** Note that the trunk page is not really full until it contains 6307 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have 6308 ** coded. But due to a coding error in versions of SQLite prior to 6309 ** 3.6.0, databases with freelist trunk pages holding more than 6310 ** usableSize/4 - 8 entries will be reported as corrupt. In order 6311 ** to maintain backwards compatibility with older versions of SQLite, 6312 ** we will continue to restrict the number of entries to usableSize/4 - 8 6313 ** for now. At some point in the future (once everyone has upgraded 6314 ** to 3.6.0 or later) we should consider fixing the conditional above 6315 ** to read "usableSize/4-2" instead of "usableSize/4-8". 6316 ** 6317 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still 6318 ** avoid using the last six entries in the freelist trunk page array in 6319 ** order that database files created by newer versions of SQLite can be 6320 ** read by older versions of SQLite. 6321 */ 6322 rc = sqlite3PagerWrite(pTrunk->pDbPage); 6323 if( rc==SQLITE_OK ){ 6324 put4byte(&pTrunk->aData[4], nLeaf+1); 6325 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); 6326 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ 6327 sqlite3PagerDontWrite(pPage->pDbPage); 6328 } 6329 rc = btreeSetHasContent(pBt, iPage); 6330 } 6331 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); 6332 goto freepage_out; 6333 } 6334 } 6335 6336 /* If control flows to this point, then it was not possible to add the 6337 ** the page being freed as a leaf page of the first trunk in the free-list. 6338 ** Possibly because the free-list is empty, or possibly because the 6339 ** first trunk in the free-list is full. Either way, the page being freed 6340 ** will become the new first trunk page in the free-list. 6341 */ 6342 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ 6343 goto freepage_out; 6344 } 6345 rc = sqlite3PagerWrite(pPage->pDbPage); 6346 if( rc!=SQLITE_OK ){ 6347 goto freepage_out; 6348 } 6349 put4byte(pPage->aData, iTrunk); 6350 put4byte(&pPage->aData[4], 0); 6351 put4byte(&pPage1->aData[32], iPage); 6352 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); 6353 6354 freepage_out: 6355 if( pPage ){ 6356 pPage->isInit = 0; 6357 } 6358 releasePage(pPage); 6359 releasePage(pTrunk); 6360 return rc; 6361 } 6362 static void freePage(MemPage *pPage, int *pRC){ 6363 if( (*pRC)==SQLITE_OK ){ 6364 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); 6365 } 6366 } 6367 6368 /* 6369 ** Free any overflow pages associated with the given Cell. Store 6370 ** size information about the cell in pInfo. 6371 */ 6372 static int clearCell( 6373 MemPage *pPage, /* The page that contains the Cell */ 6374 unsigned char *pCell, /* First byte of the Cell */ 6375 CellInfo *pInfo /* Size information about the cell */ 6376 ){ 6377 BtShared *pBt; 6378 Pgno ovflPgno; 6379 int rc; 6380 int nOvfl; 6381 u32 ovflPageSize; 6382 6383 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6384 pPage->xParseCell(pPage, pCell, pInfo); 6385 if( pInfo->nLocal==pInfo->nPayload ){ 6386 return SQLITE_OK; /* No overflow pages. Return without doing anything */ 6387 } 6388 testcase( pCell + pInfo->nSize == pPage->aDataEnd ); 6389 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd ); 6390 if( pCell + pInfo->nSize > pPage->aDataEnd ){ 6391 /* Cell extends past end of page */ 6392 return SQLITE_CORRUPT_PAGE(pPage); 6393 } 6394 ovflPgno = get4byte(pCell + pInfo->nSize - 4); 6395 pBt = pPage->pBt; 6396 assert( pBt->usableSize > 4 ); 6397 ovflPageSize = pBt->usableSize - 4; 6398 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; 6399 assert( nOvfl>0 || 6400 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize) 6401 ); 6402 while( nOvfl-- ){ 6403 Pgno iNext = 0; 6404 MemPage *pOvfl = 0; 6405 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ 6406 /* 0 is not a legal page number and page 1 cannot be an 6407 ** overflow page. Therefore if ovflPgno<2 or past the end of the 6408 ** file the database must be corrupt. */ 6409 return SQLITE_CORRUPT_BKPT; 6410 } 6411 if( nOvfl ){ 6412 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); 6413 if( rc ) return rc; 6414 } 6415 6416 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) 6417 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 6418 ){ 6419 /* There is no reason any cursor should have an outstanding reference 6420 ** to an overflow page belonging to a cell that is being deleted/updated. 6421 ** So if there exists more than one reference to this page, then it 6422 ** must not really be an overflow page and the database must be corrupt. 6423 ** It is helpful to detect this before calling freePage2(), as 6424 ** freePage2() may zero the page contents if secure-delete mode is 6425 ** enabled. If this 'overflow' page happens to be a page that the 6426 ** caller is iterating through or using in some other way, this 6427 ** can be problematic. 6428 */ 6429 rc = SQLITE_CORRUPT_BKPT; 6430 }else{ 6431 rc = freePage2(pBt, pOvfl, ovflPgno); 6432 } 6433 6434 if( pOvfl ){ 6435 sqlite3PagerUnref(pOvfl->pDbPage); 6436 } 6437 if( rc ) return rc; 6438 ovflPgno = iNext; 6439 } 6440 return SQLITE_OK; 6441 } 6442 6443 /* 6444 ** Create the byte sequence used to represent a cell on page pPage 6445 ** and write that byte sequence into pCell[]. Overflow pages are 6446 ** allocated and filled in as necessary. The calling procedure 6447 ** is responsible for making sure sufficient space has been allocated 6448 ** for pCell[]. 6449 ** 6450 ** Note that pCell does not necessary need to point to the pPage->aData 6451 ** area. pCell might point to some temporary storage. The cell will 6452 ** be constructed in this temporary area then copied into pPage->aData 6453 ** later. 6454 */ 6455 static int fillInCell( 6456 MemPage *pPage, /* The page that contains the cell */ 6457 unsigned char *pCell, /* Complete text of the cell */ 6458 const BtreePayload *pX, /* Payload with which to construct the cell */ 6459 int *pnSize /* Write cell size here */ 6460 ){ 6461 int nPayload; 6462 const u8 *pSrc; 6463 int nSrc, n, rc, mn; 6464 int spaceLeft; 6465 MemPage *pToRelease; 6466 unsigned char *pPrior; 6467 unsigned char *pPayload; 6468 BtShared *pBt; 6469 Pgno pgnoOvfl; 6470 int nHeader; 6471 6472 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6473 6474 /* pPage is not necessarily writeable since pCell might be auxiliary 6475 ** buffer space that is separate from the pPage buffer area */ 6476 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize] 6477 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6478 6479 /* Fill in the header. */ 6480 nHeader = pPage->childPtrSize; 6481 if( pPage->intKey ){ 6482 nPayload = pX->nData + pX->nZero; 6483 pSrc = pX->pData; 6484 nSrc = pX->nData; 6485 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ 6486 nHeader += putVarint32(&pCell[nHeader], nPayload); 6487 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); 6488 }else{ 6489 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); 6490 nSrc = nPayload = (int)pX->nKey; 6491 pSrc = pX->pKey; 6492 nHeader += putVarint32(&pCell[nHeader], nPayload); 6493 } 6494 6495 /* Fill in the payload */ 6496 pPayload = &pCell[nHeader]; 6497 if( nPayload<=pPage->maxLocal ){ 6498 /* This is the common case where everything fits on the btree page 6499 ** and no overflow pages are required. */ 6500 n = nHeader + nPayload; 6501 testcase( n==3 ); 6502 testcase( n==4 ); 6503 if( n<4 ) n = 4; 6504 *pnSize = n; 6505 assert( nSrc<=nPayload ); 6506 testcase( nSrc<nPayload ); 6507 memcpy(pPayload, pSrc, nSrc); 6508 memset(pPayload+nSrc, 0, nPayload-nSrc); 6509 return SQLITE_OK; 6510 } 6511 6512 /* If we reach this point, it means that some of the content will need 6513 ** to spill onto overflow pages. 6514 */ 6515 mn = pPage->minLocal; 6516 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); 6517 testcase( n==pPage->maxLocal ); 6518 testcase( n==pPage->maxLocal+1 ); 6519 if( n > pPage->maxLocal ) n = mn; 6520 spaceLeft = n; 6521 *pnSize = n + nHeader + 4; 6522 pPrior = &pCell[nHeader+n]; 6523 pToRelease = 0; 6524 pgnoOvfl = 0; 6525 pBt = pPage->pBt; 6526 6527 /* At this point variables should be set as follows: 6528 ** 6529 ** nPayload Total payload size in bytes 6530 ** pPayload Begin writing payload here 6531 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, 6532 ** that means content must spill into overflow pages. 6533 ** *pnSize Size of the local cell (not counting overflow pages) 6534 ** pPrior Where to write the pgno of the first overflow page 6535 ** 6536 ** Use a call to btreeParseCellPtr() to verify that the values above 6537 ** were computed correctly. 6538 */ 6539 #ifdef SQLITE_DEBUG 6540 { 6541 CellInfo info; 6542 pPage->xParseCell(pPage, pCell, &info); 6543 assert( nHeader==(int)(info.pPayload - pCell) ); 6544 assert( info.nKey==pX->nKey ); 6545 assert( *pnSize == info.nSize ); 6546 assert( spaceLeft == info.nLocal ); 6547 } 6548 #endif 6549 6550 /* Write the payload into the local Cell and any extra into overflow pages */ 6551 while( 1 ){ 6552 n = nPayload; 6553 if( n>spaceLeft ) n = spaceLeft; 6554 6555 /* If pToRelease is not zero than pPayload points into the data area 6556 ** of pToRelease. Make sure pToRelease is still writeable. */ 6557 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6558 6559 /* If pPayload is part of the data area of pPage, then make sure pPage 6560 ** is still writeable */ 6561 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] 6562 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6563 6564 if( nSrc>=n ){ 6565 memcpy(pPayload, pSrc, n); 6566 }else if( nSrc>0 ){ 6567 n = nSrc; 6568 memcpy(pPayload, pSrc, n); 6569 }else{ 6570 memset(pPayload, 0, n); 6571 } 6572 nPayload -= n; 6573 if( nPayload<=0 ) break; 6574 pPayload += n; 6575 pSrc += n; 6576 nSrc -= n; 6577 spaceLeft -= n; 6578 if( spaceLeft==0 ){ 6579 MemPage *pOvfl = 0; 6580 #ifndef SQLITE_OMIT_AUTOVACUUM 6581 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ 6582 if( pBt->autoVacuum ){ 6583 do{ 6584 pgnoOvfl++; 6585 } while( 6586 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 6587 ); 6588 } 6589 #endif 6590 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); 6591 #ifndef SQLITE_OMIT_AUTOVACUUM 6592 /* If the database supports auto-vacuum, and the second or subsequent 6593 ** overflow page is being allocated, add an entry to the pointer-map 6594 ** for that page now. 6595 ** 6596 ** If this is the first overflow page, then write a partial entry 6597 ** to the pointer-map. If we write nothing to this pointer-map slot, 6598 ** then the optimistic overflow chain processing in clearCell() 6599 ** may misinterpret the uninitialized values and delete the 6600 ** wrong pages from the database. 6601 */ 6602 if( pBt->autoVacuum && rc==SQLITE_OK ){ 6603 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); 6604 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); 6605 if( rc ){ 6606 releasePage(pOvfl); 6607 } 6608 } 6609 #endif 6610 if( rc ){ 6611 releasePage(pToRelease); 6612 return rc; 6613 } 6614 6615 /* If pToRelease is not zero than pPrior points into the data area 6616 ** of pToRelease. Make sure pToRelease is still writeable. */ 6617 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); 6618 6619 /* If pPrior is part of the data area of pPage, then make sure pPage 6620 ** is still writeable */ 6621 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize] 6622 || sqlite3PagerIswriteable(pPage->pDbPage) ); 6623 6624 put4byte(pPrior, pgnoOvfl); 6625 releasePage(pToRelease); 6626 pToRelease = pOvfl; 6627 pPrior = pOvfl->aData; 6628 put4byte(pPrior, 0); 6629 pPayload = &pOvfl->aData[4]; 6630 spaceLeft = pBt->usableSize - 4; 6631 } 6632 } 6633 releasePage(pToRelease); 6634 return SQLITE_OK; 6635 } 6636 6637 /* 6638 ** Remove the i-th cell from pPage. This routine effects pPage only. 6639 ** The cell content is not freed or deallocated. It is assumed that 6640 ** the cell content has been copied someplace else. This routine just 6641 ** removes the reference to the cell from pPage. 6642 ** 6643 ** "sz" must be the number of bytes in the cell. 6644 */ 6645 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ 6646 u32 pc; /* Offset to cell content of cell being deleted */ 6647 u8 *data; /* pPage->aData */ 6648 u8 *ptr; /* Used to move bytes around within data[] */ 6649 int rc; /* The return code */ 6650 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ 6651 6652 if( *pRC ) return; 6653 assert( idx>=0 && idx<pPage->nCell ); 6654 assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); 6655 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6656 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6657 assert( pPage->nFree>=0 ); 6658 data = pPage->aData; 6659 ptr = &pPage->aCellIdx[2*idx]; 6660 pc = get2byte(ptr); 6661 hdr = pPage->hdrOffset; 6662 testcase( pc==get2byte(&data[hdr+5]) ); 6663 testcase( pc+sz==pPage->pBt->usableSize ); 6664 if( pc+sz > pPage->pBt->usableSize ){ 6665 *pRC = SQLITE_CORRUPT_BKPT; 6666 return; 6667 } 6668 rc = freeSpace(pPage, pc, sz); 6669 if( rc ){ 6670 *pRC = rc; 6671 return; 6672 } 6673 pPage->nCell--; 6674 if( pPage->nCell==0 ){ 6675 memset(&data[hdr+1], 0, 4); 6676 data[hdr+7] = 0; 6677 put2byte(&data[hdr+5], pPage->pBt->usableSize); 6678 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset 6679 - pPage->childPtrSize - 8; 6680 }else{ 6681 memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); 6682 put2byte(&data[hdr+3], pPage->nCell); 6683 pPage->nFree += 2; 6684 } 6685 } 6686 6687 /* 6688 ** Insert a new cell on pPage at cell index "i". pCell points to the 6689 ** content of the cell. 6690 ** 6691 ** If the cell content will fit on the page, then put it there. If it 6692 ** will not fit, then make a copy of the cell content into pTemp if 6693 ** pTemp is not null. Regardless of pTemp, allocate a new entry 6694 ** in pPage->apOvfl[] and make it point to the cell content (either 6695 ** in pTemp or the original pCell) and also record its index. 6696 ** Allocating a new entry in pPage->aCell[] implies that 6697 ** pPage->nOverflow is incremented. 6698 ** 6699 ** *pRC must be SQLITE_OK when this routine is called. 6700 */ 6701 static void insertCell( 6702 MemPage *pPage, /* Page into which we are copying */ 6703 int i, /* New cell becomes the i-th cell of the page */ 6704 u8 *pCell, /* Content of the new cell */ 6705 int sz, /* Bytes of content in pCell */ 6706 u8 *pTemp, /* Temp storage space for pCell, if needed */ 6707 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ 6708 int *pRC /* Read and write return code from here */ 6709 ){ 6710 int idx = 0; /* Where to write new cell content in data[] */ 6711 int j; /* Loop counter */ 6712 u8 *data; /* The content of the whole page */ 6713 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ 6714 6715 assert( *pRC==SQLITE_OK ); 6716 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); 6717 assert( MX_CELL(pPage->pBt)<=10921 ); 6718 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); 6719 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); 6720 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); 6721 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 6722 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB ); 6723 assert( pPage->nFree>=0 ); 6724 if( pPage->nOverflow || sz+2>pPage->nFree ){ 6725 if( pTemp ){ 6726 memcpy(pTemp, pCell, sz); 6727 pCell = pTemp; 6728 } 6729 if( iChild ){ 6730 put4byte(pCell, iChild); 6731 } 6732 j = pPage->nOverflow++; 6733 /* Comparison against ArraySize-1 since we hold back one extra slot 6734 ** as a contingency. In other words, never need more than 3 overflow 6735 ** slots but 4 are allocated, just to be safe. */ 6736 assert( j < ArraySize(pPage->apOvfl)-1 ); 6737 pPage->apOvfl[j] = pCell; 6738 pPage->aiOvfl[j] = (u16)i; 6739 6740 /* When multiple overflows occur, they are always sequential and in 6741 ** sorted order. This invariants arise because multiple overflows can 6742 ** only occur when inserting divider cells into the parent page during 6743 ** balancing, and the dividers are adjacent and sorted. 6744 */ 6745 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ 6746 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ 6747 }else{ 6748 int rc = sqlite3PagerWrite(pPage->pDbPage); 6749 if( rc!=SQLITE_OK ){ 6750 *pRC = rc; 6751 return; 6752 } 6753 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 6754 data = pPage->aData; 6755 assert( &data[pPage->cellOffset]==pPage->aCellIdx ); 6756 rc = allocateSpace(pPage, sz, &idx); 6757 if( rc ){ *pRC = rc; return; } 6758 /* The allocateSpace() routine guarantees the following properties 6759 ** if it returns successfully */ 6760 assert( idx >= 0 ); 6761 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); 6762 assert( idx+sz <= (int)pPage->pBt->usableSize ); 6763 pPage->nFree -= (u16)(2 + sz); 6764 if( iChild ){ 6765 /* In a corrupt database where an entry in the cell index section of 6766 ** a btree page has a value of 3 or less, the pCell value might point 6767 ** as many as 4 bytes in front of the start of the aData buffer for 6768 ** the source page. Make sure this does not cause problems by not 6769 ** reading the first 4 bytes */ 6770 memcpy(&data[idx+4], pCell+4, sz-4); 6771 put4byte(&data[idx], iChild); 6772 }else{ 6773 memcpy(&data[idx], pCell, sz); 6774 } 6775 pIns = pPage->aCellIdx + i*2; 6776 memmove(pIns+2, pIns, 2*(pPage->nCell - i)); 6777 put2byte(pIns, idx); 6778 pPage->nCell++; 6779 /* increment the cell count */ 6780 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; 6781 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB ); 6782 #ifndef SQLITE_OMIT_AUTOVACUUM 6783 if( pPage->pBt->autoVacuum ){ 6784 /* The cell may contain a pointer to an overflow page. If so, write 6785 ** the entry for the overflow page into the pointer map. 6786 */ 6787 ptrmapPutOvflPtr(pPage, pPage, pCell, pRC); 6788 } 6789 #endif 6790 } 6791 } 6792 6793 /* 6794 ** The following parameters determine how many adjacent pages get involved 6795 ** in a balancing operation. NN is the number of neighbors on either side 6796 ** of the page that participate in the balancing operation. NB is the 6797 ** total number of pages that participate, including the target page and 6798 ** NN neighbors on either side. 6799 ** 6800 ** The minimum value of NN is 1 (of course). Increasing NN above 1 6801 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance 6802 ** in exchange for a larger degradation in INSERT and UPDATE performance. 6803 ** The value of NN appears to give the best results overall. 6804 ** 6805 ** (Later:) The description above makes it seem as if these values are 6806 ** tunable - as if you could change them and recompile and it would all work. 6807 ** But that is unlikely. NB has been 3 since the inception of SQLite and 6808 ** we have never tested any other value. 6809 */ 6810 #define NN 1 /* Number of neighbors on either side of pPage */ 6811 #define NB 3 /* (NN*2+1): Total pages involved in the balance */ 6812 6813 /* 6814 ** A CellArray object contains a cache of pointers and sizes for a 6815 ** consecutive sequence of cells that might be held on multiple pages. 6816 ** 6817 ** The cells in this array are the divider cell or cells from the pParent 6818 ** page plus up to three child pages. There are a total of nCell cells. 6819 ** 6820 ** pRef is a pointer to one of the pages that contributes cells. This is 6821 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize 6822 ** which should be common to all pages that contribute cells to this array. 6823 ** 6824 ** apCell[] and szCell[] hold, respectively, pointers to the start of each 6825 ** cell and the size of each cell. Some of the apCell[] pointers might refer 6826 ** to overflow cells. In other words, some apCel[] pointers might not point 6827 ** to content area of the pages. 6828 ** 6829 ** A szCell[] of zero means the size of that cell has not yet been computed. 6830 ** 6831 ** The cells come from as many as four different pages: 6832 ** 6833 ** ----------- 6834 ** | Parent | 6835 ** ----------- 6836 ** / | \ 6837 ** / | \ 6838 ** --------- --------- --------- 6839 ** |Child-1| |Child-2| |Child-3| 6840 ** --------- --------- --------- 6841 ** 6842 ** The order of cells is in the array is for an index btree is: 6843 ** 6844 ** 1. All cells from Child-1 in order 6845 ** 2. The first divider cell from Parent 6846 ** 3. All cells from Child-2 in order 6847 ** 4. The second divider cell from Parent 6848 ** 5. All cells from Child-3 in order 6849 ** 6850 ** For a table-btree (with rowids) the items 2 and 4 are empty because 6851 ** content exists only in leaves and there are no divider cells. 6852 ** 6853 ** For an index btree, the apEnd[] array holds pointer to the end of page 6854 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3, 6855 ** respectively. The ixNx[] array holds the number of cells contained in 6856 ** each of these 5 stages, and all stages to the left. Hence: 6857 ** 6858 ** ixNx[0] = Number of cells in Child-1. 6859 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider. 6860 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider. 6861 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells 6862 ** ixNx[4] = Total number of cells. 6863 ** 6864 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2] 6865 ** are used and they point to the leaf pages only, and the ixNx value are: 6866 ** 6867 ** ixNx[0] = Number of cells in Child-1. 6868 ** ixNx[1] = Number of cells in Child-1 and Child-2. 6869 ** ixNx[2] = Total number of cells. 6870 ** 6871 ** Sometimes when deleting, a child page can have zero cells. In those 6872 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[] 6873 ** entries, shift down. The end result is that each ixNx[] entry should 6874 ** be larger than the previous 6875 */ 6876 typedef struct CellArray CellArray; 6877 struct CellArray { 6878 int nCell; /* Number of cells in apCell[] */ 6879 MemPage *pRef; /* Reference page */ 6880 u8 **apCell; /* All cells begin balanced */ 6881 u16 *szCell; /* Local size of all cells in apCell[] */ 6882 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */ 6883 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */ 6884 }; 6885 6886 /* 6887 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been 6888 ** computed. 6889 */ 6890 static void populateCellCache(CellArray *p, int idx, int N){ 6891 assert( idx>=0 && idx+N<=p->nCell ); 6892 while( N>0 ){ 6893 assert( p->apCell[idx]!=0 ); 6894 if( p->szCell[idx]==0 ){ 6895 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); 6896 }else{ 6897 assert( CORRUPT_DB || 6898 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); 6899 } 6900 idx++; 6901 N--; 6902 } 6903 } 6904 6905 /* 6906 ** Return the size of the Nth element of the cell array 6907 */ 6908 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ 6909 assert( N>=0 && N<p->nCell ); 6910 assert( p->szCell[N]==0 ); 6911 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); 6912 return p->szCell[N]; 6913 } 6914 static u16 cachedCellSize(CellArray *p, int N){ 6915 assert( N>=0 && N<p->nCell ); 6916 if( p->szCell[N] ) return p->szCell[N]; 6917 return computeCellSize(p, N); 6918 } 6919 6920 /* 6921 ** Array apCell[] contains pointers to nCell b-tree page cells. The 6922 ** szCell[] array contains the size in bytes of each cell. This function 6923 ** replaces the current contents of page pPg with the contents of the cell 6924 ** array. 6925 ** 6926 ** Some of the cells in apCell[] may currently be stored in pPg. This 6927 ** function works around problems caused by this by making a copy of any 6928 ** such cells before overwriting the page data. 6929 ** 6930 ** The MemPage.nFree field is invalidated by this function. It is the 6931 ** responsibility of the caller to set it correctly. 6932 */ 6933 static int rebuildPage( 6934 CellArray *pCArray, /* Content to be added to page pPg */ 6935 int iFirst, /* First cell in pCArray to use */ 6936 int nCell, /* Final number of cells on page */ 6937 MemPage *pPg /* The page to be reconstructed */ 6938 ){ 6939 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ 6940 u8 * const aData = pPg->aData; /* Pointer to data for pPg */ 6941 const int usableSize = pPg->pBt->usableSize; 6942 u8 * const pEnd = &aData[usableSize]; 6943 int i = iFirst; /* Which cell to copy from pCArray*/ 6944 u32 j; /* Start of cell content area */ 6945 int iEnd = i+nCell; /* Loop terminator */ 6946 u8 *pCellptr = pPg->aCellIdx; 6947 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 6948 u8 *pData; 6949 int k; /* Current slot in pCArray->apEnd[] */ 6950 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */ 6951 6952 assert( i<iEnd ); 6953 j = get2byte(&aData[hdr+5]); 6954 if( NEVER(j>(u32)usableSize) ){ j = 0; } 6955 memcpy(&pTmp[j], &aData[j], usableSize - j); 6956 6957 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} 6958 pSrcEnd = pCArray->apEnd[k]; 6959 6960 pData = pEnd; 6961 while( 1/*exit by break*/ ){ 6962 u8 *pCell = pCArray->apCell[i]; 6963 u16 sz = pCArray->szCell[i]; 6964 assert( sz>0 ); 6965 if( SQLITE_WITHIN(pCell,aData,pEnd) ){ 6966 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT; 6967 pCell = &pTmp[pCell - aData]; 6968 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd 6969 && (uptr)(pCell)<(uptr)pSrcEnd 6970 ){ 6971 return SQLITE_CORRUPT_BKPT; 6972 } 6973 6974 pData -= sz; 6975 put2byte(pCellptr, (pData - aData)); 6976 pCellptr += 2; 6977 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; 6978 memcpy(pData, pCell, sz); 6979 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); 6980 testcase( sz!=pPg->xCellSize(pPg,pCell) ) 6981 i++; 6982 if( i>=iEnd ) break; 6983 if( pCArray->ixNx[k]<=i ){ 6984 k++; 6985 pSrcEnd = pCArray->apEnd[k]; 6986 } 6987 } 6988 6989 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ 6990 pPg->nCell = nCell; 6991 pPg->nOverflow = 0; 6992 6993 put2byte(&aData[hdr+1], 0); 6994 put2byte(&aData[hdr+3], pPg->nCell); 6995 put2byte(&aData[hdr+5], pData - aData); 6996 aData[hdr+7] = 0x00; 6997 return SQLITE_OK; 6998 } 6999 7000 /* 7001 ** The pCArray objects contains pointers to b-tree cells and the cell sizes. 7002 ** This function attempts to add the cells stored in the array to page pPg. 7003 ** If it cannot (because the page needs to be defragmented before the cells 7004 ** will fit), non-zero is returned. Otherwise, if the cells are added 7005 ** successfully, zero is returned. 7006 ** 7007 ** Argument pCellptr points to the first entry in the cell-pointer array 7008 ** (part of page pPg) to populate. After cell apCell[0] is written to the 7009 ** page body, a 16-bit offset is written to pCellptr. And so on, for each 7010 ** cell in the array. It is the responsibility of the caller to ensure 7011 ** that it is safe to overwrite this part of the cell-pointer array. 7012 ** 7013 ** When this function is called, *ppData points to the start of the 7014 ** content area on page pPg. If the size of the content area is extended, 7015 ** *ppData is updated to point to the new start of the content area 7016 ** before returning. 7017 ** 7018 ** Finally, argument pBegin points to the byte immediately following the 7019 ** end of the space required by this page for the cell-pointer area (for 7020 ** all cells - not just those inserted by the current call). If the content 7021 ** area must be extended to before this point in order to accomodate all 7022 ** cells in apCell[], then the cells do not fit and non-zero is returned. 7023 */ 7024 static int pageInsertArray( 7025 MemPage *pPg, /* Page to add cells to */ 7026 u8 *pBegin, /* End of cell-pointer array */ 7027 u8 **ppData, /* IN/OUT: Page content-area pointer */ 7028 u8 *pCellptr, /* Pointer to cell-pointer area */ 7029 int iFirst, /* Index of first cell to add */ 7030 int nCell, /* Number of cells to add to pPg */ 7031 CellArray *pCArray /* Array of cells */ 7032 ){ 7033 int i = iFirst; /* Loop counter - cell index to insert */ 7034 u8 *aData = pPg->aData; /* Complete page */ 7035 u8 *pData = *ppData; /* Content area. A subset of aData[] */ 7036 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */ 7037 int k; /* Current slot in pCArray->apEnd[] */ 7038 u8 *pEnd; /* Maximum extent of cell data */ 7039 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ 7040 if( iEnd<=iFirst ) return 0; 7041 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} 7042 pEnd = pCArray->apEnd[k]; 7043 while( 1 /*Exit by break*/ ){ 7044 int sz, rc; 7045 u8 *pSlot; 7046 assert( pCArray->szCell[i]!=0 ); 7047 sz = pCArray->szCell[i]; 7048 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ 7049 if( (pData - pBegin)<sz ) return 1; 7050 pData -= sz; 7051 pSlot = pData; 7052 } 7053 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed 7054 ** database. But they might for a corrupt database. Hence use memmove() 7055 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ 7056 assert( (pSlot+sz)<=pCArray->apCell[i] 7057 || pSlot>=(pCArray->apCell[i]+sz) 7058 || CORRUPT_DB ); 7059 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd 7060 && (uptr)(pCArray->apCell[i])<(uptr)pEnd 7061 ){ 7062 assert( CORRUPT_DB ); 7063 (void)SQLITE_CORRUPT_BKPT; 7064 return 1; 7065 } 7066 memmove(pSlot, pCArray->apCell[i], sz); 7067 put2byte(pCellptr, (pSlot - aData)); 7068 pCellptr += 2; 7069 i++; 7070 if( i>=iEnd ) break; 7071 if( pCArray->ixNx[k]<=i ){ 7072 k++; 7073 pEnd = pCArray->apEnd[k]; 7074 } 7075 } 7076 *ppData = pData; 7077 return 0; 7078 } 7079 7080 /* 7081 ** The pCArray object contains pointers to b-tree cells and their sizes. 7082 ** 7083 ** This function adds the space associated with each cell in the array 7084 ** that is currently stored within the body of pPg to the pPg free-list. 7085 ** The cell-pointers and other fields of the page are not updated. 7086 ** 7087 ** This function returns the total number of cells added to the free-list. 7088 */ 7089 static int pageFreeArray( 7090 MemPage *pPg, /* Page to edit */ 7091 int iFirst, /* First cell to delete */ 7092 int nCell, /* Cells to delete */ 7093 CellArray *pCArray /* Array of cells */ 7094 ){ 7095 u8 * const aData = pPg->aData; 7096 u8 * const pEnd = &aData[pPg->pBt->usableSize]; 7097 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; 7098 int nRet = 0; 7099 int i; 7100 int iEnd = iFirst + nCell; 7101 u8 *pFree = 0; 7102 int szFree = 0; 7103 7104 for(i=iFirst; i<iEnd; i++){ 7105 u8 *pCell = pCArray->apCell[i]; 7106 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){ 7107 int sz; 7108 /* No need to use cachedCellSize() here. The sizes of all cells that 7109 ** are to be freed have already been computing while deciding which 7110 ** cells need freeing */ 7111 sz = pCArray->szCell[i]; assert( sz>0 ); 7112 if( pFree!=(pCell + sz) ){ 7113 if( pFree ){ 7114 assert( pFree>aData && (pFree - aData)<65536 ); 7115 freeSpace(pPg, (u16)(pFree - aData), szFree); 7116 } 7117 pFree = pCell; 7118 szFree = sz; 7119 if( pFree+sz>pEnd ) return 0; 7120 }else{ 7121 pFree = pCell; 7122 szFree += sz; 7123 } 7124 nRet++; 7125 } 7126 } 7127 if( pFree ){ 7128 assert( pFree>aData && (pFree - aData)<65536 ); 7129 freeSpace(pPg, (u16)(pFree - aData), szFree); 7130 } 7131 return nRet; 7132 } 7133 7134 /* 7135 ** pCArray contains pointers to and sizes of all cells in the page being 7136 ** balanced. The current page, pPg, has pPg->nCell cells starting with 7137 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells 7138 ** starting at apCell[iNew]. 7139 ** 7140 ** This routine makes the necessary adjustments to pPg so that it contains 7141 ** the correct cells after being balanced. 7142 ** 7143 ** The pPg->nFree field is invalid when this function returns. It is the 7144 ** responsibility of the caller to set it correctly. 7145 */ 7146 static int editPage( 7147 MemPage *pPg, /* Edit this page */ 7148 int iOld, /* Index of first cell currently on page */ 7149 int iNew, /* Index of new first cell on page */ 7150 int nNew, /* Final number of cells on page */ 7151 CellArray *pCArray /* Array of cells and sizes */ 7152 ){ 7153 u8 * const aData = pPg->aData; 7154 const int hdr = pPg->hdrOffset; 7155 u8 *pBegin = &pPg->aCellIdx[nNew * 2]; 7156 int nCell = pPg->nCell; /* Cells stored on pPg */ 7157 u8 *pData; 7158 u8 *pCellptr; 7159 int i; 7160 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; 7161 int iNewEnd = iNew + nNew; 7162 7163 #ifdef SQLITE_DEBUG 7164 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); 7165 memcpy(pTmp, aData, pPg->pBt->usableSize); 7166 #endif 7167 7168 /* Remove cells from the start and end of the page */ 7169 assert( nCell>=0 ); 7170 if( iOld<iNew ){ 7171 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); 7172 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT; 7173 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); 7174 nCell -= nShift; 7175 } 7176 if( iNewEnd < iOldEnd ){ 7177 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); 7178 assert( nCell>=nTail ); 7179 nCell -= nTail; 7180 } 7181 7182 pData = &aData[get2byteNotZero(&aData[hdr+5])]; 7183 if( pData<pBegin ) goto editpage_fail; 7184 7185 /* Add cells to the start of the page */ 7186 if( iNew<iOld ){ 7187 int nAdd = MIN(nNew,iOld-iNew); 7188 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB ); 7189 assert( nAdd>=0 ); 7190 pCellptr = pPg->aCellIdx; 7191 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); 7192 if( pageInsertArray( 7193 pPg, pBegin, &pData, pCellptr, 7194 iNew, nAdd, pCArray 7195 ) ) goto editpage_fail; 7196 nCell += nAdd; 7197 } 7198 7199 /* Add any overflow cells */ 7200 for(i=0; i<pPg->nOverflow; i++){ 7201 int iCell = (iOld + pPg->aiOvfl[i]) - iNew; 7202 if( iCell>=0 && iCell<nNew ){ 7203 pCellptr = &pPg->aCellIdx[iCell * 2]; 7204 if( nCell>iCell ){ 7205 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); 7206 } 7207 nCell++; 7208 cachedCellSize(pCArray, iCell+iNew); 7209 if( pageInsertArray( 7210 pPg, pBegin, &pData, pCellptr, 7211 iCell+iNew, 1, pCArray 7212 ) ) goto editpage_fail; 7213 } 7214 } 7215 7216 /* Append cells to the end of the page */ 7217 assert( nCell>=0 ); 7218 pCellptr = &pPg->aCellIdx[nCell*2]; 7219 if( pageInsertArray( 7220 pPg, pBegin, &pData, pCellptr, 7221 iNew+nCell, nNew-nCell, pCArray 7222 ) ) goto editpage_fail; 7223 7224 pPg->nCell = nNew; 7225 pPg->nOverflow = 0; 7226 7227 put2byte(&aData[hdr+3], pPg->nCell); 7228 put2byte(&aData[hdr+5], pData - aData); 7229 7230 #ifdef SQLITE_DEBUG 7231 for(i=0; i<nNew && !CORRUPT_DB; i++){ 7232 u8 *pCell = pCArray->apCell[i+iNew]; 7233 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); 7234 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){ 7235 pCell = &pTmp[pCell - aData]; 7236 } 7237 assert( 0==memcmp(pCell, &aData[iOff], 7238 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); 7239 } 7240 #endif 7241 7242 return SQLITE_OK; 7243 editpage_fail: 7244 /* Unable to edit this page. Rebuild it from scratch instead. */ 7245 populateCellCache(pCArray, iNew, nNew); 7246 return rebuildPage(pCArray, iNew, nNew, pPg); 7247 } 7248 7249 7250 #ifndef SQLITE_OMIT_QUICKBALANCE 7251 /* 7252 ** This version of balance() handles the common special case where 7253 ** a new entry is being inserted on the extreme right-end of the 7254 ** tree, in other words, when the new entry will become the largest 7255 ** entry in the tree. 7256 ** 7257 ** Instead of trying to balance the 3 right-most leaf pages, just add 7258 ** a new page to the right-hand side and put the one new entry in 7259 ** that page. This leaves the right side of the tree somewhat 7260 ** unbalanced. But odds are that we will be inserting new entries 7261 ** at the end soon afterwards so the nearly empty page will quickly 7262 ** fill up. On average. 7263 ** 7264 ** pPage is the leaf page which is the right-most page in the tree. 7265 ** pParent is its parent. pPage must have a single overflow entry 7266 ** which is also the right-most entry on the page. 7267 ** 7268 ** The pSpace buffer is used to store a temporary copy of the divider 7269 ** cell that will be inserted into pParent. Such a cell consists of a 4 7270 ** byte page number followed by a variable length integer. In other 7271 ** words, at most 13 bytes. Hence the pSpace buffer must be at 7272 ** least 13 bytes in size. 7273 */ 7274 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ 7275 BtShared *const pBt = pPage->pBt; /* B-Tree Database */ 7276 MemPage *pNew; /* Newly allocated page */ 7277 int rc; /* Return Code */ 7278 Pgno pgnoNew; /* Page number of pNew */ 7279 7280 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 7281 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7282 assert( pPage->nOverflow==1 ); 7283 7284 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */ 7285 assert( pPage->nFree>=0 ); 7286 assert( pParent->nFree>=0 ); 7287 7288 /* Allocate a new page. This page will become the right-sibling of 7289 ** pPage. Make the parent page writable, so that the new divider cell 7290 ** may be inserted. If both these operations are successful, proceed. 7291 */ 7292 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); 7293 7294 if( rc==SQLITE_OK ){ 7295 7296 u8 *pOut = &pSpace[4]; 7297 u8 *pCell = pPage->apOvfl[0]; 7298 u16 szCell = pPage->xCellSize(pPage, pCell); 7299 u8 *pStop; 7300 CellArray b; 7301 7302 assert( sqlite3PagerIswriteable(pNew->pDbPage) ); 7303 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); 7304 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); 7305 b.nCell = 1; 7306 b.pRef = pPage; 7307 b.apCell = &pCell; 7308 b.szCell = &szCell; 7309 b.apEnd[0] = pPage->aDataEnd; 7310 b.ixNx[0] = 2; 7311 rc = rebuildPage(&b, 0, 1, pNew); 7312 if( NEVER(rc) ){ 7313 releasePage(pNew); 7314 return rc; 7315 } 7316 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; 7317 7318 /* If this is an auto-vacuum database, update the pointer map 7319 ** with entries for the new page, and any pointer from the 7320 ** cell on the page to an overflow page. If either of these 7321 ** operations fails, the return code is set, but the contents 7322 ** of the parent page are still manipulated by thh code below. 7323 ** That is Ok, at this point the parent page is guaranteed to 7324 ** be marked as dirty. Returning an error code will cause a 7325 ** rollback, undoing any changes made to the parent page. 7326 */ 7327 if( ISAUTOVACUUM ){ 7328 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); 7329 if( szCell>pNew->minLocal ){ 7330 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc); 7331 } 7332 } 7333 7334 /* Create a divider cell to insert into pParent. The divider cell 7335 ** consists of a 4-byte page number (the page number of pPage) and 7336 ** a variable length key value (which must be the same value as the 7337 ** largest key on pPage). 7338 ** 7339 ** To find the largest key value on pPage, first find the right-most 7340 ** cell on pPage. The first two fields of this cell are the 7341 ** record-length (a variable length integer at most 32-bits in size) 7342 ** and the key value (a variable length integer, may have any value). 7343 ** The first of the while(...) loops below skips over the record-length 7344 ** field. The second while(...) loop copies the key value from the 7345 ** cell on pPage into the pSpace buffer. 7346 */ 7347 pCell = findCell(pPage, pPage->nCell-1); 7348 pStop = &pCell[9]; 7349 while( (*(pCell++)&0x80) && pCell<pStop ); 7350 pStop = &pCell[9]; 7351 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop ); 7352 7353 /* Insert the new divider cell into pParent. */ 7354 if( rc==SQLITE_OK ){ 7355 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace), 7356 0, pPage->pgno, &rc); 7357 } 7358 7359 /* Set the right-child pointer of pParent to point to the new page. */ 7360 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); 7361 7362 /* Release the reference to the new page. */ 7363 releasePage(pNew); 7364 } 7365 7366 return rc; 7367 } 7368 #endif /* SQLITE_OMIT_QUICKBALANCE */ 7369 7370 #if 0 7371 /* 7372 ** This function does not contribute anything to the operation of SQLite. 7373 ** it is sometimes activated temporarily while debugging code responsible 7374 ** for setting pointer-map entries. 7375 */ 7376 static int ptrmapCheckPages(MemPage **apPage, int nPage){ 7377 int i, j; 7378 for(i=0; i<nPage; i++){ 7379 Pgno n; 7380 u8 e; 7381 MemPage *pPage = apPage[i]; 7382 BtShared *pBt = pPage->pBt; 7383 assert( pPage->isInit ); 7384 7385 for(j=0; j<pPage->nCell; j++){ 7386 CellInfo info; 7387 u8 *z; 7388 7389 z = findCell(pPage, j); 7390 pPage->xParseCell(pPage, z, &info); 7391 if( info.nLocal<info.nPayload ){ 7392 Pgno ovfl = get4byte(&z[info.nSize-4]); 7393 ptrmapGet(pBt, ovfl, &e, &n); 7394 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); 7395 } 7396 if( !pPage->leaf ){ 7397 Pgno child = get4byte(z); 7398 ptrmapGet(pBt, child, &e, &n); 7399 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 7400 } 7401 } 7402 if( !pPage->leaf ){ 7403 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); 7404 ptrmapGet(pBt, child, &e, &n); 7405 assert( n==pPage->pgno && e==PTRMAP_BTREE ); 7406 } 7407 } 7408 return 1; 7409 } 7410 #endif 7411 7412 /* 7413 ** This function is used to copy the contents of the b-tree node stored 7414 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then 7415 ** the pointer-map entries for each child page are updated so that the 7416 ** parent page stored in the pointer map is page pTo. If pFrom contained 7417 ** any cells with overflow page pointers, then the corresponding pointer 7418 ** map entries are also updated so that the parent page is page pTo. 7419 ** 7420 ** If pFrom is currently carrying any overflow cells (entries in the 7421 ** MemPage.apOvfl[] array), they are not copied to pTo. 7422 ** 7423 ** Before returning, page pTo is reinitialized using btreeInitPage(). 7424 ** 7425 ** The performance of this function is not critical. It is only used by 7426 ** the balance_shallower() and balance_deeper() procedures, neither of 7427 ** which are called often under normal circumstances. 7428 */ 7429 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ 7430 if( (*pRC)==SQLITE_OK ){ 7431 BtShared * const pBt = pFrom->pBt; 7432 u8 * const aFrom = pFrom->aData; 7433 u8 * const aTo = pTo->aData; 7434 int const iFromHdr = pFrom->hdrOffset; 7435 int const iToHdr = ((pTo->pgno==1) ? 100 : 0); 7436 int rc; 7437 int iData; 7438 7439 7440 assert( pFrom->isInit ); 7441 assert( pFrom->nFree>=iToHdr ); 7442 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); 7443 7444 /* Copy the b-tree node content from page pFrom to page pTo. */ 7445 iData = get2byte(&aFrom[iFromHdr+5]); 7446 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); 7447 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); 7448 7449 /* Reinitialize page pTo so that the contents of the MemPage structure 7450 ** match the new data. The initialization of pTo can actually fail under 7451 ** fairly obscure circumstances, even though it is a copy of initialized 7452 ** page pFrom. 7453 */ 7454 pTo->isInit = 0; 7455 rc = btreeInitPage(pTo); 7456 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo); 7457 if( rc!=SQLITE_OK ){ 7458 *pRC = rc; 7459 return; 7460 } 7461 7462 /* If this is an auto-vacuum database, update the pointer-map entries 7463 ** for any b-tree or overflow pages that pTo now contains the pointers to. 7464 */ 7465 if( ISAUTOVACUUM ){ 7466 *pRC = setChildPtrmaps(pTo); 7467 } 7468 } 7469 } 7470 7471 /* 7472 ** This routine redistributes cells on the iParentIdx'th child of pParent 7473 ** (hereafter "the page") and up to 2 siblings so that all pages have about the 7474 ** same amount of free space. Usually a single sibling on either side of the 7475 ** page are used in the balancing, though both siblings might come from one 7476 ** side if the page is the first or last child of its parent. If the page 7477 ** has fewer than 2 siblings (something which can only happen if the page 7478 ** is a root page or a child of a root page) then all available siblings 7479 ** participate in the balancing. 7480 ** 7481 ** The number of siblings of the page might be increased or decreased by 7482 ** one or two in an effort to keep pages nearly full but not over full. 7483 ** 7484 ** Note that when this routine is called, some of the cells on the page 7485 ** might not actually be stored in MemPage.aData[]. This can happen 7486 ** if the page is overfull. This routine ensures that all cells allocated 7487 ** to the page and its siblings fit into MemPage.aData[] before returning. 7488 ** 7489 ** In the course of balancing the page and its siblings, cells may be 7490 ** inserted into or removed from the parent page (pParent). Doing so 7491 ** may cause the parent page to become overfull or underfull. If this 7492 ** happens, it is the responsibility of the caller to invoke the correct 7493 ** balancing routine to fix this problem (see the balance() routine). 7494 ** 7495 ** If this routine fails for any reason, it might leave the database 7496 ** in a corrupted state. So if this routine fails, the database should 7497 ** be rolled back. 7498 ** 7499 ** The third argument to this function, aOvflSpace, is a pointer to a 7500 ** buffer big enough to hold one page. If while inserting cells into the parent 7501 ** page (pParent) the parent page becomes overfull, this buffer is 7502 ** used to store the parent's overflow cells. Because this function inserts 7503 ** a maximum of four divider cells into the parent page, and the maximum 7504 ** size of a cell stored within an internal node is always less than 1/4 7505 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large 7506 ** enough for all overflow cells. 7507 ** 7508 ** If aOvflSpace is set to a null pointer, this function returns 7509 ** SQLITE_NOMEM. 7510 */ 7511 static int balance_nonroot( 7512 MemPage *pParent, /* Parent page of siblings being balanced */ 7513 int iParentIdx, /* Index of "the page" in pParent */ 7514 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ 7515 int isRoot, /* True if pParent is a root-page */ 7516 int bBulk /* True if this call is part of a bulk load */ 7517 ){ 7518 BtShared *pBt; /* The whole database */ 7519 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ 7520 int nNew = 0; /* Number of pages in apNew[] */ 7521 int nOld; /* Number of pages in apOld[] */ 7522 int i, j, k; /* Loop counters */ 7523 int nxDiv; /* Next divider slot in pParent->aCell[] */ 7524 int rc = SQLITE_OK; /* The return code */ 7525 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ 7526 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ 7527 int usableSpace; /* Bytes in pPage beyond the header */ 7528 int pageFlags; /* Value of pPage->aData[0] */ 7529 int iSpace1 = 0; /* First unused byte of aSpace1[] */ 7530 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ 7531 int szScratch; /* Size of scratch memory requested */ 7532 MemPage *apOld[NB]; /* pPage and up to two siblings */ 7533 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ 7534 u8 *pRight; /* Location in parent of right-sibling pointer */ 7535 u8 *apDiv[NB-1]; /* Divider cells in pParent */ 7536 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ 7537 int cntOld[NB+2]; /* Old index in b.apCell[] */ 7538 int szNew[NB+2]; /* Combined size of cells placed on i-th page */ 7539 u8 *aSpace1; /* Space for copies of dividers cells */ 7540 Pgno pgno; /* Temp var to store a page number in */ 7541 u8 abDone[NB+2]; /* True after i'th new page is populated */ 7542 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ 7543 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ 7544 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ 7545 CellArray b; /* Parsed information on cells being balanced */ 7546 7547 memset(abDone, 0, sizeof(abDone)); 7548 b.nCell = 0; 7549 b.apCell = 0; 7550 pBt = pParent->pBt; 7551 assert( sqlite3_mutex_held(pBt->mutex) ); 7552 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 7553 7554 /* At this point pParent may have at most one overflow cell. And if 7555 ** this overflow cell is present, it must be the cell with 7556 ** index iParentIdx. This scenario comes about when this function 7557 ** is called (indirectly) from sqlite3BtreeDelete(). 7558 */ 7559 assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); 7560 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); 7561 7562 if( !aOvflSpace ){ 7563 return SQLITE_NOMEM_BKPT; 7564 } 7565 assert( pParent->nFree>=0 ); 7566 7567 /* Find the sibling pages to balance. Also locate the cells in pParent 7568 ** that divide the siblings. An attempt is made to find NN siblings on 7569 ** either side of pPage. More siblings are taken from one side, however, 7570 ** if there are fewer than NN siblings on the other side. If pParent 7571 ** has NB or fewer children then all children of pParent are taken. 7572 ** 7573 ** This loop also drops the divider cells from the parent page. This 7574 ** way, the remainder of the function does not have to deal with any 7575 ** overflow cells in the parent page, since if any existed they will 7576 ** have already been removed. 7577 */ 7578 i = pParent->nOverflow + pParent->nCell; 7579 if( i<2 ){ 7580 nxDiv = 0; 7581 }else{ 7582 assert( bBulk==0 || bBulk==1 ); 7583 if( iParentIdx==0 ){ 7584 nxDiv = 0; 7585 }else if( iParentIdx==i ){ 7586 nxDiv = i-2+bBulk; 7587 }else{ 7588 nxDiv = iParentIdx-1; 7589 } 7590 i = 2-bBulk; 7591 } 7592 nOld = i+1; 7593 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ 7594 pRight = &pParent->aData[pParent->hdrOffset+8]; 7595 }else{ 7596 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); 7597 } 7598 pgno = get4byte(pRight); 7599 while( 1 ){ 7600 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); 7601 if( rc ){ 7602 memset(apOld, 0, (i+1)*sizeof(MemPage*)); 7603 goto balance_cleanup; 7604 } 7605 if( apOld[i]->nFree<0 ){ 7606 rc = btreeComputeFreeSpace(apOld[i]); 7607 if( rc ){ 7608 memset(apOld, 0, (i)*sizeof(MemPage*)); 7609 goto balance_cleanup; 7610 } 7611 } 7612 if( (i--)==0 ) break; 7613 7614 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ 7615 apDiv[i] = pParent->apOvfl[0]; 7616 pgno = get4byte(apDiv[i]); 7617 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7618 pParent->nOverflow = 0; 7619 }else{ 7620 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); 7621 pgno = get4byte(apDiv[i]); 7622 szNew[i] = pParent->xCellSize(pParent, apDiv[i]); 7623 7624 /* Drop the cell from the parent page. apDiv[i] still points to 7625 ** the cell within the parent, even though it has been dropped. 7626 ** This is safe because dropping a cell only overwrites the first 7627 ** four bytes of it, and this function does not need the first 7628 ** four bytes of the divider cell. So the pointer is safe to use 7629 ** later on. 7630 ** 7631 ** But not if we are in secure-delete mode. In secure-delete mode, 7632 ** the dropCell() routine will overwrite the entire cell with zeroes. 7633 ** In this case, temporarily copy the cell into the aOvflSpace[] 7634 ** buffer. It will be copied out again as soon as the aSpace[] buffer 7635 ** is allocated. */ 7636 if( pBt->btsFlags & BTS_FAST_SECURE ){ 7637 int iOff; 7638 7639 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); 7640 if( (iOff+szNew[i])>(int)pBt->usableSize ){ 7641 rc = SQLITE_CORRUPT_BKPT; 7642 memset(apOld, 0, (i+1)*sizeof(MemPage*)); 7643 goto balance_cleanup; 7644 }else{ 7645 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); 7646 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; 7647 } 7648 } 7649 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); 7650 } 7651 } 7652 7653 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte 7654 ** alignment */ 7655 nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl)); 7656 nMaxCells = (nMaxCells + 3)&~3; 7657 7658 /* 7659 ** Allocate space for memory structures 7660 */ 7661 szScratch = 7662 nMaxCells*sizeof(u8*) /* b.apCell */ 7663 + nMaxCells*sizeof(u16) /* b.szCell */ 7664 + pBt->pageSize; /* aSpace1 */ 7665 7666 assert( szScratch<=7*(int)pBt->pageSize ); 7667 b.apCell = sqlite3StackAllocRaw(0, szScratch ); 7668 if( b.apCell==0 ){ 7669 rc = SQLITE_NOMEM_BKPT; 7670 goto balance_cleanup; 7671 } 7672 b.szCell = (u16*)&b.apCell[nMaxCells]; 7673 aSpace1 = (u8*)&b.szCell[nMaxCells]; 7674 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); 7675 7676 /* 7677 ** Load pointers to all cells on sibling pages and the divider cells 7678 ** into the local b.apCell[] array. Make copies of the divider cells 7679 ** into space obtained from aSpace1[]. The divider cells have already 7680 ** been removed from pParent. 7681 ** 7682 ** If the siblings are on leaf pages, then the child pointers of the 7683 ** divider cells are stripped from the cells before they are copied 7684 ** into aSpace1[]. In this way, all cells in b.apCell[] are without 7685 ** child pointers. If siblings are not leaves, then all cell in 7686 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] 7687 ** are alike. 7688 ** 7689 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. 7690 ** leafData: 1 if pPage holds key+data and pParent holds only keys. 7691 */ 7692 b.pRef = apOld[0]; 7693 leafCorrection = b.pRef->leaf*4; 7694 leafData = b.pRef->intKeyLeaf; 7695 for(i=0; i<nOld; i++){ 7696 MemPage *pOld = apOld[i]; 7697 int limit = pOld->nCell; 7698 u8 *aData = pOld->aData; 7699 u16 maskPage = pOld->maskPage; 7700 u8 *piCell = aData + pOld->cellOffset; 7701 u8 *piEnd; 7702 VVA_ONLY( int nCellAtStart = b.nCell; ) 7703 7704 /* Verify that all sibling pages are of the same "type" (table-leaf, 7705 ** table-interior, index-leaf, or index-interior). 7706 */ 7707 if( pOld->aData[0]!=apOld[0]->aData[0] ){ 7708 rc = SQLITE_CORRUPT_BKPT; 7709 goto balance_cleanup; 7710 } 7711 7712 /* Load b.apCell[] with pointers to all cells in pOld. If pOld 7713 ** contains overflow cells, include them in the b.apCell[] array 7714 ** in the correct spot. 7715 ** 7716 ** Note that when there are multiple overflow cells, it is always the 7717 ** case that they are sequential and adjacent. This invariant arises 7718 ** because multiple overflows can only occurs when inserting divider 7719 ** cells into a parent on a prior balance, and divider cells are always 7720 ** adjacent and are inserted in order. There is an assert() tagged 7721 ** with "NOTE 1" in the overflow cell insertion loop to prove this 7722 ** invariant. 7723 ** 7724 ** This must be done in advance. Once the balance starts, the cell 7725 ** offset section of the btree page will be overwritten and we will no 7726 ** long be able to find the cells if a pointer to each cell is not saved 7727 ** first. 7728 */ 7729 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); 7730 if( pOld->nOverflow>0 ){ 7731 if( NEVER(limit<pOld->aiOvfl[0]) ){ 7732 rc = SQLITE_CORRUPT_BKPT; 7733 goto balance_cleanup; 7734 } 7735 limit = pOld->aiOvfl[0]; 7736 for(j=0; j<limit; j++){ 7737 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7738 piCell += 2; 7739 b.nCell++; 7740 } 7741 for(k=0; k<pOld->nOverflow; k++){ 7742 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ 7743 b.apCell[b.nCell] = pOld->apOvfl[k]; 7744 b.nCell++; 7745 } 7746 } 7747 piEnd = aData + pOld->cellOffset + 2*pOld->nCell; 7748 while( piCell<piEnd ){ 7749 assert( b.nCell<nMaxCells ); 7750 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); 7751 piCell += 2; 7752 b.nCell++; 7753 } 7754 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) ); 7755 7756 cntOld[i] = b.nCell; 7757 if( i<nOld-1 && !leafData){ 7758 u16 sz = (u16)szNew[i]; 7759 u8 *pTemp; 7760 assert( b.nCell<nMaxCells ); 7761 b.szCell[b.nCell] = sz; 7762 pTemp = &aSpace1[iSpace1]; 7763 iSpace1 += sz; 7764 assert( sz<=pBt->maxLocal+23 ); 7765 assert( iSpace1 <= (int)pBt->pageSize ); 7766 memcpy(pTemp, apDiv[i], sz); 7767 b.apCell[b.nCell] = pTemp+leafCorrection; 7768 assert( leafCorrection==0 || leafCorrection==4 ); 7769 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; 7770 if( !pOld->leaf ){ 7771 assert( leafCorrection==0 ); 7772 assert( pOld->hdrOffset==0 ); 7773 /* The right pointer of the child page pOld becomes the left 7774 ** pointer of the divider cell */ 7775 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); 7776 }else{ 7777 assert( leafCorrection==4 ); 7778 while( b.szCell[b.nCell]<4 ){ 7779 /* Do not allow any cells smaller than 4 bytes. If a smaller cell 7780 ** does exist, pad it with 0x00 bytes. */ 7781 assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); 7782 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); 7783 aSpace1[iSpace1++] = 0x00; 7784 b.szCell[b.nCell]++; 7785 } 7786 } 7787 b.nCell++; 7788 } 7789 } 7790 7791 /* 7792 ** Figure out the number of pages needed to hold all b.nCell cells. 7793 ** Store this number in "k". Also compute szNew[] which is the total 7794 ** size of all cells on the i-th page and cntNew[] which is the index 7795 ** in b.apCell[] of the cell that divides page i from page i+1. 7796 ** cntNew[k] should equal b.nCell. 7797 ** 7798 ** Values computed by this block: 7799 ** 7800 ** k: The total number of sibling pages 7801 ** szNew[i]: Spaced used on the i-th sibling page. 7802 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to 7803 ** the right of the i-th sibling page. 7804 ** usableSpace: Number of bytes of space available on each sibling. 7805 ** 7806 */ 7807 usableSpace = pBt->usableSize - 12 + leafCorrection; 7808 for(i=k=0; i<nOld; i++, k++){ 7809 MemPage *p = apOld[i]; 7810 b.apEnd[k] = p->aDataEnd; 7811 b.ixNx[k] = cntOld[i]; 7812 if( k && b.ixNx[k]==b.ixNx[k-1] ){ 7813 k--; /* Omit b.ixNx[] entry for child pages with no cells */ 7814 } 7815 if( !leafData ){ 7816 k++; 7817 b.apEnd[k] = pParent->aDataEnd; 7818 b.ixNx[k] = cntOld[i]+1; 7819 } 7820 assert( p->nFree>=0 ); 7821 szNew[i] = usableSpace - p->nFree; 7822 for(j=0; j<p->nOverflow; j++){ 7823 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); 7824 } 7825 cntNew[i] = cntOld[i]; 7826 } 7827 k = nOld; 7828 for(i=0; i<k; i++){ 7829 int sz; 7830 while( szNew[i]>usableSpace ){ 7831 if( i+1>=k ){ 7832 k = i+2; 7833 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } 7834 szNew[k-1] = 0; 7835 cntNew[k-1] = b.nCell; 7836 } 7837 sz = 2 + cachedCellSize(&b, cntNew[i]-1); 7838 szNew[i] -= sz; 7839 if( !leafData ){ 7840 if( cntNew[i]<b.nCell ){ 7841 sz = 2 + cachedCellSize(&b, cntNew[i]); 7842 }else{ 7843 sz = 0; 7844 } 7845 } 7846 szNew[i+1] += sz; 7847 cntNew[i]--; 7848 } 7849 while( cntNew[i]<b.nCell ){ 7850 sz = 2 + cachedCellSize(&b, cntNew[i]); 7851 if( szNew[i]+sz>usableSpace ) break; 7852 szNew[i] += sz; 7853 cntNew[i]++; 7854 if( !leafData ){ 7855 if( cntNew[i]<b.nCell ){ 7856 sz = 2 + cachedCellSize(&b, cntNew[i]); 7857 }else{ 7858 sz = 0; 7859 } 7860 } 7861 szNew[i+1] -= sz; 7862 } 7863 if( cntNew[i]>=b.nCell ){ 7864 k = i+1; 7865 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ 7866 rc = SQLITE_CORRUPT_BKPT; 7867 goto balance_cleanup; 7868 } 7869 } 7870 7871 /* 7872 ** The packing computed by the previous block is biased toward the siblings 7873 ** on the left side (siblings with smaller keys). The left siblings are 7874 ** always nearly full, while the right-most sibling might be nearly empty. 7875 ** The next block of code attempts to adjust the packing of siblings to 7876 ** get a better balance. 7877 ** 7878 ** This adjustment is more than an optimization. The packing above might 7879 ** be so out of balance as to be illegal. For example, the right-most 7880 ** sibling might be completely empty. This adjustment is not optional. 7881 */ 7882 for(i=k-1; i>0; i--){ 7883 int szRight = szNew[i]; /* Size of sibling on the right */ 7884 int szLeft = szNew[i-1]; /* Size of sibling on the left */ 7885 int r; /* Index of right-most cell in left sibling */ 7886 int d; /* Index of first cell to the left of right sibling */ 7887 7888 r = cntNew[i-1] - 1; 7889 d = r + 1 - leafData; 7890 (void)cachedCellSize(&b, d); 7891 do{ 7892 assert( d<nMaxCells ); 7893 assert( r<nMaxCells ); 7894 (void)cachedCellSize(&b, r); 7895 if( szRight!=0 7896 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){ 7897 break; 7898 } 7899 szRight += b.szCell[d] + 2; 7900 szLeft -= b.szCell[r] + 2; 7901 cntNew[i-1] = r; 7902 r--; 7903 d--; 7904 }while( r>=0 ); 7905 szNew[i] = szRight; 7906 szNew[i-1] = szLeft; 7907 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ 7908 rc = SQLITE_CORRUPT_BKPT; 7909 goto balance_cleanup; 7910 } 7911 } 7912 7913 /* Sanity check: For a non-corrupt database file one of the follwing 7914 ** must be true: 7915 ** (1) We found one or more cells (cntNew[0])>0), or 7916 ** (2) pPage is a virtual root page. A virtual root page is when 7917 ** the real root page is page 1 and we are the only child of 7918 ** that page. 7919 */ 7920 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); 7921 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", 7922 apOld[0]->pgno, apOld[0]->nCell, 7923 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, 7924 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 7925 )); 7926 7927 /* 7928 ** Allocate k new pages. Reuse old pages where possible. 7929 */ 7930 pageFlags = apOld[0]->aData[0]; 7931 for(i=0; i<k; i++){ 7932 MemPage *pNew; 7933 if( i<nOld ){ 7934 pNew = apNew[i] = apOld[i]; 7935 apOld[i] = 0; 7936 rc = sqlite3PagerWrite(pNew->pDbPage); 7937 nNew++; 7938 if( rc ) goto balance_cleanup; 7939 }else{ 7940 assert( i>0 ); 7941 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); 7942 if( rc ) goto balance_cleanup; 7943 zeroPage(pNew, pageFlags); 7944 apNew[i] = pNew; 7945 nNew++; 7946 cntOld[i] = b.nCell; 7947 7948 /* Set the pointer-map entry for the new sibling page. */ 7949 if( ISAUTOVACUUM ){ 7950 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); 7951 if( rc!=SQLITE_OK ){ 7952 goto balance_cleanup; 7953 } 7954 } 7955 } 7956 } 7957 7958 /* 7959 ** Reassign page numbers so that the new pages are in ascending order. 7960 ** This helps to keep entries in the disk file in order so that a scan 7961 ** of the table is closer to a linear scan through the file. That in turn 7962 ** helps the operating system to deliver pages from the disk more rapidly. 7963 ** 7964 ** An O(n^2) insertion sort algorithm is used, but since n is never more 7965 ** than (NB+2) (a small constant), that should not be a problem. 7966 ** 7967 ** When NB==3, this one optimization makes the database about 25% faster 7968 ** for large insertions and deletions. 7969 */ 7970 for(i=0; i<nNew; i++){ 7971 aPgOrder[i] = aPgno[i] = apNew[i]->pgno; 7972 aPgFlags[i] = apNew[i]->pDbPage->flags; 7973 for(j=0; j<i; j++){ 7974 if( aPgno[j]==aPgno[i] ){ 7975 /* This branch is taken if the set of sibling pages somehow contains 7976 ** duplicate entries. This can happen if the database is corrupt. 7977 ** It would be simpler to detect this as part of the loop below, but 7978 ** we do the detection here in order to avoid populating the pager 7979 ** cache with two separate objects associated with the same 7980 ** page number. */ 7981 assert( CORRUPT_DB ); 7982 rc = SQLITE_CORRUPT_BKPT; 7983 goto balance_cleanup; 7984 } 7985 } 7986 } 7987 for(i=0; i<nNew; i++){ 7988 int iBest = 0; /* aPgno[] index of page number to use */ 7989 for(j=1; j<nNew; j++){ 7990 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j; 7991 } 7992 pgno = aPgOrder[iBest]; 7993 aPgOrder[iBest] = 0xffffffff; 7994 if( iBest!=i ){ 7995 if( iBest>i ){ 7996 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); 7997 } 7998 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); 7999 apNew[i]->pgno = pgno; 8000 } 8001 } 8002 8003 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " 8004 "%d(%d nc=%d) %d(%d nc=%d)\n", 8005 apNew[0]->pgno, szNew[0], cntNew[0], 8006 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, 8007 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, 8008 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, 8009 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, 8010 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, 8011 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, 8012 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, 8013 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 8014 )); 8015 8016 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 8017 assert( nNew>=1 && nNew<=ArraySize(apNew) ); 8018 assert( apNew[nNew-1]!=0 ); 8019 put4byte(pRight, apNew[nNew-1]->pgno); 8020 8021 /* If the sibling pages are not leaves, ensure that the right-child pointer 8022 ** of the right-most new sibling page is set to the value that was 8023 ** originally in the same field of the right-most old sibling page. */ 8024 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ 8025 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; 8026 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); 8027 } 8028 8029 /* Make any required updates to pointer map entries associated with 8030 ** cells stored on sibling pages following the balance operation. Pointer 8031 ** map entries associated with divider cells are set by the insertCell() 8032 ** routine. The associated pointer map entries are: 8033 ** 8034 ** a) if the cell contains a reference to an overflow chain, the 8035 ** entry associated with the first page in the overflow chain, and 8036 ** 8037 ** b) if the sibling pages are not leaves, the child page associated 8038 ** with the cell. 8039 ** 8040 ** If the sibling pages are not leaves, then the pointer map entry 8041 ** associated with the right-child of each sibling may also need to be 8042 ** updated. This happens below, after the sibling pages have been 8043 ** populated, not here. 8044 */ 8045 if( ISAUTOVACUUM ){ 8046 MemPage *pOld; 8047 MemPage *pNew = pOld = apNew[0]; 8048 int cntOldNext = pNew->nCell + pNew->nOverflow; 8049 int iNew = 0; 8050 int iOld = 0; 8051 8052 for(i=0; i<b.nCell; i++){ 8053 u8 *pCell = b.apCell[i]; 8054 while( i==cntOldNext ){ 8055 iOld++; 8056 assert( iOld<nNew || iOld<nOld ); 8057 assert( iOld>=0 && iOld<NB ); 8058 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld]; 8059 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; 8060 } 8061 if( i==cntNew[iNew] ){ 8062 pNew = apNew[++iNew]; 8063 if( !leafData ) continue; 8064 } 8065 8066 /* Cell pCell is destined for new sibling page pNew. Originally, it 8067 ** was either part of sibling page iOld (possibly an overflow cell), 8068 ** or else the divider cell to the left of sibling page iOld. So, 8069 ** if sibling page iOld had the same page number as pNew, and if 8070 ** pCell really was a part of sibling page iOld (not a divider or 8071 ** overflow cell), we can skip updating the pointer map entries. */ 8072 if( iOld>=nNew 8073 || pNew->pgno!=aPgno[iOld] 8074 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd) 8075 ){ 8076 if( !leafCorrection ){ 8077 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); 8078 } 8079 if( cachedCellSize(&b,i)>pNew->minLocal ){ 8080 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc); 8081 } 8082 if( rc ) goto balance_cleanup; 8083 } 8084 } 8085 } 8086 8087 /* Insert new divider cells into pParent. */ 8088 for(i=0; i<nNew-1; i++){ 8089 u8 *pCell; 8090 u8 *pTemp; 8091 int sz; 8092 MemPage *pNew = apNew[i]; 8093 j = cntNew[i]; 8094 8095 assert( j<nMaxCells ); 8096 assert( b.apCell[j]!=0 ); 8097 pCell = b.apCell[j]; 8098 sz = b.szCell[j] + leafCorrection; 8099 pTemp = &aOvflSpace[iOvflSpace]; 8100 if( !pNew->leaf ){ 8101 memcpy(&pNew->aData[8], pCell, 4); 8102 }else if( leafData ){ 8103 /* If the tree is a leaf-data tree, and the siblings are leaves, 8104 ** then there is no divider cell in b.apCell[]. Instead, the divider 8105 ** cell consists of the integer key for the right-most cell of 8106 ** the sibling-page assembled above only. 8107 */ 8108 CellInfo info; 8109 j--; 8110 pNew->xParseCell(pNew, b.apCell[j], &info); 8111 pCell = pTemp; 8112 sz = 4 + putVarint(&pCell[4], info.nKey); 8113 pTemp = 0; 8114 }else{ 8115 pCell -= 4; 8116 /* Obscure case for non-leaf-data trees: If the cell at pCell was 8117 ** previously stored on a leaf node, and its reported size was 4 8118 ** bytes, then it may actually be smaller than this 8119 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of 8120 ** any cell). But it is important to pass the correct size to 8121 ** insertCell(), so reparse the cell now. 8122 ** 8123 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" 8124 ** and WITHOUT ROWID tables with exactly one column which is the 8125 ** primary key. 8126 */ 8127 if( b.szCell[j]==4 ){ 8128 assert(leafCorrection==4); 8129 sz = pParent->xCellSize(pParent, pCell); 8130 } 8131 } 8132 iOvflSpace += sz; 8133 assert( sz<=pBt->maxLocal+23 ); 8134 assert( iOvflSpace <= (int)pBt->pageSize ); 8135 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); 8136 if( rc!=SQLITE_OK ) goto balance_cleanup; 8137 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); 8138 } 8139 8140 /* Now update the actual sibling pages. The order in which they are updated 8141 ** is important, as this code needs to avoid disrupting any page from which 8142 ** cells may still to be read. In practice, this means: 8143 ** 8144 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) 8145 ** then it is not safe to update page apNew[iPg] until after 8146 ** the left-hand sibling apNew[iPg-1] has been updated. 8147 ** 8148 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) 8149 ** then it is not safe to update page apNew[iPg] until after 8150 ** the right-hand sibling apNew[iPg+1] has been updated. 8151 ** 8152 ** If neither of the above apply, the page is safe to update. 8153 ** 8154 ** The iPg value in the following loop starts at nNew-1 goes down 8155 ** to 0, then back up to nNew-1 again, thus making two passes over 8156 ** the pages. On the initial downward pass, only condition (1) above 8157 ** needs to be tested because (2) will always be true from the previous 8158 ** step. On the upward pass, both conditions are always true, so the 8159 ** upwards pass simply processes pages that were missed on the downward 8160 ** pass. 8161 */ 8162 for(i=1-nNew; i<nNew; i++){ 8163 int iPg = i<0 ? -i : i; 8164 assert( iPg>=0 && iPg<nNew ); 8165 if( abDone[iPg] ) continue; /* Skip pages already processed */ 8166 if( i>=0 /* On the upwards pass, or... */ 8167 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ 8168 ){ 8169 int iNew; 8170 int iOld; 8171 int nNewCell; 8172 8173 /* Verify condition (1): If cells are moving left, update iPg 8174 ** only after iPg-1 has already been updated. */ 8175 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); 8176 8177 /* Verify condition (2): If cells are moving right, update iPg 8178 ** only after iPg+1 has already been updated. */ 8179 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); 8180 8181 if( iPg==0 ){ 8182 iNew = iOld = 0; 8183 nNewCell = cntNew[0]; 8184 }else{ 8185 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell; 8186 iNew = cntNew[iPg-1] + !leafData; 8187 nNewCell = cntNew[iPg] - iNew; 8188 } 8189 8190 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b); 8191 if( rc ) goto balance_cleanup; 8192 abDone[iPg]++; 8193 apNew[iPg]->nFree = usableSpace-szNew[iPg]; 8194 assert( apNew[iPg]->nOverflow==0 ); 8195 assert( apNew[iPg]->nCell==nNewCell ); 8196 } 8197 } 8198 8199 /* All pages have been processed exactly once */ 8200 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); 8201 8202 assert( nOld>0 ); 8203 assert( nNew>0 ); 8204 8205 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ 8206 /* The root page of the b-tree now contains no cells. The only sibling 8207 ** page is the right-child of the parent. Copy the contents of the 8208 ** child page into the parent, decreasing the overall height of the 8209 ** b-tree structure by one. This is described as the "balance-shallower" 8210 ** sub-algorithm in some documentation. 8211 ** 8212 ** If this is an auto-vacuum database, the call to copyNodeContent() 8213 ** sets all pointer-map entries corresponding to database image pages 8214 ** for which the pointer is stored within the content being copied. 8215 ** 8216 ** It is critical that the child page be defragmented before being 8217 ** copied into the parent, because if the parent is page 1 then it will 8218 ** by smaller than the child due to the database header, and so all the 8219 ** free space needs to be up front. 8220 */ 8221 assert( nNew==1 || CORRUPT_DB ); 8222 rc = defragmentPage(apNew[0], -1); 8223 testcase( rc!=SQLITE_OK ); 8224 assert( apNew[0]->nFree == 8225 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset 8226 - apNew[0]->nCell*2) 8227 || rc!=SQLITE_OK 8228 ); 8229 copyNodeContent(apNew[0], pParent, &rc); 8230 freePage(apNew[0], &rc); 8231 }else if( ISAUTOVACUUM && !leafCorrection ){ 8232 /* Fix the pointer map entries associated with the right-child of each 8233 ** sibling page. All other pointer map entries have already been taken 8234 ** care of. */ 8235 for(i=0; i<nNew; i++){ 8236 u32 key = get4byte(&apNew[i]->aData[8]); 8237 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); 8238 } 8239 } 8240 8241 assert( pParent->isInit ); 8242 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", 8243 nOld, nNew, b.nCell)); 8244 8245 /* Free any old pages that were not reused as new pages. 8246 */ 8247 for(i=nNew; i<nOld; i++){ 8248 freePage(apOld[i], &rc); 8249 } 8250 8251 #if 0 8252 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){ 8253 /* The ptrmapCheckPages() contains assert() statements that verify that 8254 ** all pointer map pages are set correctly. This is helpful while 8255 ** debugging. This is usually disabled because a corrupt database may 8256 ** cause an assert() statement to fail. */ 8257 ptrmapCheckPages(apNew, nNew); 8258 ptrmapCheckPages(&pParent, 1); 8259 } 8260 #endif 8261 8262 /* 8263 ** Cleanup before returning. 8264 */ 8265 balance_cleanup: 8266 sqlite3StackFree(0, b.apCell); 8267 for(i=0; i<nOld; i++){ 8268 releasePage(apOld[i]); 8269 } 8270 for(i=0; i<nNew; i++){ 8271 releasePage(apNew[i]); 8272 } 8273 8274 return rc; 8275 } 8276 8277 8278 /* 8279 ** This function is called when the root page of a b-tree structure is 8280 ** overfull (has one or more overflow pages). 8281 ** 8282 ** A new child page is allocated and the contents of the current root 8283 ** page, including overflow cells, are copied into the child. The root 8284 ** page is then overwritten to make it an empty page with the right-child 8285 ** pointer pointing to the new page. 8286 ** 8287 ** Before returning, all pointer-map entries corresponding to pages 8288 ** that the new child-page now contains pointers to are updated. The 8289 ** entry corresponding to the new right-child pointer of the root 8290 ** page is also updated. 8291 ** 8292 ** If successful, *ppChild is set to contain a reference to the child 8293 ** page and SQLITE_OK is returned. In this case the caller is required 8294 ** to call releasePage() on *ppChild exactly once. If an error occurs, 8295 ** an error code is returned and *ppChild is set to 0. 8296 */ 8297 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ 8298 int rc; /* Return value from subprocedures */ 8299 MemPage *pChild = 0; /* Pointer to a new child page */ 8300 Pgno pgnoChild = 0; /* Page number of the new child page */ 8301 BtShared *pBt = pRoot->pBt; /* The BTree */ 8302 8303 assert( pRoot->nOverflow>0 ); 8304 assert( sqlite3_mutex_held(pBt->mutex) ); 8305 8306 /* Make pRoot, the root page of the b-tree, writable. Allocate a new 8307 ** page that will become the new right-child of pPage. Copy the contents 8308 ** of the node stored on pRoot into the new child page. 8309 */ 8310 rc = sqlite3PagerWrite(pRoot->pDbPage); 8311 if( rc==SQLITE_OK ){ 8312 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); 8313 copyNodeContent(pRoot, pChild, &rc); 8314 if( ISAUTOVACUUM ){ 8315 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); 8316 } 8317 } 8318 if( rc ){ 8319 *ppChild = 0; 8320 releasePage(pChild); 8321 return rc; 8322 } 8323 assert( sqlite3PagerIswriteable(pChild->pDbPage) ); 8324 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 8325 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB ); 8326 8327 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); 8328 8329 /* Copy the overflow cells from pRoot to pChild */ 8330 memcpy(pChild->aiOvfl, pRoot->aiOvfl, 8331 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); 8332 memcpy(pChild->apOvfl, pRoot->apOvfl, 8333 pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); 8334 pChild->nOverflow = pRoot->nOverflow; 8335 8336 /* Zero the contents of pRoot. Then install pChild as the right-child. */ 8337 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); 8338 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); 8339 8340 *ppChild = pChild; 8341 return SQLITE_OK; 8342 } 8343 8344 /* 8345 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid 8346 ** on the same B-tree as pCur. 8347 ** 8348 ** This can if a database is corrupt with two or more SQL tables 8349 ** pointing to the same b-tree. If an insert occurs on one SQL table 8350 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL 8351 ** table linked to the same b-tree. If the secondary insert causes a 8352 ** rebalance, that can change content out from under the cursor on the 8353 ** first SQL table, violating invariants on the first insert. 8354 */ 8355 static int anotherValidCursor(BtCursor *pCur){ 8356 BtCursor *pOther; 8357 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){ 8358 if( pOther!=pCur 8359 && pOther->eState==CURSOR_VALID 8360 && pOther->pPage==pCur->pPage 8361 ){ 8362 return SQLITE_CORRUPT_BKPT; 8363 } 8364 } 8365 return SQLITE_OK; 8366 } 8367 8368 /* 8369 ** The page that pCur currently points to has just been modified in 8370 ** some way. This function figures out if this modification means the 8371 ** tree needs to be balanced, and if so calls the appropriate balancing 8372 ** routine. Balancing routines are: 8373 ** 8374 ** balance_quick() 8375 ** balance_deeper() 8376 ** balance_nonroot() 8377 */ 8378 static int balance(BtCursor *pCur){ 8379 int rc = SQLITE_OK; 8380 const int nMin = pCur->pBt->usableSize * 2 / 3; 8381 u8 aBalanceQuickSpace[13]; 8382 u8 *pFree = 0; 8383 8384 VVA_ONLY( int balance_quick_called = 0 ); 8385 VVA_ONLY( int balance_deeper_called = 0 ); 8386 8387 do { 8388 int iPage; 8389 MemPage *pPage = pCur->pPage; 8390 8391 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break; 8392 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ 8393 break; 8394 }else if( (iPage = pCur->iPage)==0 ){ 8395 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){ 8396 /* The root page of the b-tree is overfull. In this case call the 8397 ** balance_deeper() function to create a new child for the root-page 8398 ** and copy the current contents of the root-page to it. The 8399 ** next iteration of the do-loop will balance the child page. 8400 */ 8401 assert( balance_deeper_called==0 ); 8402 VVA_ONLY( balance_deeper_called++ ); 8403 rc = balance_deeper(pPage, &pCur->apPage[1]); 8404 if( rc==SQLITE_OK ){ 8405 pCur->iPage = 1; 8406 pCur->ix = 0; 8407 pCur->aiIdx[0] = 0; 8408 pCur->apPage[0] = pPage; 8409 pCur->pPage = pCur->apPage[1]; 8410 assert( pCur->pPage->nOverflow ); 8411 } 8412 }else{ 8413 break; 8414 } 8415 }else{ 8416 MemPage * const pParent = pCur->apPage[iPage-1]; 8417 int const iIdx = pCur->aiIdx[iPage-1]; 8418 8419 rc = sqlite3PagerWrite(pParent->pDbPage); 8420 if( rc==SQLITE_OK && pParent->nFree<0 ){ 8421 rc = btreeComputeFreeSpace(pParent); 8422 } 8423 if( rc==SQLITE_OK ){ 8424 #ifndef SQLITE_OMIT_QUICKBALANCE 8425 if( pPage->intKeyLeaf 8426 && pPage->nOverflow==1 8427 && pPage->aiOvfl[0]==pPage->nCell 8428 && pParent->pgno!=1 8429 && pParent->nCell==iIdx 8430 ){ 8431 /* Call balance_quick() to create a new sibling of pPage on which 8432 ** to store the overflow cell. balance_quick() inserts a new cell 8433 ** into pParent, which may cause pParent overflow. If this 8434 ** happens, the next iteration of the do-loop will balance pParent 8435 ** use either balance_nonroot() or balance_deeper(). Until this 8436 ** happens, the overflow cell is stored in the aBalanceQuickSpace[] 8437 ** buffer. 8438 ** 8439 ** The purpose of the following assert() is to check that only a 8440 ** single call to balance_quick() is made for each call to this 8441 ** function. If this were not verified, a subtle bug involving reuse 8442 ** of the aBalanceQuickSpace[] might sneak in. 8443 */ 8444 assert( balance_quick_called==0 ); 8445 VVA_ONLY( balance_quick_called++ ); 8446 rc = balance_quick(pParent, pPage, aBalanceQuickSpace); 8447 }else 8448 #endif 8449 { 8450 /* In this case, call balance_nonroot() to redistribute cells 8451 ** between pPage and up to 2 of its sibling pages. This involves 8452 ** modifying the contents of pParent, which may cause pParent to 8453 ** become overfull or underfull. The next iteration of the do-loop 8454 ** will balance the parent page to correct this. 8455 ** 8456 ** If the parent page becomes overfull, the overflow cell or cells 8457 ** are stored in the pSpace buffer allocated immediately below. 8458 ** A subsequent iteration of the do-loop will deal with this by 8459 ** calling balance_nonroot() (balance_deeper() may be called first, 8460 ** but it doesn't deal with overflow cells - just moves them to a 8461 ** different page). Once this subsequent call to balance_nonroot() 8462 ** has completed, it is safe to release the pSpace buffer used by 8463 ** the previous call, as the overflow cell data will have been 8464 ** copied either into the body of a database page or into the new 8465 ** pSpace buffer passed to the latter call to balance_nonroot(). 8466 */ 8467 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); 8468 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, 8469 pCur->hints&BTREE_BULKLOAD); 8470 if( pFree ){ 8471 /* If pFree is not NULL, it points to the pSpace buffer used 8472 ** by a previous call to balance_nonroot(). Its contents are 8473 ** now stored either on real database pages or within the 8474 ** new pSpace buffer, so it may be safely freed here. */ 8475 sqlite3PageFree(pFree); 8476 } 8477 8478 /* The pSpace buffer will be freed after the next call to 8479 ** balance_nonroot(), or just before this function returns, whichever 8480 ** comes first. */ 8481 pFree = pSpace; 8482 } 8483 } 8484 8485 pPage->nOverflow = 0; 8486 8487 /* The next iteration of the do-loop balances the parent page. */ 8488 releasePage(pPage); 8489 pCur->iPage--; 8490 assert( pCur->iPage>=0 ); 8491 pCur->pPage = pCur->apPage[pCur->iPage]; 8492 } 8493 }while( rc==SQLITE_OK ); 8494 8495 if( pFree ){ 8496 sqlite3PageFree(pFree); 8497 } 8498 return rc; 8499 } 8500 8501 /* Overwrite content from pX into pDest. Only do the write if the 8502 ** content is different from what is already there. 8503 */ 8504 static int btreeOverwriteContent( 8505 MemPage *pPage, /* MemPage on which writing will occur */ 8506 u8 *pDest, /* Pointer to the place to start writing */ 8507 const BtreePayload *pX, /* Source of data to write */ 8508 int iOffset, /* Offset of first byte to write */ 8509 int iAmt /* Number of bytes to be written */ 8510 ){ 8511 int nData = pX->nData - iOffset; 8512 if( nData<=0 ){ 8513 /* Overwritting with zeros */ 8514 int i; 8515 for(i=0; i<iAmt && pDest[i]==0; i++){} 8516 if( i<iAmt ){ 8517 int rc = sqlite3PagerWrite(pPage->pDbPage); 8518 if( rc ) return rc; 8519 memset(pDest + i, 0, iAmt - i); 8520 } 8521 }else{ 8522 if( nData<iAmt ){ 8523 /* Mixed read data and zeros at the end. Make a recursive call 8524 ** to write the zeros then fall through to write the real data */ 8525 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData, 8526 iAmt-nData); 8527 if( rc ) return rc; 8528 iAmt = nData; 8529 } 8530 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){ 8531 int rc = sqlite3PagerWrite(pPage->pDbPage); 8532 if( rc ) return rc; 8533 /* In a corrupt database, it is possible for the source and destination 8534 ** buffers to overlap. This is harmless since the database is already 8535 ** corrupt but it does cause valgrind and ASAN warnings. So use 8536 ** memmove(). */ 8537 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); 8538 } 8539 } 8540 return SQLITE_OK; 8541 } 8542 8543 /* 8544 ** Overwrite the cell that cursor pCur is pointing to with fresh content 8545 ** contained in pX. 8546 */ 8547 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){ 8548 int iOffset; /* Next byte of pX->pData to write */ 8549 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ 8550 int rc; /* Return code */ 8551 MemPage *pPage = pCur->pPage; /* Page being written */ 8552 BtShared *pBt; /* Btree */ 8553 Pgno ovflPgno; /* Next overflow page to write */ 8554 u32 ovflPageSize; /* Size to write on overflow page */ 8555 8556 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd 8557 || pCur->info.pPayload < pPage->aData + pPage->cellOffset 8558 ){ 8559 return SQLITE_CORRUPT_BKPT; 8560 } 8561 /* Overwrite the local portion first */ 8562 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX, 8563 0, pCur->info.nLocal); 8564 if( rc ) return rc; 8565 if( pCur->info.nLocal==nTotal ) return SQLITE_OK; 8566 8567 /* Now overwrite the overflow pages */ 8568 iOffset = pCur->info.nLocal; 8569 assert( nTotal>=0 ); 8570 assert( iOffset>=0 ); 8571 ovflPgno = get4byte(pCur->info.pPayload + iOffset); 8572 pBt = pPage->pBt; 8573 ovflPageSize = pBt->usableSize - 4; 8574 do{ 8575 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0); 8576 if( rc ) return rc; 8577 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){ 8578 rc = SQLITE_CORRUPT_BKPT; 8579 }else{ 8580 if( iOffset+ovflPageSize<(u32)nTotal ){ 8581 ovflPgno = get4byte(pPage->aData); 8582 }else{ 8583 ovflPageSize = nTotal - iOffset; 8584 } 8585 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX, 8586 iOffset, ovflPageSize); 8587 } 8588 sqlite3PagerUnref(pPage->pDbPage); 8589 if( rc ) return rc; 8590 iOffset += ovflPageSize; 8591 }while( iOffset<nTotal ); 8592 return SQLITE_OK; 8593 } 8594 8595 8596 /* 8597 ** Insert a new record into the BTree. The content of the new record 8598 ** is described by the pX object. The pCur cursor is used only to 8599 ** define what table the record should be inserted into, and is left 8600 ** pointing at a random location. 8601 ** 8602 ** For a table btree (used for rowid tables), only the pX.nKey value of 8603 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the 8604 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields 8605 ** hold the content of the row. 8606 ** 8607 ** For an index btree (used for indexes and WITHOUT ROWID tables), the 8608 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The 8609 ** pX.pData,nData,nZero fields must be zero. 8610 ** 8611 ** If the seekResult parameter is non-zero, then a successful call to 8612 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already 8613 ** been performed. In other words, if seekResult!=0 then the cursor 8614 ** is currently pointing to a cell that will be adjacent to the cell 8615 ** to be inserted. If seekResult<0 then pCur points to a cell that is 8616 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell 8617 ** that is larger than (pKey,nKey). 8618 ** 8619 ** If seekResult==0, that means pCur is pointing at some unknown location. 8620 ** In that case, this routine must seek the cursor to the correct insertion 8621 ** point for (pKey,nKey) before doing the insertion. For index btrees, 8622 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked 8623 ** key values and pX->aMem can be used instead of pX->pKey to avoid having 8624 ** to decode the key. 8625 */ 8626 int sqlite3BtreeInsert( 8627 BtCursor *pCur, /* Insert data into the table of this cursor */ 8628 const BtreePayload *pX, /* Content of the row to be inserted */ 8629 int flags, /* True if this is likely an append */ 8630 int seekResult /* Result of prior MovetoUnpacked() call */ 8631 ){ 8632 int rc; 8633 int loc = seekResult; /* -1: before desired location +1: after */ 8634 int szNew = 0; 8635 int idx; 8636 MemPage *pPage; 8637 Btree *p = pCur->pBtree; 8638 BtShared *pBt = p->pBt; 8639 unsigned char *oldCell; 8640 unsigned char *newCell = 0; 8641 8642 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags ); 8643 8644 if( pCur->eState==CURSOR_FAULT ){ 8645 assert( pCur->skipNext!=SQLITE_OK ); 8646 return pCur->skipNext; 8647 } 8648 8649 assert( cursorOwnsBtShared(pCur) ); 8650 assert( (pCur->curFlags & BTCF_WriteFlag)!=0 8651 && pBt->inTransaction==TRANS_WRITE 8652 && (pBt->btsFlags & BTS_READ_ONLY)==0 ); 8653 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 8654 8655 /* Assert that the caller has been consistent. If this cursor was opened 8656 ** expecting an index b-tree, then the caller should be inserting blob 8657 ** keys with no associated data. If the cursor was opened expecting an 8658 ** intkey table, the caller should be inserting integer keys with a 8659 ** blob of associated data. */ 8660 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) ); 8661 8662 /* Save the positions of any other cursors open on this table. 8663 ** 8664 ** In some cases, the call to btreeMoveto() below is a no-op. For 8665 ** example, when inserting data into a table with auto-generated integer 8666 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 8667 ** integer key to use. It then calls this function to actually insert the 8668 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes 8669 ** that the cursor is already where it needs to be and returns without 8670 ** doing any work. To avoid thwarting these optimizations, it is important 8671 ** not to clear the cursor here. 8672 */ 8673 if( pCur->curFlags & BTCF_Multiple ){ 8674 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 8675 if( rc ) return rc; 8676 } 8677 8678 if( pCur->pKeyInfo==0 ){ 8679 assert( pX->pKey==0 ); 8680 /* If this is an insert into a table b-tree, invalidate any incrblob 8681 ** cursors open on the row being replaced */ 8682 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0); 8683 8684 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 8685 ** to a row with the same key as the new entry being inserted. 8686 */ 8687 #ifdef SQLITE_DEBUG 8688 if( flags & BTREE_SAVEPOSITION ){ 8689 assert( pCur->curFlags & BTCF_ValidNKey ); 8690 assert( pX->nKey==pCur->info.nKey ); 8691 assert( loc==0 ); 8692 } 8693 #endif 8694 8695 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply 8696 ** that the cursor is not pointing to a row to be overwritten. 8697 ** So do a complete check. 8698 */ 8699 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ 8700 /* The cursor is pointing to the entry that is to be 8701 ** overwritten */ 8702 assert( pX->nData>=0 && pX->nZero>=0 ); 8703 if( pCur->info.nSize!=0 8704 && pCur->info.nPayload==(u32)pX->nData+pX->nZero 8705 ){ 8706 /* New entry is the same size as the old. Do an overwrite */ 8707 return btreeOverwriteCell(pCur, pX); 8708 } 8709 assert( loc==0 ); 8710 }else if( loc==0 ){ 8711 /* The cursor is *not* pointing to the cell to be overwritten, nor 8712 ** to an adjacent cell. Move the cursor so that it is pointing either 8713 ** to the cell to be overwritten or an adjacent cell. 8714 */ 8715 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc); 8716 if( rc ) return rc; 8717 } 8718 }else{ 8719 /* This is an index or a WITHOUT ROWID table */ 8720 8721 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 8722 ** to a row with the same key as the new entry being inserted. 8723 */ 8724 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 ); 8725 8726 /* If the cursor is not already pointing either to the cell to be 8727 ** overwritten, or if a new cell is being inserted, if the cursor is 8728 ** not pointing to an immediately adjacent cell, then move the cursor 8729 ** so that it does. 8730 */ 8731 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){ 8732 if( pX->nMem ){ 8733 UnpackedRecord r; 8734 r.pKeyInfo = pCur->pKeyInfo; 8735 r.aMem = pX->aMem; 8736 r.nField = pX->nMem; 8737 r.default_rc = 0; 8738 r.errCode = 0; 8739 r.r1 = 0; 8740 r.r2 = 0; 8741 r.eqSeen = 0; 8742 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc); 8743 }else{ 8744 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc); 8745 } 8746 if( rc ) return rc; 8747 } 8748 8749 /* If the cursor is currently pointing to an entry to be overwritten 8750 ** and the new content is the same as as the old, then use the 8751 ** overwrite optimization. 8752 */ 8753 if( loc==0 ){ 8754 getCellInfo(pCur); 8755 if( pCur->info.nKey==pX->nKey ){ 8756 BtreePayload x2; 8757 x2.pData = pX->pKey; 8758 x2.nData = pX->nKey; 8759 x2.nZero = 0; 8760 return btreeOverwriteCell(pCur, &x2); 8761 } 8762 } 8763 8764 } 8765 assert( pCur->eState==CURSOR_VALID 8766 || (pCur->eState==CURSOR_INVALID && loc) 8767 || CORRUPT_DB ); 8768 8769 pPage = pCur->pPage; 8770 assert( pPage->intKey || pX->nKey>=0 ); 8771 assert( pPage->leaf || !pPage->intKey ); 8772 if( pPage->nFree<0 ){ 8773 rc = btreeComputeFreeSpace(pPage); 8774 if( rc ) return rc; 8775 } 8776 8777 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", 8778 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, 8779 loc==0 ? "overwrite" : "new entry")); 8780 assert( pPage->isInit ); 8781 newCell = pBt->pTmpSpace; 8782 assert( newCell!=0 ); 8783 rc = fillInCell(pPage, newCell, pX, &szNew); 8784 if( rc ) goto end_insert; 8785 assert( szNew==pPage->xCellSize(pPage, newCell) ); 8786 assert( szNew <= MX_CELL_SIZE(pBt) ); 8787 idx = pCur->ix; 8788 if( loc==0 ){ 8789 CellInfo info; 8790 assert( idx<pPage->nCell ); 8791 rc = sqlite3PagerWrite(pPage->pDbPage); 8792 if( rc ){ 8793 goto end_insert; 8794 } 8795 oldCell = findCell(pPage, idx); 8796 if( !pPage->leaf ){ 8797 memcpy(newCell, oldCell, 4); 8798 } 8799 rc = clearCell(pPage, oldCell, &info); 8800 testcase( pCur->curFlags & BTCF_ValidOvfl ); 8801 invalidateOverflowCache(pCur); 8802 if( info.nSize==szNew && info.nLocal==info.nPayload 8803 && (!ISAUTOVACUUM || szNew<pPage->minLocal) 8804 ){ 8805 /* Overwrite the old cell with the new if they are the same size. 8806 ** We could also try to do this if the old cell is smaller, then add 8807 ** the leftover space to the free list. But experiments show that 8808 ** doing that is no faster then skipping this optimization and just 8809 ** calling dropCell() and insertCell(). 8810 ** 8811 ** This optimization cannot be used on an autovacuum database if the 8812 ** new entry uses overflow pages, as the insertCell() call below is 8813 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ 8814 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ 8815 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){ 8816 return SQLITE_CORRUPT_BKPT; 8817 } 8818 if( oldCell+szNew > pPage->aDataEnd ){ 8819 return SQLITE_CORRUPT_BKPT; 8820 } 8821 memcpy(oldCell, newCell, szNew); 8822 return SQLITE_OK; 8823 } 8824 dropCell(pPage, idx, info.nSize, &rc); 8825 if( rc ) goto end_insert; 8826 }else if( loc<0 && pPage->nCell>0 ){ 8827 assert( pPage->leaf ); 8828 idx = ++pCur->ix; 8829 pCur->curFlags &= ~BTCF_ValidNKey; 8830 }else{ 8831 assert( pPage->leaf ); 8832 } 8833 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); 8834 assert( pPage->nOverflow==0 || rc==SQLITE_OK ); 8835 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); 8836 8837 /* If no error has occurred and pPage has an overflow cell, call balance() 8838 ** to redistribute the cells within the tree. Since balance() may move 8839 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey 8840 ** variables. 8841 ** 8842 ** Previous versions of SQLite called moveToRoot() to move the cursor 8843 ** back to the root page as balance() used to invalidate the contents 8844 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, 8845 ** set the cursor state to "invalid". This makes common insert operations 8846 ** slightly faster. 8847 ** 8848 ** There is a subtle but important optimization here too. When inserting 8849 ** multiple records into an intkey b-tree using a single cursor (as can 8850 ** happen while processing an "INSERT INTO ... SELECT" statement), it 8851 ** is advantageous to leave the cursor pointing to the last entry in 8852 ** the b-tree if possible. If the cursor is left pointing to the last 8853 ** entry in the table, and the next row inserted has an integer key 8854 ** larger than the largest existing key, it is possible to insert the 8855 ** row without seeking the cursor. This can be a big performance boost. 8856 */ 8857 pCur->info.nSize = 0; 8858 if( pPage->nOverflow ){ 8859 assert( rc==SQLITE_OK ); 8860 pCur->curFlags &= ~(BTCF_ValidNKey); 8861 rc = balance(pCur); 8862 8863 /* Must make sure nOverflow is reset to zero even if the balance() 8864 ** fails. Internal data structure corruption will result otherwise. 8865 ** Also, set the cursor state to invalid. This stops saveCursorPosition() 8866 ** from trying to save the current position of the cursor. */ 8867 pCur->pPage->nOverflow = 0; 8868 pCur->eState = CURSOR_INVALID; 8869 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){ 8870 btreeReleaseAllCursorPages(pCur); 8871 if( pCur->pKeyInfo ){ 8872 assert( pCur->pKey==0 ); 8873 pCur->pKey = sqlite3Malloc( pX->nKey ); 8874 if( pCur->pKey==0 ){ 8875 rc = SQLITE_NOMEM; 8876 }else{ 8877 memcpy(pCur->pKey, pX->pKey, pX->nKey); 8878 } 8879 } 8880 pCur->eState = CURSOR_REQUIRESEEK; 8881 pCur->nKey = pX->nKey; 8882 } 8883 } 8884 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 ); 8885 8886 end_insert: 8887 return rc; 8888 } 8889 8890 /* 8891 ** Delete the entry that the cursor is pointing to. 8892 ** 8893 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then 8894 ** the cursor is left pointing at an arbitrary location after the delete. 8895 ** But if that bit is set, then the cursor is left in a state such that 8896 ** the next call to BtreeNext() or BtreePrev() moves it to the same row 8897 ** as it would have been on if the call to BtreeDelete() had been omitted. 8898 ** 8899 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes 8900 ** associated with a single table entry and its indexes. Only one of those 8901 ** deletes is considered the "primary" delete. The primary delete occurs 8902 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete 8903 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. 8904 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, 8905 ** but which might be used by alternative storage engines. 8906 */ 8907 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ 8908 Btree *p = pCur->pBtree; 8909 BtShared *pBt = p->pBt; 8910 int rc; /* Return code */ 8911 MemPage *pPage; /* Page to delete cell from */ 8912 unsigned char *pCell; /* Pointer to cell to delete */ 8913 int iCellIdx; /* Index of cell to delete */ 8914 int iCellDepth; /* Depth of node containing pCell */ 8915 CellInfo info; /* Size of the cell being deleted */ 8916 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ 8917 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ 8918 8919 assert( cursorOwnsBtShared(pCur) ); 8920 assert( pBt->inTransaction==TRANS_WRITE ); 8921 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 8922 assert( pCur->curFlags & BTCF_WriteFlag ); 8923 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); 8924 assert( !hasReadConflicts(p, pCur->pgnoRoot) ); 8925 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); 8926 if( pCur->eState==CURSOR_REQUIRESEEK ){ 8927 rc = btreeRestoreCursorPosition(pCur); 8928 if( rc ) return rc; 8929 } 8930 assert( pCur->eState==CURSOR_VALID ); 8931 8932 iCellDepth = pCur->iPage; 8933 iCellIdx = pCur->ix; 8934 pPage = pCur->pPage; 8935 pCell = findCell(pPage, iCellIdx); 8936 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT; 8937 8938 /* If the bPreserve flag is set to true, then the cursor position must 8939 ** be preserved following this delete operation. If the current delete 8940 ** will cause a b-tree rebalance, then this is done by saving the cursor 8941 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 8942 ** returning. 8943 ** 8944 ** Or, if the current delete will not cause a rebalance, then the cursor 8945 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately 8946 ** before or after the deleted entry. In this case set bSkipnext to true. */ 8947 if( bPreserve ){ 8948 if( !pPage->leaf 8949 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) 8950 || pPage->nCell==1 /* See dbfuzz001.test for a test case */ 8951 ){ 8952 /* A b-tree rebalance will be required after deleting this entry. 8953 ** Save the cursor key. */ 8954 rc = saveCursorKey(pCur); 8955 if( rc ) return rc; 8956 }else{ 8957 bSkipnext = 1; 8958 } 8959 } 8960 8961 /* If the page containing the entry to delete is not a leaf page, move 8962 ** the cursor to the largest entry in the tree that is smaller than 8963 ** the entry being deleted. This cell will replace the cell being deleted 8964 ** from the internal node. The 'previous' entry is used for this instead 8965 ** of the 'next' entry, as the previous entry is always a part of the 8966 ** sub-tree headed by the child page of the cell being deleted. This makes 8967 ** balancing the tree following the delete operation easier. */ 8968 if( !pPage->leaf ){ 8969 rc = sqlite3BtreePrevious(pCur, 0); 8970 assert( rc!=SQLITE_DONE ); 8971 if( rc ) return rc; 8972 } 8973 8974 /* Save the positions of any other cursors open on this table before 8975 ** making any modifications. */ 8976 if( pCur->curFlags & BTCF_Multiple ){ 8977 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); 8978 if( rc ) return rc; 8979 } 8980 8981 /* If this is a delete operation to remove a row from a table b-tree, 8982 ** invalidate any incrblob cursors open on the row being deleted. */ 8983 if( pCur->pKeyInfo==0 ){ 8984 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0); 8985 } 8986 8987 /* Make the page containing the entry to be deleted writable. Then free any 8988 ** overflow pages associated with the entry and finally remove the cell 8989 ** itself from within the page. */ 8990 rc = sqlite3PagerWrite(pPage->pDbPage); 8991 if( rc ) return rc; 8992 rc = clearCell(pPage, pCell, &info); 8993 dropCell(pPage, iCellIdx, info.nSize, &rc); 8994 if( rc ) return rc; 8995 8996 /* If the cell deleted was not located on a leaf page, then the cursor 8997 ** is currently pointing to the largest entry in the sub-tree headed 8998 ** by the child-page of the cell that was just deleted from an internal 8999 ** node. The cell from the leaf node needs to be moved to the internal 9000 ** node to replace the deleted cell. */ 9001 if( !pPage->leaf ){ 9002 MemPage *pLeaf = pCur->pPage; 9003 int nCell; 9004 Pgno n; 9005 unsigned char *pTmp; 9006 9007 if( pLeaf->nFree<0 ){ 9008 rc = btreeComputeFreeSpace(pLeaf); 9009 if( rc ) return rc; 9010 } 9011 if( iCellDepth<pCur->iPage-1 ){ 9012 n = pCur->apPage[iCellDepth+1]->pgno; 9013 }else{ 9014 n = pCur->pPage->pgno; 9015 } 9016 pCell = findCell(pLeaf, pLeaf->nCell-1); 9017 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; 9018 nCell = pLeaf->xCellSize(pLeaf, pCell); 9019 assert( MX_CELL_SIZE(pBt) >= nCell ); 9020 pTmp = pBt->pTmpSpace; 9021 assert( pTmp!=0 ); 9022 rc = sqlite3PagerWrite(pLeaf->pDbPage); 9023 if( rc==SQLITE_OK ){ 9024 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); 9025 } 9026 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); 9027 if( rc ) return rc; 9028 } 9029 9030 /* Balance the tree. If the entry deleted was located on a leaf page, 9031 ** then the cursor still points to that page. In this case the first 9032 ** call to balance() repairs the tree, and the if(...) condition is 9033 ** never true. 9034 ** 9035 ** Otherwise, if the entry deleted was on an internal node page, then 9036 ** pCur is pointing to the leaf page from which a cell was removed to 9037 ** replace the cell deleted from the internal node. This is slightly 9038 ** tricky as the leaf node may be underfull, and the internal node may 9039 ** be either under or overfull. In this case run the balancing algorithm 9040 ** on the leaf node first. If the balance proceeds far enough up the 9041 ** tree that we can be sure that any problem in the internal node has 9042 ** been corrected, so be it. Otherwise, after balancing the leaf node, 9043 ** walk the cursor up the tree to the internal node and balance it as 9044 ** well. */ 9045 rc = balance(pCur); 9046 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ 9047 releasePageNotNull(pCur->pPage); 9048 pCur->iPage--; 9049 while( pCur->iPage>iCellDepth ){ 9050 releasePage(pCur->apPage[pCur->iPage--]); 9051 } 9052 pCur->pPage = pCur->apPage[pCur->iPage]; 9053 rc = balance(pCur); 9054 } 9055 9056 if( rc==SQLITE_OK ){ 9057 if( bSkipnext ){ 9058 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); 9059 assert( pPage==pCur->pPage || CORRUPT_DB ); 9060 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); 9061 pCur->eState = CURSOR_SKIPNEXT; 9062 if( iCellIdx>=pPage->nCell ){ 9063 pCur->skipNext = -1; 9064 pCur->ix = pPage->nCell-1; 9065 }else{ 9066 pCur->skipNext = 1; 9067 } 9068 }else{ 9069 rc = moveToRoot(pCur); 9070 if( bPreserve ){ 9071 btreeReleaseAllCursorPages(pCur); 9072 pCur->eState = CURSOR_REQUIRESEEK; 9073 } 9074 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK; 9075 } 9076 } 9077 return rc; 9078 } 9079 9080 /* 9081 ** Create a new BTree table. Write into *piTable the page 9082 ** number for the root page of the new table. 9083 ** 9084 ** The type of type is determined by the flags parameter. Only the 9085 ** following values of flags are currently in use. Other values for 9086 ** flags might not work: 9087 ** 9088 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys 9089 ** BTREE_ZERODATA Used for SQL indices 9090 */ 9091 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ 9092 BtShared *pBt = p->pBt; 9093 MemPage *pRoot; 9094 Pgno pgnoRoot; 9095 int rc; 9096 int ptfFlags; /* Page-type flage for the root page of new table */ 9097 9098 assert( sqlite3BtreeHoldsMutex(p) ); 9099 assert( pBt->inTransaction==TRANS_WRITE ); 9100 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); 9101 9102 #ifdef SQLITE_OMIT_AUTOVACUUM 9103 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 9104 if( rc ){ 9105 return rc; 9106 } 9107 #else 9108 if( pBt->autoVacuum ){ 9109 Pgno pgnoMove; /* Move a page here to make room for the root-page */ 9110 MemPage *pPageMove; /* The page to move to. */ 9111 9112 /* Creating a new table may probably require moving an existing database 9113 ** to make room for the new tables root page. In case this page turns 9114 ** out to be an overflow page, delete all overflow page-map caches 9115 ** held by open cursors. 9116 */ 9117 invalidateAllOverflowCache(pBt); 9118 9119 /* Read the value of meta[3] from the database to determine where the 9120 ** root page of the new table should go. meta[3] is the largest root-page 9121 ** created so far, so the new root-page is (meta[3]+1). 9122 */ 9123 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); 9124 pgnoRoot++; 9125 9126 /* The new root-page may not be allocated on a pointer-map page, or the 9127 ** PENDING_BYTE page. 9128 */ 9129 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || 9130 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ 9131 pgnoRoot++; 9132 } 9133 assert( pgnoRoot>=3 || CORRUPT_DB ); 9134 testcase( pgnoRoot<3 ); 9135 9136 /* Allocate a page. The page that currently resides at pgnoRoot will 9137 ** be moved to the allocated page (unless the allocated page happens 9138 ** to reside at pgnoRoot). 9139 */ 9140 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); 9141 if( rc!=SQLITE_OK ){ 9142 return rc; 9143 } 9144 9145 if( pgnoMove!=pgnoRoot ){ 9146 /* pgnoRoot is the page that will be used for the root-page of 9147 ** the new table (assuming an error did not occur). But we were 9148 ** allocated pgnoMove. If required (i.e. if it was not allocated 9149 ** by extending the file), the current page at position pgnoMove 9150 ** is already journaled. 9151 */ 9152 u8 eType = 0; 9153 Pgno iPtrPage = 0; 9154 9155 /* Save the positions of any open cursors. This is required in 9156 ** case they are holding a reference to an xFetch reference 9157 ** corresponding to page pgnoRoot. */ 9158 rc = saveAllCursors(pBt, 0, 0); 9159 releasePage(pPageMove); 9160 if( rc!=SQLITE_OK ){ 9161 return rc; 9162 } 9163 9164 /* Move the page currently at pgnoRoot to pgnoMove. */ 9165 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 9166 if( rc!=SQLITE_OK ){ 9167 return rc; 9168 } 9169 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); 9170 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ 9171 rc = SQLITE_CORRUPT_BKPT; 9172 } 9173 if( rc!=SQLITE_OK ){ 9174 releasePage(pRoot); 9175 return rc; 9176 } 9177 assert( eType!=PTRMAP_ROOTPAGE ); 9178 assert( eType!=PTRMAP_FREEPAGE ); 9179 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); 9180 releasePage(pRoot); 9181 9182 /* Obtain the page at pgnoRoot */ 9183 if( rc!=SQLITE_OK ){ 9184 return rc; 9185 } 9186 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); 9187 if( rc!=SQLITE_OK ){ 9188 return rc; 9189 } 9190 rc = sqlite3PagerWrite(pRoot->pDbPage); 9191 if( rc!=SQLITE_OK ){ 9192 releasePage(pRoot); 9193 return rc; 9194 } 9195 }else{ 9196 pRoot = pPageMove; 9197 } 9198 9199 /* Update the pointer-map and meta-data with the new root-page number. */ 9200 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); 9201 if( rc ){ 9202 releasePage(pRoot); 9203 return rc; 9204 } 9205 9206 /* When the new root page was allocated, page 1 was made writable in 9207 ** order either to increase the database filesize, or to decrement the 9208 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. 9209 */ 9210 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); 9211 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); 9212 if( NEVER(rc) ){ 9213 releasePage(pRoot); 9214 return rc; 9215 } 9216 9217 }else{ 9218 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); 9219 if( rc ) return rc; 9220 } 9221 #endif 9222 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); 9223 if( createTabFlags & BTREE_INTKEY ){ 9224 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; 9225 }else{ 9226 ptfFlags = PTF_ZERODATA | PTF_LEAF; 9227 } 9228 zeroPage(pRoot, ptfFlags); 9229 sqlite3PagerUnref(pRoot->pDbPage); 9230 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); 9231 *piTable = (int)pgnoRoot; 9232 return SQLITE_OK; 9233 } 9234 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ 9235 int rc; 9236 sqlite3BtreeEnter(p); 9237 rc = btreeCreateTable(p, piTable, flags); 9238 sqlite3BtreeLeave(p); 9239 return rc; 9240 } 9241 9242 /* 9243 ** Erase the given database page and all its children. Return 9244 ** the page to the freelist. 9245 */ 9246 static int clearDatabasePage( 9247 BtShared *pBt, /* The BTree that contains the table */ 9248 Pgno pgno, /* Page number to clear */ 9249 int freePageFlag, /* Deallocate page if true */ 9250 int *pnChange /* Add number of Cells freed to this counter */ 9251 ){ 9252 MemPage *pPage; 9253 int rc; 9254 unsigned char *pCell; 9255 int i; 9256 int hdr; 9257 CellInfo info; 9258 9259 assert( sqlite3_mutex_held(pBt->mutex) ); 9260 if( pgno>btreePagecount(pBt) ){ 9261 return SQLITE_CORRUPT_BKPT; 9262 } 9263 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); 9264 if( rc ) return rc; 9265 if( pPage->bBusy ){ 9266 rc = SQLITE_CORRUPT_BKPT; 9267 goto cleardatabasepage_out; 9268 } 9269 pPage->bBusy = 1; 9270 hdr = pPage->hdrOffset; 9271 for(i=0; i<pPage->nCell; i++){ 9272 pCell = findCell(pPage, i); 9273 if( !pPage->leaf ){ 9274 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); 9275 if( rc ) goto cleardatabasepage_out; 9276 } 9277 rc = clearCell(pPage, pCell, &info); 9278 if( rc ) goto cleardatabasepage_out; 9279 } 9280 if( !pPage->leaf ){ 9281 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); 9282 if( rc ) goto cleardatabasepage_out; 9283 }else if( pnChange ){ 9284 assert( pPage->intKey || CORRUPT_DB ); 9285 testcase( !pPage->intKey ); 9286 *pnChange += pPage->nCell; 9287 } 9288 if( freePageFlag ){ 9289 freePage(pPage, &rc); 9290 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ 9291 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); 9292 } 9293 9294 cleardatabasepage_out: 9295 pPage->bBusy = 0; 9296 releasePage(pPage); 9297 return rc; 9298 } 9299 9300 /* 9301 ** Delete all information from a single table in the database. iTable is 9302 ** the page number of the root of the table. After this routine returns, 9303 ** the root page is empty, but still exists. 9304 ** 9305 ** This routine will fail with SQLITE_LOCKED if there are any open 9306 ** read cursors on the table. Open write cursors are moved to the 9307 ** root of the table. 9308 ** 9309 ** If pnChange is not NULL, then table iTable must be an intkey table. The 9310 ** integer value pointed to by pnChange is incremented by the number of 9311 ** entries in the table. 9312 */ 9313 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ 9314 int rc; 9315 BtShared *pBt = p->pBt; 9316 sqlite3BtreeEnter(p); 9317 assert( p->inTrans==TRANS_WRITE ); 9318 9319 rc = saveAllCursors(pBt, (Pgno)iTable, 0); 9320 9321 if( SQLITE_OK==rc ){ 9322 /* Invalidate all incrblob cursors open on table iTable (assuming iTable 9323 ** is the root of a table b-tree - if it is not, the following call is 9324 ** a no-op). */ 9325 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1); 9326 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); 9327 } 9328 sqlite3BtreeLeave(p); 9329 return rc; 9330 } 9331 9332 /* 9333 ** Delete all information from the single table that pCur is open on. 9334 ** 9335 ** This routine only work for pCur on an ephemeral table. 9336 */ 9337 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ 9338 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); 9339 } 9340 9341 /* 9342 ** Erase all information in a table and add the root of the table to 9343 ** the freelist. Except, the root of the principle table (the one on 9344 ** page 1) is never added to the freelist. 9345 ** 9346 ** This routine will fail with SQLITE_LOCKED if there are any open 9347 ** cursors on the table. 9348 ** 9349 ** If AUTOVACUUM is enabled and the page at iTable is not the last 9350 ** root page in the database file, then the last root page 9351 ** in the database file is moved into the slot formerly occupied by 9352 ** iTable and that last slot formerly occupied by the last root page 9353 ** is added to the freelist instead of iTable. In this say, all 9354 ** root pages are kept at the beginning of the database file, which 9355 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the 9356 ** page number that used to be the last root page in the file before 9357 ** the move. If no page gets moved, *piMoved is set to 0. 9358 ** The last root page is recorded in meta[3] and the value of 9359 ** meta[3] is updated by this procedure. 9360 */ 9361 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ 9362 int rc; 9363 MemPage *pPage = 0; 9364 BtShared *pBt = p->pBt; 9365 9366 assert( sqlite3BtreeHoldsMutex(p) ); 9367 assert( p->inTrans==TRANS_WRITE ); 9368 assert( iTable>=2 ); 9369 if( iTable>btreePagecount(pBt) ){ 9370 return SQLITE_CORRUPT_BKPT; 9371 } 9372 9373 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); 9374 if( rc ) return rc; 9375 rc = sqlite3BtreeClearTable(p, iTable, 0); 9376 if( rc ){ 9377 releasePage(pPage); 9378 return rc; 9379 } 9380 9381 *piMoved = 0; 9382 9383 #ifdef SQLITE_OMIT_AUTOVACUUM 9384 freePage(pPage, &rc); 9385 releasePage(pPage); 9386 #else 9387 if( pBt->autoVacuum ){ 9388 Pgno maxRootPgno; 9389 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); 9390 9391 if( iTable==maxRootPgno ){ 9392 /* If the table being dropped is the table with the largest root-page 9393 ** number in the database, put the root page on the free list. 9394 */ 9395 freePage(pPage, &rc); 9396 releasePage(pPage); 9397 if( rc!=SQLITE_OK ){ 9398 return rc; 9399 } 9400 }else{ 9401 /* The table being dropped does not have the largest root-page 9402 ** number in the database. So move the page that does into the 9403 ** gap left by the deleted root-page. 9404 */ 9405 MemPage *pMove; 9406 releasePage(pPage); 9407 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 9408 if( rc!=SQLITE_OK ){ 9409 return rc; 9410 } 9411 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); 9412 releasePage(pMove); 9413 if( rc!=SQLITE_OK ){ 9414 return rc; 9415 } 9416 pMove = 0; 9417 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); 9418 freePage(pMove, &rc); 9419 releasePage(pMove); 9420 if( rc!=SQLITE_OK ){ 9421 return rc; 9422 } 9423 *piMoved = maxRootPgno; 9424 } 9425 9426 /* Set the new 'max-root-page' value in the database header. This 9427 ** is the old value less one, less one more if that happens to 9428 ** be a root-page number, less one again if that is the 9429 ** PENDING_BYTE_PAGE. 9430 */ 9431 maxRootPgno--; 9432 while( maxRootPgno==PENDING_BYTE_PAGE(pBt) 9433 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ 9434 maxRootPgno--; 9435 } 9436 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); 9437 9438 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); 9439 }else{ 9440 freePage(pPage, &rc); 9441 releasePage(pPage); 9442 } 9443 #endif 9444 return rc; 9445 } 9446 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ 9447 int rc; 9448 sqlite3BtreeEnter(p); 9449 rc = btreeDropTable(p, iTable, piMoved); 9450 sqlite3BtreeLeave(p); 9451 return rc; 9452 } 9453 9454 9455 /* 9456 ** This function may only be called if the b-tree connection already 9457 ** has a read or write transaction open on the database. 9458 ** 9459 ** Read the meta-information out of a database file. Meta[0] 9460 ** is the number of free pages currently in the database. Meta[1] 9461 ** through meta[15] are available for use by higher layers. Meta[0] 9462 ** is read-only, the others are read/write. 9463 ** 9464 ** The schema layer numbers meta values differently. At the schema 9465 ** layer (and the SetCookie and ReadCookie opcodes) the number of 9466 ** free pages is not visible. So Cookie[0] is the same as Meta[1]. 9467 ** 9468 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead 9469 ** of reading the value out of the header, it instead loads the "DataVersion" 9470 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the 9471 ** database file. It is a number computed by the pager. But its access 9472 ** pattern is the same as header meta values, and so it is convenient to 9473 ** read it from this routine. 9474 */ 9475 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ 9476 BtShared *pBt = p->pBt; 9477 9478 sqlite3BtreeEnter(p); 9479 assert( p->inTrans>TRANS_NONE ); 9480 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) ); 9481 assert( pBt->pPage1 ); 9482 assert( idx>=0 && idx<=15 ); 9483 9484 if( idx==BTREE_DATA_VERSION ){ 9485 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; 9486 }else{ 9487 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); 9488 } 9489 9490 /* If auto-vacuum is disabled in this build and this is an auto-vacuum 9491 ** database, mark the database as read-only. */ 9492 #ifdef SQLITE_OMIT_AUTOVACUUM 9493 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ 9494 pBt->btsFlags |= BTS_READ_ONLY; 9495 } 9496 #endif 9497 9498 sqlite3BtreeLeave(p); 9499 } 9500 9501 /* 9502 ** Write meta-information back into the database. Meta[0] is 9503 ** read-only and may not be written. 9504 */ 9505 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ 9506 BtShared *pBt = p->pBt; 9507 unsigned char *pP1; 9508 int rc; 9509 assert( idx>=1 && idx<=15 ); 9510 sqlite3BtreeEnter(p); 9511 assert( p->inTrans==TRANS_WRITE ); 9512 assert( pBt->pPage1!=0 ); 9513 pP1 = pBt->pPage1->aData; 9514 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 9515 if( rc==SQLITE_OK ){ 9516 put4byte(&pP1[36 + idx*4], iMeta); 9517 #ifndef SQLITE_OMIT_AUTOVACUUM 9518 if( idx==BTREE_INCR_VACUUM ){ 9519 assert( pBt->autoVacuum || iMeta==0 ); 9520 assert( iMeta==0 || iMeta==1 ); 9521 pBt->incrVacuum = (u8)iMeta; 9522 } 9523 #endif 9524 } 9525 sqlite3BtreeLeave(p); 9526 return rc; 9527 } 9528 9529 /* 9530 ** The first argument, pCur, is a cursor opened on some b-tree. Count the 9531 ** number of entries in the b-tree and write the result to *pnEntry. 9532 ** 9533 ** SQLITE_OK is returned if the operation is successfully executed. 9534 ** Otherwise, if an error is encountered (i.e. an IO error or database 9535 ** corruption) an SQLite error code is returned. 9536 */ 9537 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){ 9538 i64 nEntry = 0; /* Value to return in *pnEntry */ 9539 int rc; /* Return code */ 9540 9541 rc = moveToRoot(pCur); 9542 if( rc==SQLITE_EMPTY ){ 9543 *pnEntry = 0; 9544 return SQLITE_OK; 9545 } 9546 9547 /* Unless an error occurs, the following loop runs one iteration for each 9548 ** page in the B-Tree structure (not including overflow pages). 9549 */ 9550 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){ 9551 int iIdx; /* Index of child node in parent */ 9552 MemPage *pPage; /* Current page of the b-tree */ 9553 9554 /* If this is a leaf page or the tree is not an int-key tree, then 9555 ** this page contains countable entries. Increment the entry counter 9556 ** accordingly. 9557 */ 9558 pPage = pCur->pPage; 9559 if( pPage->leaf || !pPage->intKey ){ 9560 nEntry += pPage->nCell; 9561 } 9562 9563 /* pPage is a leaf node. This loop navigates the cursor so that it 9564 ** points to the first interior cell that it points to the parent of 9565 ** the next page in the tree that has not yet been visited. The 9566 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell 9567 ** of the page, or to the number of cells in the page if the next page 9568 ** to visit is the right-child of its parent. 9569 ** 9570 ** If all pages in the tree have been visited, return SQLITE_OK to the 9571 ** caller. 9572 */ 9573 if( pPage->leaf ){ 9574 do { 9575 if( pCur->iPage==0 ){ 9576 /* All pages of the b-tree have been visited. Return successfully. */ 9577 *pnEntry = nEntry; 9578 return moveToRoot(pCur); 9579 } 9580 moveToParent(pCur); 9581 }while ( pCur->ix>=pCur->pPage->nCell ); 9582 9583 pCur->ix++; 9584 pPage = pCur->pPage; 9585 } 9586 9587 /* Descend to the child node of the cell that the cursor currently 9588 ** points at. This is the right-child if (iIdx==pPage->nCell). 9589 */ 9590 iIdx = pCur->ix; 9591 if( iIdx==pPage->nCell ){ 9592 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); 9593 }else{ 9594 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); 9595 } 9596 } 9597 9598 /* An error has occurred. Return an error code. */ 9599 return rc; 9600 } 9601 9602 /* 9603 ** Return the pager associated with a BTree. This routine is used for 9604 ** testing and debugging only. 9605 */ 9606 Pager *sqlite3BtreePager(Btree *p){ 9607 return p->pBt->pPager; 9608 } 9609 9610 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9611 /* 9612 ** Append a message to the error message string. 9613 */ 9614 static void checkAppendMsg( 9615 IntegrityCk *pCheck, 9616 const char *zFormat, 9617 ... 9618 ){ 9619 va_list ap; 9620 if( !pCheck->mxErr ) return; 9621 pCheck->mxErr--; 9622 pCheck->nErr++; 9623 va_start(ap, zFormat); 9624 if( pCheck->errMsg.nChar ){ 9625 sqlite3_str_append(&pCheck->errMsg, "\n", 1); 9626 } 9627 if( pCheck->zPfx ){ 9628 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); 9629 } 9630 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap); 9631 va_end(ap); 9632 if( pCheck->errMsg.accError==SQLITE_NOMEM ){ 9633 pCheck->mallocFailed = 1; 9634 } 9635 } 9636 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 9637 9638 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9639 9640 /* 9641 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that 9642 ** corresponds to page iPg is already set. 9643 */ 9644 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 9645 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 9646 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); 9647 } 9648 9649 /* 9650 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. 9651 */ 9652 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ 9653 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); 9654 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); 9655 } 9656 9657 9658 /* 9659 ** Add 1 to the reference count for page iPage. If this is the second 9660 ** reference to the page, add an error message to pCheck->zErrMsg. 9661 ** Return 1 if there are 2 or more references to the page and 0 if 9662 ** if this is the first reference to the page. 9663 ** 9664 ** Also check that the page number is in bounds. 9665 */ 9666 static int checkRef(IntegrityCk *pCheck, Pgno iPage){ 9667 if( iPage>pCheck->nPage || iPage==0 ){ 9668 checkAppendMsg(pCheck, "invalid page number %d", iPage); 9669 return 1; 9670 } 9671 if( getPageReferenced(pCheck, iPage) ){ 9672 checkAppendMsg(pCheck, "2nd reference to page %d", iPage); 9673 return 1; 9674 } 9675 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1; 9676 setPageReferenced(pCheck, iPage); 9677 return 0; 9678 } 9679 9680 #ifndef SQLITE_OMIT_AUTOVACUUM 9681 /* 9682 ** Check that the entry in the pointer-map for page iChild maps to 9683 ** page iParent, pointer type ptrType. If not, append an error message 9684 ** to pCheck. 9685 */ 9686 static void checkPtrmap( 9687 IntegrityCk *pCheck, /* Integrity check context */ 9688 Pgno iChild, /* Child page number */ 9689 u8 eType, /* Expected pointer map type */ 9690 Pgno iParent /* Expected pointer map parent page number */ 9691 ){ 9692 int rc; 9693 u8 ePtrmapType; 9694 Pgno iPtrmapParent; 9695 9696 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); 9697 if( rc!=SQLITE_OK ){ 9698 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; 9699 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); 9700 return; 9701 } 9702 9703 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ 9704 checkAppendMsg(pCheck, 9705 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 9706 iChild, eType, iParent, ePtrmapType, iPtrmapParent); 9707 } 9708 } 9709 #endif 9710 9711 /* 9712 ** Check the integrity of the freelist or of an overflow page list. 9713 ** Verify that the number of pages on the list is N. 9714 */ 9715 static void checkList( 9716 IntegrityCk *pCheck, /* Integrity checking context */ 9717 int isFreeList, /* True for a freelist. False for overflow page list */ 9718 int iPage, /* Page number for first page in the list */ 9719 u32 N /* Expected number of pages in the list */ 9720 ){ 9721 int i; 9722 u32 expected = N; 9723 int nErrAtStart = pCheck->nErr; 9724 while( iPage!=0 && pCheck->mxErr ){ 9725 DbPage *pOvflPage; 9726 unsigned char *pOvflData; 9727 if( checkRef(pCheck, iPage) ) break; 9728 N--; 9729 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ 9730 checkAppendMsg(pCheck, "failed to get page %d", iPage); 9731 break; 9732 } 9733 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); 9734 if( isFreeList ){ 9735 u32 n = (u32)get4byte(&pOvflData[4]); 9736 #ifndef SQLITE_OMIT_AUTOVACUUM 9737 if( pCheck->pBt->autoVacuum ){ 9738 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); 9739 } 9740 #endif 9741 if( n>pCheck->pBt->usableSize/4-2 ){ 9742 checkAppendMsg(pCheck, 9743 "freelist leaf count too big on page %d", iPage); 9744 N--; 9745 }else{ 9746 for(i=0; i<(int)n; i++){ 9747 Pgno iFreePage = get4byte(&pOvflData[8+i*4]); 9748 #ifndef SQLITE_OMIT_AUTOVACUUM 9749 if( pCheck->pBt->autoVacuum ){ 9750 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); 9751 } 9752 #endif 9753 checkRef(pCheck, iFreePage); 9754 } 9755 N -= n; 9756 } 9757 } 9758 #ifndef SQLITE_OMIT_AUTOVACUUM 9759 else{ 9760 /* If this database supports auto-vacuum and iPage is not the last 9761 ** page in this overflow list, check that the pointer-map entry for 9762 ** the following page matches iPage. 9763 */ 9764 if( pCheck->pBt->autoVacuum && N>0 ){ 9765 i = get4byte(pOvflData); 9766 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); 9767 } 9768 } 9769 #endif 9770 iPage = get4byte(pOvflData); 9771 sqlite3PagerUnref(pOvflPage); 9772 } 9773 if( N && nErrAtStart==pCheck->nErr ){ 9774 checkAppendMsg(pCheck, 9775 "%s is %d but should be %d", 9776 isFreeList ? "size" : "overflow list length", 9777 expected-N, expected); 9778 } 9779 } 9780 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 9781 9782 /* 9783 ** An implementation of a min-heap. 9784 ** 9785 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the 9786 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] 9787 ** and aHeap[N*2+1]. 9788 ** 9789 ** The heap property is this: Every node is less than or equal to both 9790 ** of its daughter nodes. A consequence of the heap property is that the 9791 ** root node aHeap[1] is always the minimum value currently in the heap. 9792 ** 9793 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto 9794 ** the heap, preserving the heap property. The btreeHeapPull() routine 9795 ** removes the root element from the heap (the minimum value in the heap) 9796 ** and then moves other nodes around as necessary to preserve the heap 9797 ** property. 9798 ** 9799 ** This heap is used for cell overlap and coverage testing. Each u32 9800 ** entry represents the span of a cell or freeblock on a btree page. 9801 ** The upper 16 bits are the index of the first byte of a range and the 9802 ** lower 16 bits are the index of the last byte of that range. 9803 */ 9804 static void btreeHeapInsert(u32 *aHeap, u32 x){ 9805 u32 j, i = ++aHeap[0]; 9806 aHeap[i] = x; 9807 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ 9808 x = aHeap[j]; 9809 aHeap[j] = aHeap[i]; 9810 aHeap[i] = x; 9811 i = j; 9812 } 9813 } 9814 static int btreeHeapPull(u32 *aHeap, u32 *pOut){ 9815 u32 j, i, x; 9816 if( (x = aHeap[0])==0 ) return 0; 9817 *pOut = aHeap[1]; 9818 aHeap[1] = aHeap[x]; 9819 aHeap[x] = 0xffffffff; 9820 aHeap[0]--; 9821 i = 1; 9822 while( (j = i*2)<=aHeap[0] ){ 9823 if( aHeap[j]>aHeap[j+1] ) j++; 9824 if( aHeap[i]<aHeap[j] ) break; 9825 x = aHeap[i]; 9826 aHeap[i] = aHeap[j]; 9827 aHeap[j] = x; 9828 i = j; 9829 } 9830 return 1; 9831 } 9832 9833 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 9834 /* 9835 ** Do various sanity checks on a single page of a tree. Return 9836 ** the tree depth. Root pages return 0. Parents of root pages 9837 ** return 1, and so forth. 9838 ** 9839 ** These checks are done: 9840 ** 9841 ** 1. Make sure that cells and freeblocks do not overlap 9842 ** but combine to completely cover the page. 9843 ** 2. Make sure integer cell keys are in order. 9844 ** 3. Check the integrity of overflow pages. 9845 ** 4. Recursively call checkTreePage on all children. 9846 ** 5. Verify that the depth of all children is the same. 9847 */ 9848 static int checkTreePage( 9849 IntegrityCk *pCheck, /* Context for the sanity check */ 9850 int iPage, /* Page number of the page to check */ 9851 i64 *piMinKey, /* Write minimum integer primary key here */ 9852 i64 maxKey /* Error if integer primary key greater than this */ 9853 ){ 9854 MemPage *pPage = 0; /* The page being analyzed */ 9855 int i; /* Loop counter */ 9856 int rc; /* Result code from subroutine call */ 9857 int depth = -1, d2; /* Depth of a subtree */ 9858 int pgno; /* Page number */ 9859 int nFrag; /* Number of fragmented bytes on the page */ 9860 int hdr; /* Offset to the page header */ 9861 int cellStart; /* Offset to the start of the cell pointer array */ 9862 int nCell; /* Number of cells */ 9863 int doCoverageCheck = 1; /* True if cell coverage checking should be done */ 9864 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey 9865 ** False if IPK must be strictly less than maxKey */ 9866 u8 *data; /* Page content */ 9867 u8 *pCell; /* Cell content */ 9868 u8 *pCellIdx; /* Next element of the cell pointer array */ 9869 BtShared *pBt; /* The BtShared object that owns pPage */ 9870 u32 pc; /* Address of a cell */ 9871 u32 usableSize; /* Usable size of the page */ 9872 u32 contentOffset; /* Offset to the start of the cell content area */ 9873 u32 *heap = 0; /* Min-heap used for checking cell coverage */ 9874 u32 x, prev = 0; /* Next and previous entry on the min-heap */ 9875 const char *saved_zPfx = pCheck->zPfx; 9876 int saved_v1 = pCheck->v1; 9877 int saved_v2 = pCheck->v2; 9878 u8 savedIsInit = 0; 9879 9880 /* Check that the page exists 9881 */ 9882 pBt = pCheck->pBt; 9883 usableSize = pBt->usableSize; 9884 if( iPage==0 ) return 0; 9885 if( checkRef(pCheck, iPage) ) return 0; 9886 pCheck->zPfx = "Page %d: "; 9887 pCheck->v1 = iPage; 9888 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ 9889 checkAppendMsg(pCheck, 9890 "unable to get the page. error code=%d", rc); 9891 goto end_of_check; 9892 } 9893 9894 /* Clear MemPage.isInit to make sure the corruption detection code in 9895 ** btreeInitPage() is executed. */ 9896 savedIsInit = pPage->isInit; 9897 pPage->isInit = 0; 9898 if( (rc = btreeInitPage(pPage))!=0 ){ 9899 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ 9900 checkAppendMsg(pCheck, 9901 "btreeInitPage() returns error code %d", rc); 9902 goto end_of_check; 9903 } 9904 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){ 9905 assert( rc==SQLITE_CORRUPT ); 9906 checkAppendMsg(pCheck, "free space corruption", rc); 9907 goto end_of_check; 9908 } 9909 data = pPage->aData; 9910 hdr = pPage->hdrOffset; 9911 9912 /* Set up for cell analysis */ 9913 pCheck->zPfx = "On tree page %d cell %d: "; 9914 contentOffset = get2byteNotZero(&data[hdr+5]); 9915 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ 9916 9917 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the 9918 ** number of cells on the page. */ 9919 nCell = get2byte(&data[hdr+3]); 9920 assert( pPage->nCell==nCell ); 9921 9922 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page 9923 ** immediately follows the b-tree page header. */ 9924 cellStart = hdr + 12 - 4*pPage->leaf; 9925 assert( pPage->aCellIdx==&data[cellStart] ); 9926 pCellIdx = &data[cellStart + 2*(nCell-1)]; 9927 9928 if( !pPage->leaf ){ 9929 /* Analyze the right-child page of internal pages */ 9930 pgno = get4byte(&data[hdr+8]); 9931 #ifndef SQLITE_OMIT_AUTOVACUUM 9932 if( pBt->autoVacuum ){ 9933 pCheck->zPfx = "On page %d at right child: "; 9934 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 9935 } 9936 #endif 9937 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); 9938 keyCanBeEqual = 0; 9939 }else{ 9940 /* For leaf pages, the coverage check will occur in the same loop 9941 ** as the other cell checks, so initialize the heap. */ 9942 heap = pCheck->heap; 9943 heap[0] = 0; 9944 } 9945 9946 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte 9947 ** integer offsets to the cell contents. */ 9948 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ 9949 CellInfo info; 9950 9951 /* Check cell size */ 9952 pCheck->v2 = i; 9953 assert( pCellIdx==&data[cellStart + i*2] ); 9954 pc = get2byteAligned(pCellIdx); 9955 pCellIdx -= 2; 9956 if( pc<contentOffset || pc>usableSize-4 ){ 9957 checkAppendMsg(pCheck, "Offset %d out of range %d..%d", 9958 pc, contentOffset, usableSize-4); 9959 doCoverageCheck = 0; 9960 continue; 9961 } 9962 pCell = &data[pc]; 9963 pPage->xParseCell(pPage, pCell, &info); 9964 if( pc+info.nSize>usableSize ){ 9965 checkAppendMsg(pCheck, "Extends off end of page"); 9966 doCoverageCheck = 0; 9967 continue; 9968 } 9969 9970 /* Check for integer primary key out of range */ 9971 if( pPage->intKey ){ 9972 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ 9973 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); 9974 } 9975 maxKey = info.nKey; 9976 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */ 9977 } 9978 9979 /* Check the content overflow list */ 9980 if( info.nPayload>info.nLocal ){ 9981 u32 nPage; /* Number of pages on the overflow chain */ 9982 Pgno pgnoOvfl; /* First page of the overflow chain */ 9983 assert( pc + info.nSize - 4 <= usableSize ); 9984 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); 9985 pgnoOvfl = get4byte(&pCell[info.nSize - 4]); 9986 #ifndef SQLITE_OMIT_AUTOVACUUM 9987 if( pBt->autoVacuum ){ 9988 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); 9989 } 9990 #endif 9991 checkList(pCheck, 0, pgnoOvfl, nPage); 9992 } 9993 9994 if( !pPage->leaf ){ 9995 /* Check sanity of left child page for internal pages */ 9996 pgno = get4byte(pCell); 9997 #ifndef SQLITE_OMIT_AUTOVACUUM 9998 if( pBt->autoVacuum ){ 9999 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); 10000 } 10001 #endif 10002 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); 10003 keyCanBeEqual = 0; 10004 if( d2!=depth ){ 10005 checkAppendMsg(pCheck, "Child page depth differs"); 10006 depth = d2; 10007 } 10008 }else{ 10009 /* Populate the coverage-checking heap for leaf pages */ 10010 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); 10011 } 10012 } 10013 *piMinKey = maxKey; 10014 10015 /* Check for complete coverage of the page 10016 */ 10017 pCheck->zPfx = 0; 10018 if( doCoverageCheck && pCheck->mxErr>0 ){ 10019 /* For leaf pages, the min-heap has already been initialized and the 10020 ** cells have already been inserted. But for internal pages, that has 10021 ** not yet been done, so do it now */ 10022 if( !pPage->leaf ){ 10023 heap = pCheck->heap; 10024 heap[0] = 0; 10025 for(i=nCell-1; i>=0; i--){ 10026 u32 size; 10027 pc = get2byteAligned(&data[cellStart+i*2]); 10028 size = pPage->xCellSize(pPage, &data[pc]); 10029 btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); 10030 } 10031 } 10032 /* Add the freeblocks to the min-heap 10033 ** 10034 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header 10035 ** is the offset of the first freeblock, or zero if there are no 10036 ** freeblocks on the page. 10037 */ 10038 i = get2byte(&data[hdr+1]); 10039 while( i>0 ){ 10040 int size, j; 10041 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ 10042 size = get2byte(&data[i+2]); 10043 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */ 10044 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); 10045 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a 10046 ** big-endian integer which is the offset in the b-tree page of the next 10047 ** freeblock in the chain, or zero if the freeblock is the last on the 10048 ** chain. */ 10049 j = get2byte(&data[i]); 10050 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of 10051 ** increasing offset. */ 10052 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */ 10053 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ 10054 i = j; 10055 } 10056 /* Analyze the min-heap looking for overlap between cells and/or 10057 ** freeblocks, and counting the number of untracked bytes in nFrag. 10058 ** 10059 ** Each min-heap entry is of the form: (start_address<<16)|end_address. 10060 ** There is an implied first entry the covers the page header, the cell 10061 ** pointer index, and the gap between the cell pointer index and the start 10062 ** of cell content. 10063 ** 10064 ** The loop below pulls entries from the min-heap in order and compares 10065 ** the start_address against the previous end_address. If there is an 10066 ** overlap, that means bytes are used multiple times. If there is a gap, 10067 ** that gap is added to the fragmentation count. 10068 */ 10069 nFrag = 0; 10070 prev = contentOffset - 1; /* Implied first min-heap entry */ 10071 while( btreeHeapPull(heap,&x) ){ 10072 if( (prev&0xffff)>=(x>>16) ){ 10073 checkAppendMsg(pCheck, 10074 "Multiple uses for byte %u of page %d", x>>16, iPage); 10075 break; 10076 }else{ 10077 nFrag += (x>>16) - (prev&0xffff) - 1; 10078 prev = x; 10079 } 10080 } 10081 nFrag += usableSize - (prev&0xffff) - 1; 10082 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments 10083 ** is stored in the fifth field of the b-tree page header. 10084 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the 10085 ** number of fragmented free bytes within the cell content area. 10086 */ 10087 if( heap[0]==0 && nFrag!=data[hdr+7] ){ 10088 checkAppendMsg(pCheck, 10089 "Fragmentation of %d bytes reported as %d on page %d", 10090 nFrag, data[hdr+7], iPage); 10091 } 10092 } 10093 10094 end_of_check: 10095 if( !doCoverageCheck ) pPage->isInit = savedIsInit; 10096 releasePage(pPage); 10097 pCheck->zPfx = saved_zPfx; 10098 pCheck->v1 = saved_v1; 10099 pCheck->v2 = saved_v2; 10100 return depth+1; 10101 } 10102 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 10103 10104 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 10105 /* 10106 ** This routine does a complete check of the given BTree file. aRoot[] is 10107 ** an array of pages numbers were each page number is the root page of 10108 ** a table. nRoot is the number of entries in aRoot. 10109 ** 10110 ** A read-only or read-write transaction must be opened before calling 10111 ** this function. 10112 ** 10113 ** Write the number of error seen in *pnErr. Except for some memory 10114 ** allocation errors, an error message held in memory obtained from 10115 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is 10116 ** returned. If a memory allocation error occurs, NULL is returned. 10117 */ 10118 char *sqlite3BtreeIntegrityCheck( 10119 sqlite3 *db, /* Database connection that is running the check */ 10120 Btree *p, /* The btree to be checked */ 10121 int *aRoot, /* An array of root pages numbers for individual trees */ 10122 int nRoot, /* Number of entries in aRoot[] */ 10123 int mxErr, /* Stop reporting errors after this many */ 10124 int *pnErr /* Write number of errors seen to this variable */ 10125 ){ 10126 Pgno i; 10127 IntegrityCk sCheck; 10128 BtShared *pBt = p->pBt; 10129 u64 savedDbFlags = pBt->db->flags; 10130 char zErr[100]; 10131 VVA_ONLY( int nRef ); 10132 10133 sqlite3BtreeEnter(p); 10134 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); 10135 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); 10136 assert( nRef>=0 ); 10137 sCheck.db = db; 10138 sCheck.pBt = pBt; 10139 sCheck.pPager = pBt->pPager; 10140 sCheck.nPage = btreePagecount(sCheck.pBt); 10141 sCheck.mxErr = mxErr; 10142 sCheck.nErr = 0; 10143 sCheck.mallocFailed = 0; 10144 sCheck.zPfx = 0; 10145 sCheck.v1 = 0; 10146 sCheck.v2 = 0; 10147 sCheck.aPgRef = 0; 10148 sCheck.heap = 0; 10149 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); 10150 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; 10151 if( sCheck.nPage==0 ){ 10152 goto integrity_ck_cleanup; 10153 } 10154 10155 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); 10156 if( !sCheck.aPgRef ){ 10157 sCheck.mallocFailed = 1; 10158 goto integrity_ck_cleanup; 10159 } 10160 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); 10161 if( sCheck.heap==0 ){ 10162 sCheck.mallocFailed = 1; 10163 goto integrity_ck_cleanup; 10164 } 10165 10166 i = PENDING_BYTE_PAGE(pBt); 10167 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); 10168 10169 /* Check the integrity of the freelist 10170 */ 10171 sCheck.zPfx = "Main freelist: "; 10172 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), 10173 get4byte(&pBt->pPage1->aData[36])); 10174 sCheck.zPfx = 0; 10175 10176 /* Check all the tables. 10177 */ 10178 #ifndef SQLITE_OMIT_AUTOVACUUM 10179 if( pBt->autoVacuum ){ 10180 int mx = 0; 10181 int mxInHdr; 10182 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i]; 10183 mxInHdr = get4byte(&pBt->pPage1->aData[52]); 10184 if( mx!=mxInHdr ){ 10185 checkAppendMsg(&sCheck, 10186 "max rootpage (%d) disagrees with header (%d)", 10187 mx, mxInHdr 10188 ); 10189 } 10190 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){ 10191 checkAppendMsg(&sCheck, 10192 "incremental_vacuum enabled with a max rootpage of zero" 10193 ); 10194 } 10195 #endif 10196 testcase( pBt->db->flags & SQLITE_CellSizeCk ); 10197 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk; 10198 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ 10199 i64 notUsed; 10200 if( aRoot[i]==0 ) continue; 10201 #ifndef SQLITE_OMIT_AUTOVACUUM 10202 if( pBt->autoVacuum && aRoot[i]>1 ){ 10203 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); 10204 } 10205 #endif 10206 checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64); 10207 } 10208 pBt->db->flags = savedDbFlags; 10209 10210 /* Make sure every page in the file is referenced 10211 */ 10212 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ 10213 #ifdef SQLITE_OMIT_AUTOVACUUM 10214 if( getPageReferenced(&sCheck, i)==0 ){ 10215 checkAppendMsg(&sCheck, "Page %d is never used", i); 10216 } 10217 #else 10218 /* If the database supports auto-vacuum, make sure no tables contain 10219 ** references to pointer-map pages. 10220 */ 10221 if( getPageReferenced(&sCheck, i)==0 && 10222 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ 10223 checkAppendMsg(&sCheck, "Page %d is never used", i); 10224 } 10225 if( getPageReferenced(&sCheck, i)!=0 && 10226 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ 10227 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); 10228 } 10229 #endif 10230 } 10231 10232 /* Clean up and report errors. 10233 */ 10234 integrity_ck_cleanup: 10235 sqlite3PageFree(sCheck.heap); 10236 sqlite3_free(sCheck.aPgRef); 10237 if( sCheck.mallocFailed ){ 10238 sqlite3_str_reset(&sCheck.errMsg); 10239 sCheck.nErr++; 10240 } 10241 *pnErr = sCheck.nErr; 10242 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg); 10243 /* Make sure this analysis did not leave any unref() pages. */ 10244 assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); 10245 sqlite3BtreeLeave(p); 10246 return sqlite3StrAccumFinish(&sCheck.errMsg); 10247 } 10248 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 10249 10250 /* 10251 ** Return the full pathname of the underlying database file. Return 10252 ** an empty string if the database is in-memory or a TEMP database. 10253 ** 10254 ** The pager filename is invariant as long as the pager is 10255 ** open so it is safe to access without the BtShared mutex. 10256 */ 10257 const char *sqlite3BtreeGetFilename(Btree *p){ 10258 assert( p->pBt->pPager!=0 ); 10259 return sqlite3PagerFilename(p->pBt->pPager, 1); 10260 } 10261 10262 /* 10263 ** Return the pathname of the journal file for this database. The return 10264 ** value of this routine is the same regardless of whether the journal file 10265 ** has been created or not. 10266 ** 10267 ** The pager journal filename is invariant as long as the pager is 10268 ** open so it is safe to access without the BtShared mutex. 10269 */ 10270 const char *sqlite3BtreeGetJournalname(Btree *p){ 10271 assert( p->pBt->pPager!=0 ); 10272 return sqlite3PagerJournalname(p->pBt->pPager); 10273 } 10274 10275 /* 10276 ** Return non-zero if a transaction is active. 10277 */ 10278 int sqlite3BtreeIsInTrans(Btree *p){ 10279 assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); 10280 return (p && (p->inTrans==TRANS_WRITE)); 10281 } 10282 10283 #ifndef SQLITE_OMIT_WAL 10284 /* 10285 ** Run a checkpoint on the Btree passed as the first argument. 10286 ** 10287 ** Return SQLITE_LOCKED if this or any other connection has an open 10288 ** transaction on the shared-cache the argument Btree is connected to. 10289 ** 10290 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. 10291 */ 10292 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ 10293 int rc = SQLITE_OK; 10294 if( p ){ 10295 BtShared *pBt = p->pBt; 10296 sqlite3BtreeEnter(p); 10297 if( pBt->inTransaction!=TRANS_NONE ){ 10298 rc = SQLITE_LOCKED; 10299 }else{ 10300 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); 10301 } 10302 sqlite3BtreeLeave(p); 10303 } 10304 return rc; 10305 } 10306 #endif 10307 10308 /* 10309 ** Return non-zero if a read (or write) transaction is active. 10310 */ 10311 int sqlite3BtreeIsInReadTrans(Btree *p){ 10312 assert( p ); 10313 assert( sqlite3_mutex_held(p->db->mutex) ); 10314 return p->inTrans!=TRANS_NONE; 10315 } 10316 10317 int sqlite3BtreeIsInBackup(Btree *p){ 10318 assert( p ); 10319 assert( sqlite3_mutex_held(p->db->mutex) ); 10320 return p->nBackup!=0; 10321 } 10322 10323 /* 10324 ** This function returns a pointer to a blob of memory associated with 10325 ** a single shared-btree. The memory is used by client code for its own 10326 ** purposes (for example, to store a high-level schema associated with 10327 ** the shared-btree). The btree layer manages reference counting issues. 10328 ** 10329 ** The first time this is called on a shared-btree, nBytes bytes of memory 10330 ** are allocated, zeroed, and returned to the caller. For each subsequent 10331 ** call the nBytes parameter is ignored and a pointer to the same blob 10332 ** of memory returned. 10333 ** 10334 ** If the nBytes parameter is 0 and the blob of memory has not yet been 10335 ** allocated, a null pointer is returned. If the blob has already been 10336 ** allocated, it is returned as normal. 10337 ** 10338 ** Just before the shared-btree is closed, the function passed as the 10339 ** xFree argument when the memory allocation was made is invoked on the 10340 ** blob of allocated memory. The xFree function should not call sqlite3_free() 10341 ** on the memory, the btree layer does that. 10342 */ 10343 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ 10344 BtShared *pBt = p->pBt; 10345 sqlite3BtreeEnter(p); 10346 if( !pBt->pSchema && nBytes ){ 10347 pBt->pSchema = sqlite3DbMallocZero(0, nBytes); 10348 pBt->xFreeSchema = xFree; 10349 } 10350 sqlite3BtreeLeave(p); 10351 return pBt->pSchema; 10352 } 10353 10354 /* 10355 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 10356 ** btree as the argument handle holds an exclusive lock on the 10357 ** sqlite_master table. Otherwise SQLITE_OK. 10358 */ 10359 int sqlite3BtreeSchemaLocked(Btree *p){ 10360 int rc; 10361 assert( sqlite3_mutex_held(p->db->mutex) ); 10362 sqlite3BtreeEnter(p); 10363 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); 10364 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); 10365 sqlite3BtreeLeave(p); 10366 return rc; 10367 } 10368 10369 10370 #ifndef SQLITE_OMIT_SHARED_CACHE 10371 /* 10372 ** Obtain a lock on the table whose root page is iTab. The 10373 ** lock is a write lock if isWritelock is true or a read lock 10374 ** if it is false. 10375 */ 10376 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ 10377 int rc = SQLITE_OK; 10378 assert( p->inTrans!=TRANS_NONE ); 10379 if( p->sharable ){ 10380 u8 lockType = READ_LOCK + isWriteLock; 10381 assert( READ_LOCK+1==WRITE_LOCK ); 10382 assert( isWriteLock==0 || isWriteLock==1 ); 10383 10384 sqlite3BtreeEnter(p); 10385 rc = querySharedCacheTableLock(p, iTab, lockType); 10386 if( rc==SQLITE_OK ){ 10387 rc = setSharedCacheTableLock(p, iTab, lockType); 10388 } 10389 sqlite3BtreeLeave(p); 10390 } 10391 return rc; 10392 } 10393 #endif 10394 10395 #ifndef SQLITE_OMIT_INCRBLOB 10396 /* 10397 ** Argument pCsr must be a cursor opened for writing on an 10398 ** INTKEY table currently pointing at a valid table entry. 10399 ** This function modifies the data stored as part of that entry. 10400 ** 10401 ** Only the data content may only be modified, it is not possible to 10402 ** change the length of the data stored. If this function is called with 10403 ** parameters that attempt to write past the end of the existing data, 10404 ** no modifications are made and SQLITE_CORRUPT is returned. 10405 */ 10406 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ 10407 int rc; 10408 assert( cursorOwnsBtShared(pCsr) ); 10409 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); 10410 assert( pCsr->curFlags & BTCF_Incrblob ); 10411 10412 rc = restoreCursorPosition(pCsr); 10413 if( rc!=SQLITE_OK ){ 10414 return rc; 10415 } 10416 assert( pCsr->eState!=CURSOR_REQUIRESEEK ); 10417 if( pCsr->eState!=CURSOR_VALID ){ 10418 return SQLITE_ABORT; 10419 } 10420 10421 /* Save the positions of all other cursors open on this table. This is 10422 ** required in case any of them are holding references to an xFetch 10423 ** version of the b-tree page modified by the accessPayload call below. 10424 ** 10425 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() 10426 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence 10427 ** saveAllCursors can only return SQLITE_OK. 10428 */ 10429 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); 10430 assert( rc==SQLITE_OK ); 10431 10432 /* Check some assumptions: 10433 ** (a) the cursor is open for writing, 10434 ** (b) there is a read/write transaction open, 10435 ** (c) the connection holds a write-lock on the table (if required), 10436 ** (d) there are no conflicting read-locks, and 10437 ** (e) the cursor points at a valid row of an intKey table. 10438 */ 10439 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ 10440 return SQLITE_READONLY; 10441 } 10442 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 10443 && pCsr->pBt->inTransaction==TRANS_WRITE ); 10444 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); 10445 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); 10446 assert( pCsr->pPage->intKey ); 10447 10448 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); 10449 } 10450 10451 /* 10452 ** Mark this cursor as an incremental blob cursor. 10453 */ 10454 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ 10455 pCur->curFlags |= BTCF_Incrblob; 10456 pCur->pBtree->hasIncrblobCur = 1; 10457 } 10458 #endif 10459 10460 /* 10461 ** Set both the "read version" (single byte at byte offset 18) and 10462 ** "write version" (single byte at byte offset 19) fields in the database 10463 ** header to iVersion. 10464 */ 10465 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ 10466 BtShared *pBt = pBtree->pBt; 10467 int rc; /* Return code */ 10468 10469 assert( iVersion==1 || iVersion==2 ); 10470 10471 /* If setting the version fields to 1, do not automatically open the 10472 ** WAL connection, even if the version fields are currently set to 2. 10473 */ 10474 pBt->btsFlags &= ~BTS_NO_WAL; 10475 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; 10476 10477 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0); 10478 if( rc==SQLITE_OK ){ 10479 u8 *aData = pBt->pPage1->aData; 10480 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ 10481 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0); 10482 if( rc==SQLITE_OK ){ 10483 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); 10484 if( rc==SQLITE_OK ){ 10485 aData[18] = (u8)iVersion; 10486 aData[19] = (u8)iVersion; 10487 } 10488 } 10489 } 10490 } 10491 10492 pBt->btsFlags &= ~BTS_NO_WAL; 10493 return rc; 10494 } 10495 10496 /* 10497 ** Return true if the cursor has a hint specified. This routine is 10498 ** only used from within assert() statements 10499 */ 10500 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ 10501 return (pCsr->hints & mask)!=0; 10502 } 10503 10504 /* 10505 ** Return true if the given Btree is read-only. 10506 */ 10507 int sqlite3BtreeIsReadonly(Btree *p){ 10508 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; 10509 } 10510 10511 /* 10512 ** Return the size of the header added to each page by this module. 10513 */ 10514 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } 10515 10516 #if !defined(SQLITE_OMIT_SHARED_CACHE) 10517 /* 10518 ** Return true if the Btree passed as the only argument is sharable. 10519 */ 10520 int sqlite3BtreeSharable(Btree *p){ 10521 return p->sharable; 10522 } 10523 10524 /* 10525 ** Return the number of connections to the BtShared object accessed by 10526 ** the Btree handle passed as the only argument. For private caches 10527 ** this is always 1. For shared caches it may be 1 or greater. 10528 */ 10529 int sqlite3BtreeConnectionCount(Btree *p){ 10530 testcase( p->sharable ); 10531 return p->pBt->nRef; 10532 } 10533 #endif 10534