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