xref: /sqlite-3.40.0/src/btree.c (revision b80bb6ce)
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( (pBt->db->flags & SQLITE_WriteSchema)==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   /* Write transactions are not possible on a read-only database */
3320   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3321     rc = SQLITE_READONLY;
3322     goto trans_begun;
3323   }
3324 
3325 #ifndef SQLITE_OMIT_SHARED_CACHE
3326   {
3327     sqlite3 *pBlock = 0;
3328     /* If another database handle has already opened a write transaction
3329     ** on this shared-btree structure and a second write transaction is
3330     ** requested, return SQLITE_LOCKED.
3331     */
3332     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3333      || (pBt->btsFlags & BTS_PENDING)!=0
3334     ){
3335       pBlock = pBt->pWriter->db;
3336     }else if( wrflag>1 ){
3337       BtLock *pIter;
3338       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3339         if( pIter->pBtree!=p ){
3340           pBlock = pIter->pBtree->db;
3341           break;
3342         }
3343       }
3344     }
3345     if( pBlock ){
3346       sqlite3ConnectionBlocked(p->db, pBlock);
3347       rc = SQLITE_LOCKED_SHAREDCACHE;
3348       goto trans_begun;
3349     }
3350   }
3351 #endif
3352 
3353   /* Any read-only or read-write transaction implies a read-lock on
3354   ** page 1. So if some other shared-cache client already has a write-lock
3355   ** on page 1, the transaction cannot be opened. */
3356   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
3357   if( SQLITE_OK!=rc ) goto trans_begun;
3358 
3359   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3360   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3361   do {
3362     /* Call lockBtree() until either pBt->pPage1 is populated or
3363     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3364     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3365     ** reading page 1 it discovers that the page-size of the database
3366     ** file is not pBt->pageSize. In this case lockBtree() will update
3367     ** pBt->pageSize to the page-size of the file on disk.
3368     */
3369     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3370 
3371     if( rc==SQLITE_OK && wrflag ){
3372       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3373         rc = SQLITE_READONLY;
3374       }else{
3375         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
3376         if( rc==SQLITE_OK ){
3377           rc = newDatabase(pBt);
3378         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3379           /* if there was no transaction opened when this function was
3380           ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3381           ** code to SQLITE_BUSY. */
3382           rc = SQLITE_BUSY;
3383         }
3384       }
3385     }
3386 
3387     if( rc!=SQLITE_OK ){
3388       unlockBtreeIfUnused(pBt);
3389     }
3390   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3391           btreeInvokeBusyHandler(pBt) );
3392   sqlite3PagerResetLockTimeout(pBt->pPager);
3393 
3394   if( rc==SQLITE_OK ){
3395     if( p->inTrans==TRANS_NONE ){
3396       pBt->nTransaction++;
3397 #ifndef SQLITE_OMIT_SHARED_CACHE
3398       if( p->sharable ){
3399         assert( p->lock.pBtree==p && p->lock.iTable==1 );
3400         p->lock.eLock = READ_LOCK;
3401         p->lock.pNext = pBt->pLock;
3402         pBt->pLock = &p->lock;
3403       }
3404 #endif
3405     }
3406     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3407     if( p->inTrans>pBt->inTransaction ){
3408       pBt->inTransaction = p->inTrans;
3409     }
3410     if( wrflag ){
3411       MemPage *pPage1 = pBt->pPage1;
3412 #ifndef SQLITE_OMIT_SHARED_CACHE
3413       assert( !pBt->pWriter );
3414       pBt->pWriter = p;
3415       pBt->btsFlags &= ~BTS_EXCLUSIVE;
3416       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3417 #endif
3418 
3419       /* If the db-size header field is incorrect (as it may be if an old
3420       ** client has been writing the database file), update it now. Doing
3421       ** this sooner rather than later means the database size can safely
3422       ** re-read the database size from page 1 if a savepoint or transaction
3423       ** rollback occurs within the transaction.
3424       */
3425       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3426         rc = sqlite3PagerWrite(pPage1->pDbPage);
3427         if( rc==SQLITE_OK ){
3428           put4byte(&pPage1->aData[28], pBt->nPage);
3429         }
3430       }
3431     }
3432   }
3433 
3434 trans_begun:
3435   if( rc==SQLITE_OK ){
3436     if( pSchemaVersion ){
3437       *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3438     }
3439     if( wrflag ){
3440       /* This call makes sure that the pager has the correct number of
3441       ** open savepoints. If the second parameter is greater than 0 and
3442       ** the sub-journal is not already open, then it will be opened here.
3443       */
3444       rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3445     }
3446   }
3447 
3448   btreeIntegrity(p);
3449   sqlite3BtreeLeave(p);
3450   return rc;
3451 }
3452 
3453 #ifndef SQLITE_OMIT_AUTOVACUUM
3454 
3455 /*
3456 ** Set the pointer-map entries for all children of page pPage. Also, if
3457 ** pPage contains cells that point to overflow pages, set the pointer
3458 ** map entries for the overflow pages as well.
3459 */
3460 static int setChildPtrmaps(MemPage *pPage){
3461   int i;                             /* Counter variable */
3462   int nCell;                         /* Number of cells in page pPage */
3463   int rc;                            /* Return code */
3464   BtShared *pBt = pPage->pBt;
3465   Pgno pgno = pPage->pgno;
3466 
3467   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3468   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3469   if( rc!=SQLITE_OK ) return rc;
3470   nCell = pPage->nCell;
3471 
3472   for(i=0; i<nCell; i++){
3473     u8 *pCell = findCell(pPage, i);
3474 
3475     ptrmapPutOvflPtr(pPage, pCell, &rc);
3476 
3477     if( !pPage->leaf ){
3478       Pgno childPgno = get4byte(pCell);
3479       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3480     }
3481   }
3482 
3483   if( !pPage->leaf ){
3484     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3485     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3486   }
3487 
3488   return rc;
3489 }
3490 
3491 /*
3492 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
3493 ** that it points to iTo. Parameter eType describes the type of pointer to
3494 ** be modified, as  follows:
3495 **
3496 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
3497 **                   page of pPage.
3498 **
3499 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3500 **                   page pointed to by one of the cells on pPage.
3501 **
3502 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3503 **                   overflow page in the list.
3504 */
3505 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3506   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3507   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3508   if( eType==PTRMAP_OVERFLOW2 ){
3509     /* The pointer is always the first 4 bytes of the page in this case.  */
3510     if( get4byte(pPage->aData)!=iFrom ){
3511       return SQLITE_CORRUPT_PAGE(pPage);
3512     }
3513     put4byte(pPage->aData, iTo);
3514   }else{
3515     int i;
3516     int nCell;
3517     int rc;
3518 
3519     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3520     if( rc ) return rc;
3521     nCell = pPage->nCell;
3522 
3523     for(i=0; i<nCell; i++){
3524       u8 *pCell = findCell(pPage, i);
3525       if( eType==PTRMAP_OVERFLOW1 ){
3526         CellInfo info;
3527         pPage->xParseCell(pPage, pCell, &info);
3528         if( info.nLocal<info.nPayload ){
3529           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3530             return SQLITE_CORRUPT_PAGE(pPage);
3531           }
3532           if( iFrom==get4byte(pCell+info.nSize-4) ){
3533             put4byte(pCell+info.nSize-4, iTo);
3534             break;
3535           }
3536         }
3537       }else{
3538         if( get4byte(pCell)==iFrom ){
3539           put4byte(pCell, iTo);
3540           break;
3541         }
3542       }
3543     }
3544 
3545     if( i==nCell ){
3546       if( eType!=PTRMAP_BTREE ||
3547           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3548         return SQLITE_CORRUPT_PAGE(pPage);
3549       }
3550       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3551     }
3552   }
3553   return SQLITE_OK;
3554 }
3555 
3556 
3557 /*
3558 ** Move the open database page pDbPage to location iFreePage in the
3559 ** database. The pDbPage reference remains valid.
3560 **
3561 ** The isCommit flag indicates that there is no need to remember that
3562 ** the journal needs to be sync()ed before database page pDbPage->pgno
3563 ** can be written to. The caller has already promised not to write to that
3564 ** page.
3565 */
3566 static int relocatePage(
3567   BtShared *pBt,           /* Btree */
3568   MemPage *pDbPage,        /* Open page to move */
3569   u8 eType,                /* Pointer map 'type' entry for pDbPage */
3570   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
3571   Pgno iFreePage,          /* The location to move pDbPage to */
3572   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
3573 ){
3574   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
3575   Pgno iDbPage = pDbPage->pgno;
3576   Pager *pPager = pBt->pPager;
3577   int rc;
3578 
3579   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3580       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3581   assert( sqlite3_mutex_held(pBt->mutex) );
3582   assert( pDbPage->pBt==pBt );
3583 
3584   /* Move page iDbPage from its current location to page number iFreePage */
3585   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3586       iDbPage, iFreePage, iPtrPage, eType));
3587   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3588   if( rc!=SQLITE_OK ){
3589     return rc;
3590   }
3591   pDbPage->pgno = iFreePage;
3592 
3593   /* If pDbPage was a btree-page, then it may have child pages and/or cells
3594   ** that point to overflow pages. The pointer map entries for all these
3595   ** pages need to be changed.
3596   **
3597   ** If pDbPage is an overflow page, then the first 4 bytes may store a
3598   ** pointer to a subsequent overflow page. If this is the case, then
3599   ** the pointer map needs to be updated for the subsequent overflow page.
3600   */
3601   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3602     rc = setChildPtrmaps(pDbPage);
3603     if( rc!=SQLITE_OK ){
3604       return rc;
3605     }
3606   }else{
3607     Pgno nextOvfl = get4byte(pDbPage->aData);
3608     if( nextOvfl!=0 ){
3609       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3610       if( rc!=SQLITE_OK ){
3611         return rc;
3612       }
3613     }
3614   }
3615 
3616   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3617   ** that it points at iFreePage. Also fix the pointer map entry for
3618   ** iPtrPage.
3619   */
3620   if( eType!=PTRMAP_ROOTPAGE ){
3621     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3622     if( rc!=SQLITE_OK ){
3623       return rc;
3624     }
3625     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3626     if( rc!=SQLITE_OK ){
3627       releasePage(pPtrPage);
3628       return rc;
3629     }
3630     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3631     releasePage(pPtrPage);
3632     if( rc==SQLITE_OK ){
3633       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3634     }
3635   }
3636   return rc;
3637 }
3638 
3639 /* Forward declaration required by incrVacuumStep(). */
3640 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3641 
3642 /*
3643 ** Perform a single step of an incremental-vacuum. If successful, return
3644 ** SQLITE_OK. If there is no work to do (and therefore no point in
3645 ** calling this function again), return SQLITE_DONE. Or, if an error
3646 ** occurs, return some other error code.
3647 **
3648 ** More specifically, this function attempts to re-organize the database so
3649 ** that the last page of the file currently in use is no longer in use.
3650 **
3651 ** Parameter nFin is the number of pages that this database would contain
3652 ** were this function called until it returns SQLITE_DONE.
3653 **
3654 ** If the bCommit parameter is non-zero, this function assumes that the
3655 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3656 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3657 ** operation, or false for an incremental vacuum.
3658 */
3659 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3660   Pgno nFreeList;           /* Number of pages still on the free-list */
3661   int rc;
3662 
3663   assert( sqlite3_mutex_held(pBt->mutex) );
3664   assert( iLastPg>nFin );
3665 
3666   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3667     u8 eType;
3668     Pgno iPtrPage;
3669 
3670     nFreeList = get4byte(&pBt->pPage1->aData[36]);
3671     if( nFreeList==0 ){
3672       return SQLITE_DONE;
3673     }
3674 
3675     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3676     if( rc!=SQLITE_OK ){
3677       return rc;
3678     }
3679     if( eType==PTRMAP_ROOTPAGE ){
3680       return SQLITE_CORRUPT_BKPT;
3681     }
3682 
3683     if( eType==PTRMAP_FREEPAGE ){
3684       if( bCommit==0 ){
3685         /* Remove the page from the files free-list. This is not required
3686         ** if bCommit is non-zero. In that case, the free-list will be
3687         ** truncated to zero after this function returns, so it doesn't
3688         ** matter if it still contains some garbage entries.
3689         */
3690         Pgno iFreePg;
3691         MemPage *pFreePg;
3692         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3693         if( rc!=SQLITE_OK ){
3694           return rc;
3695         }
3696         assert( iFreePg==iLastPg );
3697         releasePage(pFreePg);
3698       }
3699     } else {
3700       Pgno iFreePg;             /* Index of free page to move pLastPg to */
3701       MemPage *pLastPg;
3702       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
3703       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
3704 
3705       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3706       if( rc!=SQLITE_OK ){
3707         return rc;
3708       }
3709 
3710       /* If bCommit is zero, this loop runs exactly once and page pLastPg
3711       ** is swapped with the first free page pulled off the free list.
3712       **
3713       ** On the other hand, if bCommit is greater than zero, then keep
3714       ** looping until a free-page located within the first nFin pages
3715       ** of the file is found.
3716       */
3717       if( bCommit==0 ){
3718         eMode = BTALLOC_LE;
3719         iNear = nFin;
3720       }
3721       do {
3722         MemPage *pFreePg;
3723         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3724         if( rc!=SQLITE_OK ){
3725           releasePage(pLastPg);
3726           return rc;
3727         }
3728         releasePage(pFreePg);
3729       }while( bCommit && iFreePg>nFin );
3730       assert( iFreePg<iLastPg );
3731 
3732       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3733       releasePage(pLastPg);
3734       if( rc!=SQLITE_OK ){
3735         return rc;
3736       }
3737     }
3738   }
3739 
3740   if( bCommit==0 ){
3741     do {
3742       iLastPg--;
3743     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3744     pBt->bDoTruncate = 1;
3745     pBt->nPage = iLastPg;
3746   }
3747   return SQLITE_OK;
3748 }
3749 
3750 /*
3751 ** The database opened by the first argument is an auto-vacuum database
3752 ** nOrig pages in size containing nFree free pages. Return the expected
3753 ** size of the database in pages following an auto-vacuum operation.
3754 */
3755 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3756   int nEntry;                     /* Number of entries on one ptrmap page */
3757   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
3758   Pgno nFin;                      /* Return value */
3759 
3760   nEntry = pBt->usableSize/5;
3761   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3762   nFin = nOrig - nFree - nPtrmap;
3763   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3764     nFin--;
3765   }
3766   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3767     nFin--;
3768   }
3769 
3770   return nFin;
3771 }
3772 
3773 /*
3774 ** A write-transaction must be opened before calling this function.
3775 ** It performs a single unit of work towards an incremental vacuum.
3776 **
3777 ** If the incremental vacuum is finished after this function has run,
3778 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3779 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3780 */
3781 int sqlite3BtreeIncrVacuum(Btree *p){
3782   int rc;
3783   BtShared *pBt = p->pBt;
3784 
3785   sqlite3BtreeEnter(p);
3786   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3787   if( !pBt->autoVacuum ){
3788     rc = SQLITE_DONE;
3789   }else{
3790     Pgno nOrig = btreePagecount(pBt);
3791     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3792     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3793 
3794     if( nOrig<nFin ){
3795       rc = SQLITE_CORRUPT_BKPT;
3796     }else if( nFree>0 ){
3797       rc = saveAllCursors(pBt, 0, 0);
3798       if( rc==SQLITE_OK ){
3799         invalidateAllOverflowCache(pBt);
3800         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3801       }
3802       if( rc==SQLITE_OK ){
3803         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3804         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3805       }
3806     }else{
3807       rc = SQLITE_DONE;
3808     }
3809   }
3810   sqlite3BtreeLeave(p);
3811   return rc;
3812 }
3813 
3814 /*
3815 ** This routine is called prior to sqlite3PagerCommit when a transaction
3816 ** is committed for an auto-vacuum database.
3817 **
3818 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3819 ** the database file should be truncated to during the commit process.
3820 ** i.e. the database has been reorganized so that only the first *pnTrunc
3821 ** pages are in use.
3822 */
3823 static int autoVacuumCommit(BtShared *pBt){
3824   int rc = SQLITE_OK;
3825   Pager *pPager = pBt->pPager;
3826   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3827 
3828   assert( sqlite3_mutex_held(pBt->mutex) );
3829   invalidateAllOverflowCache(pBt);
3830   assert(pBt->autoVacuum);
3831   if( !pBt->incrVacuum ){
3832     Pgno nFin;         /* Number of pages in database after autovacuuming */
3833     Pgno nFree;        /* Number of pages on the freelist initially */
3834     Pgno iFree;        /* The next page to be freed */
3835     Pgno nOrig;        /* Database size before freeing */
3836 
3837     nOrig = btreePagecount(pBt);
3838     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3839       /* It is not possible to create a database for which the final page
3840       ** is either a pointer-map page or the pending-byte page. If one
3841       ** is encountered, this indicates corruption.
3842       */
3843       return SQLITE_CORRUPT_BKPT;
3844     }
3845 
3846     nFree = get4byte(&pBt->pPage1->aData[36]);
3847     nFin = finalDbSize(pBt, nOrig, nFree);
3848     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3849     if( nFin<nOrig ){
3850       rc = saveAllCursors(pBt, 0, 0);
3851     }
3852     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3853       rc = incrVacuumStep(pBt, nFin, iFree, 1);
3854     }
3855     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3856       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3857       put4byte(&pBt->pPage1->aData[32], 0);
3858       put4byte(&pBt->pPage1->aData[36], 0);
3859       put4byte(&pBt->pPage1->aData[28], nFin);
3860       pBt->bDoTruncate = 1;
3861       pBt->nPage = nFin;
3862     }
3863     if( rc!=SQLITE_OK ){
3864       sqlite3PagerRollback(pPager);
3865     }
3866   }
3867 
3868   assert( nRef>=sqlite3PagerRefcount(pPager) );
3869   return rc;
3870 }
3871 
3872 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3873 # define setChildPtrmaps(x) SQLITE_OK
3874 #endif
3875 
3876 /*
3877 ** This routine does the first phase of a two-phase commit.  This routine
3878 ** causes a rollback journal to be created (if it does not already exist)
3879 ** and populated with enough information so that if a power loss occurs
3880 ** the database can be restored to its original state by playing back
3881 ** the journal.  Then the contents of the journal are flushed out to
3882 ** the disk.  After the journal is safely on oxide, the changes to the
3883 ** database are written into the database file and flushed to oxide.
3884 ** At the end of this call, the rollback journal still exists on the
3885 ** disk and we are still holding all locks, so the transaction has not
3886 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3887 ** commit process.
3888 **
3889 ** This call is a no-op if no write-transaction is currently active on pBt.
3890 **
3891 ** Otherwise, sync the database file for the btree pBt. zMaster points to
3892 ** the name of a master journal file that should be written into the
3893 ** individual journal file, or is NULL, indicating no master journal file
3894 ** (single database transaction).
3895 **
3896 ** When this is called, the master journal should already have been
3897 ** created, populated with this journal pointer and synced to disk.
3898 **
3899 ** Once this is routine has returned, the only thing required to commit
3900 ** the write-transaction for this database file is to delete the journal.
3901 */
3902 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3903   int rc = SQLITE_OK;
3904   if( p->inTrans==TRANS_WRITE ){
3905     BtShared *pBt = p->pBt;
3906     sqlite3BtreeEnter(p);
3907 #ifndef SQLITE_OMIT_AUTOVACUUM
3908     if( pBt->autoVacuum ){
3909       rc = autoVacuumCommit(pBt);
3910       if( rc!=SQLITE_OK ){
3911         sqlite3BtreeLeave(p);
3912         return rc;
3913       }
3914     }
3915     if( pBt->bDoTruncate ){
3916       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3917     }
3918 #endif
3919     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
3920     sqlite3BtreeLeave(p);
3921   }
3922   return rc;
3923 }
3924 
3925 /*
3926 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3927 ** at the conclusion of a transaction.
3928 */
3929 static void btreeEndTransaction(Btree *p){
3930   BtShared *pBt = p->pBt;
3931   sqlite3 *db = p->db;
3932   assert( sqlite3BtreeHoldsMutex(p) );
3933 
3934 #ifndef SQLITE_OMIT_AUTOVACUUM
3935   pBt->bDoTruncate = 0;
3936 #endif
3937   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
3938     /* If there are other active statements that belong to this database
3939     ** handle, downgrade to a read-only transaction. The other statements
3940     ** may still be reading from the database.  */
3941     downgradeAllSharedCacheTableLocks(p);
3942     p->inTrans = TRANS_READ;
3943   }else{
3944     /* If the handle had any kind of transaction open, decrement the
3945     ** transaction count of the shared btree. If the transaction count
3946     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3947     ** call below will unlock the pager.  */
3948     if( p->inTrans!=TRANS_NONE ){
3949       clearAllSharedCacheTableLocks(p);
3950       pBt->nTransaction--;
3951       if( 0==pBt->nTransaction ){
3952         pBt->inTransaction = TRANS_NONE;
3953       }
3954     }
3955 
3956     /* Set the current transaction state to TRANS_NONE and unlock the
3957     ** pager if this call closed the only read or write transaction.  */
3958     p->inTrans = TRANS_NONE;
3959     unlockBtreeIfUnused(pBt);
3960   }
3961 
3962   btreeIntegrity(p);
3963 }
3964 
3965 /*
3966 ** Commit the transaction currently in progress.
3967 **
3968 ** This routine implements the second phase of a 2-phase commit.  The
3969 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3970 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
3971 ** routine did all the work of writing information out to disk and flushing the
3972 ** contents so that they are written onto the disk platter.  All this
3973 ** routine has to do is delete or truncate or zero the header in the
3974 ** the rollback journal (which causes the transaction to commit) and
3975 ** drop locks.
3976 **
3977 ** Normally, if an error occurs while the pager layer is attempting to
3978 ** finalize the underlying journal file, this function returns an error and
3979 ** the upper layer will attempt a rollback. However, if the second argument
3980 ** is non-zero then this b-tree transaction is part of a multi-file
3981 ** transaction. In this case, the transaction has already been committed
3982 ** (by deleting a master journal file) and the caller will ignore this
3983 ** functions return code. So, even if an error occurs in the pager layer,
3984 ** reset the b-tree objects internal state to indicate that the write
3985 ** transaction has been closed. This is quite safe, as the pager will have
3986 ** transitioned to the error state.
3987 **
3988 ** This will release the write lock on the database file.  If there
3989 ** are no active cursors, it also releases the read lock.
3990 */
3991 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
3992 
3993   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
3994   sqlite3BtreeEnter(p);
3995   btreeIntegrity(p);
3996 
3997   /* If the handle has a write-transaction open, commit the shared-btrees
3998   ** transaction and set the shared state to TRANS_READ.
3999   */
4000   if( p->inTrans==TRANS_WRITE ){
4001     int rc;
4002     BtShared *pBt = p->pBt;
4003     assert( pBt->inTransaction==TRANS_WRITE );
4004     assert( pBt->nTransaction>0 );
4005     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4006     if( rc!=SQLITE_OK && bCleanup==0 ){
4007       sqlite3BtreeLeave(p);
4008       return rc;
4009     }
4010     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
4011     pBt->inTransaction = TRANS_READ;
4012     btreeClearHasContent(pBt);
4013   }
4014 
4015   btreeEndTransaction(p);
4016   sqlite3BtreeLeave(p);
4017   return SQLITE_OK;
4018 }
4019 
4020 /*
4021 ** Do both phases of a commit.
4022 */
4023 int sqlite3BtreeCommit(Btree *p){
4024   int rc;
4025   sqlite3BtreeEnter(p);
4026   rc = sqlite3BtreeCommitPhaseOne(p, 0);
4027   if( rc==SQLITE_OK ){
4028     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4029   }
4030   sqlite3BtreeLeave(p);
4031   return rc;
4032 }
4033 
4034 /*
4035 ** This routine sets the state to CURSOR_FAULT and the error
4036 ** code to errCode for every cursor on any BtShared that pBtree
4037 ** references.  Or if the writeOnly flag is set to 1, then only
4038 ** trip write cursors and leave read cursors unchanged.
4039 **
4040 ** Every cursor is a candidate to be tripped, including cursors
4041 ** that belong to other database connections that happen to be
4042 ** sharing the cache with pBtree.
4043 **
4044 ** This routine gets called when a rollback occurs. If the writeOnly
4045 ** flag is true, then only write-cursors need be tripped - read-only
4046 ** cursors save their current positions so that they may continue
4047 ** following the rollback. Or, if writeOnly is false, all cursors are
4048 ** tripped. In general, writeOnly is false if the transaction being
4049 ** rolled back modified the database schema. In this case b-tree root
4050 ** pages may be moved or deleted from the database altogether, making
4051 ** it unsafe for read cursors to continue.
4052 **
4053 ** If the writeOnly flag is true and an error is encountered while
4054 ** saving the current position of a read-only cursor, all cursors,
4055 ** including all read-cursors are tripped.
4056 **
4057 ** SQLITE_OK is returned if successful, or if an error occurs while
4058 ** saving a cursor position, an SQLite error code.
4059 */
4060 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4061   BtCursor *p;
4062   int rc = SQLITE_OK;
4063 
4064   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4065   if( pBtree ){
4066     sqlite3BtreeEnter(pBtree);
4067     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4068       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4069         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4070           rc = saveCursorPosition(p);
4071           if( rc!=SQLITE_OK ){
4072             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4073             break;
4074           }
4075         }
4076       }else{
4077         sqlite3BtreeClearCursor(p);
4078         p->eState = CURSOR_FAULT;
4079         p->skipNext = errCode;
4080       }
4081       btreeReleaseAllCursorPages(p);
4082     }
4083     sqlite3BtreeLeave(pBtree);
4084   }
4085   return rc;
4086 }
4087 
4088 /*
4089 ** Rollback the transaction in progress.
4090 **
4091 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4092 ** Only write cursors are tripped if writeOnly is true but all cursors are
4093 ** tripped if writeOnly is false.  Any attempt to use
4094 ** a tripped cursor will result in an error.
4095 **
4096 ** This will release the write lock on the database file.  If there
4097 ** are no active cursors, it also releases the read lock.
4098 */
4099 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4100   int rc;
4101   BtShared *pBt = p->pBt;
4102   MemPage *pPage1;
4103 
4104   assert( writeOnly==1 || writeOnly==0 );
4105   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4106   sqlite3BtreeEnter(p);
4107   if( tripCode==SQLITE_OK ){
4108     rc = tripCode = saveAllCursors(pBt, 0, 0);
4109     if( rc ) writeOnly = 0;
4110   }else{
4111     rc = SQLITE_OK;
4112   }
4113   if( tripCode ){
4114     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4115     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4116     if( rc2!=SQLITE_OK ) rc = rc2;
4117   }
4118   btreeIntegrity(p);
4119 
4120   if( p->inTrans==TRANS_WRITE ){
4121     int rc2;
4122 
4123     assert( TRANS_WRITE==pBt->inTransaction );
4124     rc2 = sqlite3PagerRollback(pBt->pPager);
4125     if( rc2!=SQLITE_OK ){
4126       rc = rc2;
4127     }
4128 
4129     /* The rollback may have destroyed the pPage1->aData value.  So
4130     ** call btreeGetPage() on page 1 again to make
4131     ** sure pPage1->aData is set correctly. */
4132     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4133       int nPage = get4byte(28+(u8*)pPage1->aData);
4134       testcase( nPage==0 );
4135       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4136       testcase( pBt->nPage!=nPage );
4137       pBt->nPage = nPage;
4138       releasePageOne(pPage1);
4139     }
4140     assert( countValidCursors(pBt, 1)==0 );
4141     pBt->inTransaction = TRANS_READ;
4142     btreeClearHasContent(pBt);
4143   }
4144 
4145   btreeEndTransaction(p);
4146   sqlite3BtreeLeave(p);
4147   return rc;
4148 }
4149 
4150 /*
4151 ** Start a statement subtransaction. The subtransaction can be rolled
4152 ** back independently of the main transaction. You must start a transaction
4153 ** before starting a subtransaction. The subtransaction is ended automatically
4154 ** if the main transaction commits or rolls back.
4155 **
4156 ** Statement subtransactions are used around individual SQL statements
4157 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4158 ** error occurs within the statement, the effect of that one statement
4159 ** can be rolled back without having to rollback the entire transaction.
4160 **
4161 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4162 ** value passed as the second parameter is the total number of savepoints,
4163 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4164 ** are no active savepoints and no other statement-transactions open,
4165 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4166 ** using the sqlite3BtreeSavepoint() function.
4167 */
4168 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4169   int rc;
4170   BtShared *pBt = p->pBt;
4171   sqlite3BtreeEnter(p);
4172   assert( p->inTrans==TRANS_WRITE );
4173   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4174   assert( iStatement>0 );
4175   assert( iStatement>p->db->nSavepoint );
4176   assert( pBt->inTransaction==TRANS_WRITE );
4177   /* At the pager level, a statement transaction is a savepoint with
4178   ** an index greater than all savepoints created explicitly using
4179   ** SQL statements. It is illegal to open, release or rollback any
4180   ** such savepoints while the statement transaction savepoint is active.
4181   */
4182   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4183   sqlite3BtreeLeave(p);
4184   return rc;
4185 }
4186 
4187 /*
4188 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4189 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4190 ** savepoint identified by parameter iSavepoint, depending on the value
4191 ** of op.
4192 **
4193 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4194 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4195 ** contents of the entire transaction are rolled back. This is different
4196 ** from a normal transaction rollback, as no locks are released and the
4197 ** transaction remains open.
4198 */
4199 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4200   int rc = SQLITE_OK;
4201   if( p && p->inTrans==TRANS_WRITE ){
4202     BtShared *pBt = p->pBt;
4203     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4204     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4205     sqlite3BtreeEnter(p);
4206     if( op==SAVEPOINT_ROLLBACK ){
4207       rc = saveAllCursors(pBt, 0, 0);
4208     }
4209     if( rc==SQLITE_OK ){
4210       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4211     }
4212     if( rc==SQLITE_OK ){
4213       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4214         pBt->nPage = 0;
4215       }
4216       rc = newDatabase(pBt);
4217       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
4218 
4219       /* The database size was written into the offset 28 of the header
4220       ** when the transaction started, so we know that the value at offset
4221       ** 28 is nonzero. */
4222       assert( pBt->nPage>0 );
4223     }
4224     sqlite3BtreeLeave(p);
4225   }
4226   return rc;
4227 }
4228 
4229 /*
4230 ** Create a new cursor for the BTree whose root is on the page
4231 ** iTable. If a read-only cursor is requested, it is assumed that
4232 ** the caller already has at least a read-only transaction open
4233 ** on the database already. If a write-cursor is requested, then
4234 ** the caller is assumed to have an open write transaction.
4235 **
4236 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4237 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4238 ** can be used for reading or for writing if other conditions for writing
4239 ** are also met.  These are the conditions that must be met in order
4240 ** for writing to be allowed:
4241 **
4242 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4243 **
4244 ** 2:  Other database connections that share the same pager cache
4245 **     but which are not in the READ_UNCOMMITTED state may not have
4246 **     cursors open with wrFlag==0 on the same table.  Otherwise
4247 **     the changes made by this write cursor would be visible to
4248 **     the read cursors in the other database connection.
4249 **
4250 ** 3:  The database must be writable (not on read-only media)
4251 **
4252 ** 4:  There must be an active transaction.
4253 **
4254 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4255 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4256 ** this cursor will only be used to seek to and delete entries of an index
4257 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4258 ** this implementation.  But in a hypothetical alternative storage engine
4259 ** in which index entries are automatically deleted when corresponding table
4260 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4261 ** operations on this cursor can be no-ops and all READ operations can
4262 ** return a null row (2-bytes: 0x01 0x00).
4263 **
4264 ** No checking is done to make sure that page iTable really is the
4265 ** root page of a b-tree.  If it is not, then the cursor acquired
4266 ** will not work correctly.
4267 **
4268 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4269 ** on pCur to initialize the memory space prior to invoking this routine.
4270 */
4271 static int btreeCursor(
4272   Btree *p,                              /* The btree */
4273   int iTable,                            /* Root page of table to open */
4274   int wrFlag,                            /* 1 to write. 0 read-only */
4275   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4276   BtCursor *pCur                         /* Space for new cursor */
4277 ){
4278   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4279   BtCursor *pX;                          /* Looping over other all cursors */
4280 
4281   assert( sqlite3BtreeHoldsMutex(p) );
4282   assert( wrFlag==0
4283        || wrFlag==BTREE_WRCSR
4284        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4285   );
4286 
4287   /* The following assert statements verify that if this is a sharable
4288   ** b-tree database, the connection is holding the required table locks,
4289   ** and that no other connection has any open cursor that conflicts with
4290   ** this lock.  */
4291   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
4292   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4293 
4294   /* Assert that the caller has opened the required transaction. */
4295   assert( p->inTrans>TRANS_NONE );
4296   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4297   assert( pBt->pPage1 && pBt->pPage1->aData );
4298   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4299 
4300   if( wrFlag ){
4301     allocateTempSpace(pBt);
4302     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4303   }
4304   if( iTable==1 && btreePagecount(pBt)==0 ){
4305     assert( wrFlag==0 );
4306     iTable = 0;
4307   }
4308 
4309   /* Now that no other errors can occur, finish filling in the BtCursor
4310   ** variables and link the cursor into the BtShared list.  */
4311   pCur->pgnoRoot = (Pgno)iTable;
4312   pCur->iPage = -1;
4313   pCur->pKeyInfo = pKeyInfo;
4314   pCur->pBtree = p;
4315   pCur->pBt = pBt;
4316   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4317   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4318   /* If there are two or more cursors on the same btree, then all such
4319   ** cursors *must* have the BTCF_Multiple flag set. */
4320   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4321     if( pX->pgnoRoot==(Pgno)iTable ){
4322       pX->curFlags |= BTCF_Multiple;
4323       pCur->curFlags |= BTCF_Multiple;
4324     }
4325   }
4326   pCur->pNext = pBt->pCursor;
4327   pBt->pCursor = pCur;
4328   pCur->eState = CURSOR_INVALID;
4329   return SQLITE_OK;
4330 }
4331 int sqlite3BtreeCursor(
4332   Btree *p,                                   /* The btree */
4333   int iTable,                                 /* Root page of table to open */
4334   int wrFlag,                                 /* 1 to write. 0 read-only */
4335   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4336   BtCursor *pCur                              /* Write new cursor here */
4337 ){
4338   int rc;
4339   if( iTable<1 ){
4340     rc = SQLITE_CORRUPT_BKPT;
4341   }else{
4342     sqlite3BtreeEnter(p);
4343     rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4344     sqlite3BtreeLeave(p);
4345   }
4346   return rc;
4347 }
4348 
4349 /*
4350 ** Return the size of a BtCursor object in bytes.
4351 **
4352 ** This interfaces is needed so that users of cursors can preallocate
4353 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4354 ** to users so they cannot do the sizeof() themselves - they must call
4355 ** this routine.
4356 */
4357 int sqlite3BtreeCursorSize(void){
4358   return ROUND8(sizeof(BtCursor));
4359 }
4360 
4361 /*
4362 ** Initialize memory that will be converted into a BtCursor object.
4363 **
4364 ** The simple approach here would be to memset() the entire object
4365 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4366 ** do not need to be zeroed and they are large, so we can save a lot
4367 ** of run-time by skipping the initialization of those elements.
4368 */
4369 void sqlite3BtreeCursorZero(BtCursor *p){
4370   memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4371 }
4372 
4373 /*
4374 ** Close a cursor.  The read lock on the database file is released
4375 ** when the last cursor is closed.
4376 */
4377 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4378   Btree *pBtree = pCur->pBtree;
4379   if( pBtree ){
4380     BtShared *pBt = pCur->pBt;
4381     sqlite3BtreeEnter(pBtree);
4382     assert( pBt->pCursor!=0 );
4383     if( pBt->pCursor==pCur ){
4384       pBt->pCursor = pCur->pNext;
4385     }else{
4386       BtCursor *pPrev = pBt->pCursor;
4387       do{
4388         if( pPrev->pNext==pCur ){
4389           pPrev->pNext = pCur->pNext;
4390           break;
4391         }
4392         pPrev = pPrev->pNext;
4393       }while( ALWAYS(pPrev) );
4394     }
4395     btreeReleaseAllCursorPages(pCur);
4396     unlockBtreeIfUnused(pBt);
4397     sqlite3_free(pCur->aOverflow);
4398     sqlite3_free(pCur->pKey);
4399     sqlite3BtreeLeave(pBtree);
4400   }
4401   return SQLITE_OK;
4402 }
4403 
4404 /*
4405 ** Make sure the BtCursor* given in the argument has a valid
4406 ** BtCursor.info structure.  If it is not already valid, call
4407 ** btreeParseCell() to fill it in.
4408 **
4409 ** BtCursor.info is a cache of the information in the current cell.
4410 ** Using this cache reduces the number of calls to btreeParseCell().
4411 */
4412 #ifndef NDEBUG
4413   static int cellInfoEqual(CellInfo *a, CellInfo *b){
4414     if( a->nKey!=b->nKey ) return 0;
4415     if( a->pPayload!=b->pPayload ) return 0;
4416     if( a->nPayload!=b->nPayload ) return 0;
4417     if( a->nLocal!=b->nLocal ) return 0;
4418     if( a->nSize!=b->nSize ) return 0;
4419     return 1;
4420   }
4421   static void assertCellInfo(BtCursor *pCur){
4422     CellInfo info;
4423     memset(&info, 0, sizeof(info));
4424     btreeParseCell(pCur->pPage, pCur->ix, &info);
4425     assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4426   }
4427 #else
4428   #define assertCellInfo(x)
4429 #endif
4430 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4431   if( pCur->info.nSize==0 ){
4432     pCur->curFlags |= BTCF_ValidNKey;
4433     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4434   }else{
4435     assertCellInfo(pCur);
4436   }
4437 }
4438 
4439 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4440 /*
4441 ** Return true if the given BtCursor is valid.  A valid cursor is one
4442 ** that is currently pointing to a row in a (non-empty) table.
4443 ** This is a verification routine is used only within assert() statements.
4444 */
4445 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4446   return pCur && pCur->eState==CURSOR_VALID;
4447 }
4448 #endif /* NDEBUG */
4449 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4450   assert( pCur!=0 );
4451   return pCur->eState==CURSOR_VALID;
4452 }
4453 
4454 /*
4455 ** Return the value of the integer key or "rowid" for a table btree.
4456 ** This routine is only valid for a cursor that is pointing into a
4457 ** ordinary table btree.  If the cursor points to an index btree or
4458 ** is invalid, the result of this routine is undefined.
4459 */
4460 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4461   assert( cursorHoldsMutex(pCur) );
4462   assert( pCur->eState==CURSOR_VALID );
4463   assert( pCur->curIntKey );
4464   getCellInfo(pCur);
4465   return pCur->info.nKey;
4466 }
4467 
4468 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4469 /*
4470 ** Return the offset into the database file for the start of the
4471 ** payload to which the cursor is pointing.
4472 */
4473 i64 sqlite3BtreeOffset(BtCursor *pCur){
4474   assert( cursorHoldsMutex(pCur) );
4475   assert( pCur->eState==CURSOR_VALID );
4476   getCellInfo(pCur);
4477   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4478          (i64)(pCur->info.pPayload - pCur->pPage->aData);
4479 }
4480 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4481 
4482 /*
4483 ** Return the number of bytes of payload for the entry that pCur is
4484 ** currently pointing to.  For table btrees, this will be the amount
4485 ** of data.  For index btrees, this will be the size of the key.
4486 **
4487 ** The caller must guarantee that the cursor is pointing to a non-NULL
4488 ** valid entry.  In other words, the calling procedure must guarantee
4489 ** that the cursor has Cursor.eState==CURSOR_VALID.
4490 */
4491 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4492   assert( cursorHoldsMutex(pCur) );
4493   assert( pCur->eState==CURSOR_VALID );
4494   getCellInfo(pCur);
4495   return pCur->info.nPayload;
4496 }
4497 
4498 /*
4499 ** Given the page number of an overflow page in the database (parameter
4500 ** ovfl), this function finds the page number of the next page in the
4501 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4502 ** pointer-map data instead of reading the content of page ovfl to do so.
4503 **
4504 ** If an error occurs an SQLite error code is returned. Otherwise:
4505 **
4506 ** The page number of the next overflow page in the linked list is
4507 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4508 ** list, *pPgnoNext is set to zero.
4509 **
4510 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4511 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4512 ** reference. It is the responsibility of the caller to call releasePage()
4513 ** on *ppPage to free the reference. In no reference was obtained (because
4514 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4515 ** *ppPage is set to zero.
4516 */
4517 static int getOverflowPage(
4518   BtShared *pBt,               /* The database file */
4519   Pgno ovfl,                   /* Current overflow page number */
4520   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4521   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4522 ){
4523   Pgno next = 0;
4524   MemPage *pPage = 0;
4525   int rc = SQLITE_OK;
4526 
4527   assert( sqlite3_mutex_held(pBt->mutex) );
4528   assert(pPgnoNext);
4529 
4530 #ifndef SQLITE_OMIT_AUTOVACUUM
4531   /* Try to find the next page in the overflow list using the
4532   ** autovacuum pointer-map pages. Guess that the next page in
4533   ** the overflow list is page number (ovfl+1). If that guess turns
4534   ** out to be wrong, fall back to loading the data of page
4535   ** number ovfl to determine the next page number.
4536   */
4537   if( pBt->autoVacuum ){
4538     Pgno pgno;
4539     Pgno iGuess = ovfl+1;
4540     u8 eType;
4541 
4542     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4543       iGuess++;
4544     }
4545 
4546     if( iGuess<=btreePagecount(pBt) ){
4547       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4548       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4549         next = iGuess;
4550         rc = SQLITE_DONE;
4551       }
4552     }
4553   }
4554 #endif
4555 
4556   assert( next==0 || rc==SQLITE_DONE );
4557   if( rc==SQLITE_OK ){
4558     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4559     assert( rc==SQLITE_OK || pPage==0 );
4560     if( rc==SQLITE_OK ){
4561       next = get4byte(pPage->aData);
4562     }
4563   }
4564 
4565   *pPgnoNext = next;
4566   if( ppPage ){
4567     *ppPage = pPage;
4568   }else{
4569     releasePage(pPage);
4570   }
4571   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4572 }
4573 
4574 /*
4575 ** Copy data from a buffer to a page, or from a page to a buffer.
4576 **
4577 ** pPayload is a pointer to data stored on database page pDbPage.
4578 ** If argument eOp is false, then nByte bytes of data are copied
4579 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4580 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4581 ** of data are copied from the buffer pBuf to pPayload.
4582 **
4583 ** SQLITE_OK is returned on success, otherwise an error code.
4584 */
4585 static int copyPayload(
4586   void *pPayload,           /* Pointer to page data */
4587   void *pBuf,               /* Pointer to buffer */
4588   int nByte,                /* Number of bytes to copy */
4589   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4590   DbPage *pDbPage           /* Page containing pPayload */
4591 ){
4592   if( eOp ){
4593     /* Copy data from buffer to page (a write operation) */
4594     int rc = sqlite3PagerWrite(pDbPage);
4595     if( rc!=SQLITE_OK ){
4596       return rc;
4597     }
4598     memcpy(pPayload, pBuf, nByte);
4599   }else{
4600     /* Copy data from page to buffer (a read operation) */
4601     memcpy(pBuf, pPayload, nByte);
4602   }
4603   return SQLITE_OK;
4604 }
4605 
4606 /*
4607 ** This function is used to read or overwrite payload information
4608 ** for the entry that the pCur cursor is pointing to. The eOp
4609 ** argument is interpreted as follows:
4610 **
4611 **   0: The operation is a read. Populate the overflow cache.
4612 **   1: The operation is a write. Populate the overflow cache.
4613 **
4614 ** A total of "amt" bytes are read or written beginning at "offset".
4615 ** Data is read to or from the buffer pBuf.
4616 **
4617 ** The content being read or written might appear on the main page
4618 ** or be scattered out on multiple overflow pages.
4619 **
4620 ** If the current cursor entry uses one or more overflow pages
4621 ** this function may allocate space for and lazily populate
4622 ** the overflow page-list cache array (BtCursor.aOverflow).
4623 ** Subsequent calls use this cache to make seeking to the supplied offset
4624 ** more efficient.
4625 **
4626 ** Once an overflow page-list cache has been allocated, it must be
4627 ** invalidated if some other cursor writes to the same table, or if
4628 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4629 ** mode, the following events may invalidate an overflow page-list cache.
4630 **
4631 **   * An incremental vacuum,
4632 **   * A commit in auto_vacuum="full" mode,
4633 **   * Creating a table (may require moving an overflow page).
4634 */
4635 static int accessPayload(
4636   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4637   u32 offset,          /* Begin reading this far into payload */
4638   u32 amt,             /* Read this many bytes */
4639   unsigned char *pBuf, /* Write the bytes into this buffer */
4640   int eOp              /* zero to read. non-zero to write. */
4641 ){
4642   unsigned char *aPayload;
4643   int rc = SQLITE_OK;
4644   int iIdx = 0;
4645   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
4646   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4647 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4648   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4649 #endif
4650 
4651   assert( pPage );
4652   assert( eOp==0 || eOp==1 );
4653   assert( pCur->eState==CURSOR_VALID );
4654   assert( pCur->ix<pPage->nCell );
4655   assert( cursorHoldsMutex(pCur) );
4656 
4657   getCellInfo(pCur);
4658   aPayload = pCur->info.pPayload;
4659   assert( offset+amt <= pCur->info.nPayload );
4660 
4661   assert( aPayload > pPage->aData );
4662   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4663     /* Trying to read or write past the end of the data is an error.  The
4664     ** conditional above is really:
4665     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4666     ** but is recast into its current form to avoid integer overflow problems
4667     */
4668     return SQLITE_CORRUPT_PAGE(pPage);
4669   }
4670 
4671   /* Check if data must be read/written to/from the btree page itself. */
4672   if( offset<pCur->info.nLocal ){
4673     int a = amt;
4674     if( a+offset>pCur->info.nLocal ){
4675       a = pCur->info.nLocal - offset;
4676     }
4677     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4678     offset = 0;
4679     pBuf += a;
4680     amt -= a;
4681   }else{
4682     offset -= pCur->info.nLocal;
4683   }
4684 
4685 
4686   if( rc==SQLITE_OK && amt>0 ){
4687     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4688     Pgno nextPage;
4689 
4690     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4691 
4692     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4693     **
4694     ** The aOverflow[] array is sized at one entry for each overflow page
4695     ** in the overflow chain. The page number of the first overflow page is
4696     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4697     ** means "not yet known" (the cache is lazily populated).
4698     */
4699     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4700       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4701       if( pCur->aOverflow==0
4702        || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4703       ){
4704         Pgno *aNew = (Pgno*)sqlite3Realloc(
4705             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4706         );
4707         if( aNew==0 ){
4708           return SQLITE_NOMEM_BKPT;
4709         }else{
4710           pCur->aOverflow = aNew;
4711         }
4712       }
4713       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4714       pCur->curFlags |= BTCF_ValidOvfl;
4715     }else{
4716       /* If the overflow page-list cache has been allocated and the
4717       ** entry for the first required overflow page is valid, skip
4718       ** directly to it.
4719       */
4720       if( pCur->aOverflow[offset/ovflSize] ){
4721         iIdx = (offset/ovflSize);
4722         nextPage = pCur->aOverflow[iIdx];
4723         offset = (offset%ovflSize);
4724       }
4725     }
4726 
4727     assert( rc==SQLITE_OK && amt>0 );
4728     while( nextPage ){
4729       /* If required, populate the overflow page-list cache. */
4730       assert( pCur->aOverflow[iIdx]==0
4731               || pCur->aOverflow[iIdx]==nextPage
4732               || CORRUPT_DB );
4733       pCur->aOverflow[iIdx] = nextPage;
4734 
4735       if( offset>=ovflSize ){
4736         /* The only reason to read this page is to obtain the page
4737         ** number for the next page in the overflow chain. The page
4738         ** data is not required. So first try to lookup the overflow
4739         ** page-list cache, if any, then fall back to the getOverflowPage()
4740         ** function.
4741         */
4742         assert( pCur->curFlags & BTCF_ValidOvfl );
4743         assert( pCur->pBtree->db==pBt->db );
4744         if( pCur->aOverflow[iIdx+1] ){
4745           nextPage = pCur->aOverflow[iIdx+1];
4746         }else{
4747           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4748         }
4749         offset -= ovflSize;
4750       }else{
4751         /* Need to read this page properly. It contains some of the
4752         ** range of data that is being read (eOp==0) or written (eOp!=0).
4753         */
4754 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4755         sqlite3_file *fd;      /* File from which to do direct overflow read */
4756 #endif
4757         int a = amt;
4758         if( a + offset > ovflSize ){
4759           a = ovflSize - offset;
4760         }
4761 
4762 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4763         /* If all the following are true:
4764         **
4765         **   1) this is a read operation, and
4766         **   2) data is required from the start of this overflow page, and
4767         **   3) there is no open write-transaction, and
4768         **   4) the database is file-backed, and
4769         **   5) the page is not in the WAL file
4770         **   6) at least 4 bytes have already been read into the output buffer
4771         **
4772         ** then data can be read directly from the database file into the
4773         ** output buffer, bypassing the page-cache altogether. This speeds
4774         ** up loading large records that span many overflow pages.
4775         */
4776         if( eOp==0                                             /* (1) */
4777          && offset==0                                          /* (2) */
4778          && pBt->inTransaction==TRANS_READ                     /* (3) */
4779          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
4780          && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
4781          && &pBuf[-4]>=pBufStart                               /* (6) */
4782         ){
4783           u8 aSave[4];
4784           u8 *aWrite = &pBuf[-4];
4785           assert( aWrite>=pBufStart );                         /* due to (6) */
4786           memcpy(aSave, aWrite, 4);
4787           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4788           nextPage = get4byte(aWrite);
4789           memcpy(aWrite, aSave, 4);
4790         }else
4791 #endif
4792 
4793         {
4794           DbPage *pDbPage;
4795           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4796               (eOp==0 ? PAGER_GET_READONLY : 0)
4797           );
4798           if( rc==SQLITE_OK ){
4799             aPayload = sqlite3PagerGetData(pDbPage);
4800             nextPage = get4byte(aPayload);
4801             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4802             sqlite3PagerUnref(pDbPage);
4803             offset = 0;
4804           }
4805         }
4806         amt -= a;
4807         if( amt==0 ) return rc;
4808         pBuf += a;
4809       }
4810       if( rc ) break;
4811       iIdx++;
4812     }
4813   }
4814 
4815   if( rc==SQLITE_OK && amt>0 ){
4816     /* Overflow chain ends prematurely */
4817     return SQLITE_CORRUPT_PAGE(pPage);
4818   }
4819   return rc;
4820 }
4821 
4822 /*
4823 ** Read part of the payload for the row at which that cursor pCur is currently
4824 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
4825 ** begins at "offset".
4826 **
4827 ** pCur can be pointing to either a table or an index b-tree.
4828 ** If pointing to a table btree, then the content section is read.  If
4829 ** pCur is pointing to an index b-tree then the key section is read.
4830 **
4831 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4832 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
4833 ** cursor might be invalid or might need to be restored before being read.
4834 **
4835 ** Return SQLITE_OK on success or an error code if anything goes
4836 ** wrong.  An error is returned if "offset+amt" is larger than
4837 ** the available payload.
4838 */
4839 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4840   assert( cursorHoldsMutex(pCur) );
4841   assert( pCur->eState==CURSOR_VALID );
4842   assert( pCur->iPage>=0 && pCur->pPage );
4843   assert( pCur->ix<pCur->pPage->nCell );
4844   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4845 }
4846 
4847 /*
4848 ** This variant of sqlite3BtreePayload() works even if the cursor has not
4849 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
4850 ** interface.
4851 */
4852 #ifndef SQLITE_OMIT_INCRBLOB
4853 static SQLITE_NOINLINE int accessPayloadChecked(
4854   BtCursor *pCur,
4855   u32 offset,
4856   u32 amt,
4857   void *pBuf
4858 ){
4859   int rc;
4860   if ( pCur->eState==CURSOR_INVALID ){
4861     return SQLITE_ABORT;
4862   }
4863   assert( cursorOwnsBtShared(pCur) );
4864   rc = btreeRestoreCursorPosition(pCur);
4865   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4866 }
4867 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4868   if( pCur->eState==CURSOR_VALID ){
4869     assert( cursorOwnsBtShared(pCur) );
4870     return accessPayload(pCur, offset, amt, pBuf, 0);
4871   }else{
4872     return accessPayloadChecked(pCur, offset, amt, pBuf);
4873   }
4874 }
4875 #endif /* SQLITE_OMIT_INCRBLOB */
4876 
4877 /*
4878 ** Return a pointer to payload information from the entry that the
4879 ** pCur cursor is pointing to.  The pointer is to the beginning of
4880 ** the key if index btrees (pPage->intKey==0) and is the data for
4881 ** table btrees (pPage->intKey==1). The number of bytes of available
4882 ** key/data is written into *pAmt.  If *pAmt==0, then the value
4883 ** returned will not be a valid pointer.
4884 **
4885 ** This routine is an optimization.  It is common for the entire key
4886 ** and data to fit on the local page and for there to be no overflow
4887 ** pages.  When that is so, this routine can be used to access the
4888 ** key and data without making a copy.  If the key and/or data spills
4889 ** onto overflow pages, then accessPayload() must be used to reassemble
4890 ** the key/data and copy it into a preallocated buffer.
4891 **
4892 ** The pointer returned by this routine looks directly into the cached
4893 ** page of the database.  The data might change or move the next time
4894 ** any btree routine is called.
4895 */
4896 static const void *fetchPayload(
4897   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4898   u32 *pAmt            /* Write the number of available bytes here */
4899 ){
4900   int amt;
4901   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
4902   assert( pCur->eState==CURSOR_VALID );
4903   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4904   assert( cursorOwnsBtShared(pCur) );
4905   assert( pCur->ix<pCur->pPage->nCell );
4906   assert( pCur->info.nSize>0 );
4907   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
4908   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
4909   amt = pCur->info.nLocal;
4910   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
4911     /* There is too little space on the page for the expected amount
4912     ** of local content. Database must be corrupt. */
4913     assert( CORRUPT_DB );
4914     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
4915   }
4916   *pAmt = (u32)amt;
4917   return (void*)pCur->info.pPayload;
4918 }
4919 
4920 
4921 /*
4922 ** For the entry that cursor pCur is point to, return as
4923 ** many bytes of the key or data as are available on the local
4924 ** b-tree page.  Write the number of available bytes into *pAmt.
4925 **
4926 ** The pointer returned is ephemeral.  The key/data may move
4927 ** or be destroyed on the next call to any Btree routine,
4928 ** including calls from other threads against the same cache.
4929 ** Hence, a mutex on the BtShared should be held prior to calling
4930 ** this routine.
4931 **
4932 ** These routines is used to get quick access to key and data
4933 ** in the common case where no overflow pages are used.
4934 */
4935 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
4936   return fetchPayload(pCur, pAmt);
4937 }
4938 
4939 
4940 /*
4941 ** Move the cursor down to a new child page.  The newPgno argument is the
4942 ** page number of the child page to move to.
4943 **
4944 ** This function returns SQLITE_CORRUPT if the page-header flags field of
4945 ** the new child page does not match the flags field of the parent (i.e.
4946 ** if an intkey page appears to be the parent of a non-intkey page, or
4947 ** vice-versa).
4948 */
4949 static int moveToChild(BtCursor *pCur, u32 newPgno){
4950   BtShared *pBt = pCur->pBt;
4951 
4952   assert( cursorOwnsBtShared(pCur) );
4953   assert( pCur->eState==CURSOR_VALID );
4954   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4955   assert( pCur->iPage>=0 );
4956   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4957     return SQLITE_CORRUPT_BKPT;
4958   }
4959   pCur->info.nSize = 0;
4960   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4961   pCur->aiIdx[pCur->iPage] = pCur->ix;
4962   pCur->apPage[pCur->iPage] = pCur->pPage;
4963   pCur->ix = 0;
4964   pCur->iPage++;
4965   return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
4966 }
4967 
4968 #ifdef SQLITE_DEBUG
4969 /*
4970 ** Page pParent is an internal (non-leaf) tree page. This function
4971 ** asserts that page number iChild is the left-child if the iIdx'th
4972 ** cell in page pParent. Or, if iIdx is equal to the total number of
4973 ** cells in pParent, that page number iChild is the right-child of
4974 ** the page.
4975 */
4976 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4977   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
4978                             ** in a corrupt database */
4979   assert( iIdx<=pParent->nCell );
4980   if( iIdx==pParent->nCell ){
4981     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4982   }else{
4983     assert( get4byte(findCell(pParent, iIdx))==iChild );
4984   }
4985 }
4986 #else
4987 #  define assertParentIndex(x,y,z)
4988 #endif
4989 
4990 /*
4991 ** Move the cursor up to the parent page.
4992 **
4993 ** pCur->idx is set to the cell index that contains the pointer
4994 ** to the page we are coming from.  If we are coming from the
4995 ** right-most child page then pCur->idx is set to one more than
4996 ** the largest cell index.
4997 */
4998 static void moveToParent(BtCursor *pCur){
4999   MemPage *pLeaf;
5000   assert( cursorOwnsBtShared(pCur) );
5001   assert( pCur->eState==CURSOR_VALID );
5002   assert( pCur->iPage>0 );
5003   assert( pCur->pPage );
5004   assertParentIndex(
5005     pCur->apPage[pCur->iPage-1],
5006     pCur->aiIdx[pCur->iPage-1],
5007     pCur->pPage->pgno
5008   );
5009   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5010   pCur->info.nSize = 0;
5011   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5012   pCur->ix = pCur->aiIdx[pCur->iPage-1];
5013   pLeaf = pCur->pPage;
5014   pCur->pPage = pCur->apPage[--pCur->iPage];
5015   releasePageNotNull(pLeaf);
5016 }
5017 
5018 /*
5019 ** Move the cursor to point to the root page of its b-tree structure.
5020 **
5021 ** If the table has a virtual root page, then the cursor is moved to point
5022 ** to the virtual root page instead of the actual root page. A table has a
5023 ** virtual root page when the actual root page contains no cells and a
5024 ** single child page. This can only happen with the table rooted at page 1.
5025 **
5026 ** If the b-tree structure is empty, the cursor state is set to
5027 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5028 ** the cursor is set to point to the first cell located on the root
5029 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5030 **
5031 ** If this function returns successfully, it may be assumed that the
5032 ** page-header flags indicate that the [virtual] root-page is the expected
5033 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5034 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5035 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5036 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5037 ** b-tree).
5038 */
5039 static int moveToRoot(BtCursor *pCur){
5040   MemPage *pRoot;
5041   int rc = SQLITE_OK;
5042 
5043   assert( cursorOwnsBtShared(pCur) );
5044   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5045   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
5046   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
5047   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5048   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5049 
5050   if( pCur->iPage>=0 ){
5051     if( pCur->iPage ){
5052       releasePageNotNull(pCur->pPage);
5053       while( --pCur->iPage ){
5054         releasePageNotNull(pCur->apPage[pCur->iPage]);
5055       }
5056       pCur->pPage = pCur->apPage[0];
5057       goto skip_init;
5058     }
5059   }else if( pCur->pgnoRoot==0 ){
5060     pCur->eState = CURSOR_INVALID;
5061     return SQLITE_EMPTY;
5062   }else{
5063     assert( pCur->iPage==(-1) );
5064     if( pCur->eState>=CURSOR_REQUIRESEEK ){
5065       if( pCur->eState==CURSOR_FAULT ){
5066         assert( pCur->skipNext!=SQLITE_OK );
5067         return pCur->skipNext;
5068       }
5069       sqlite3BtreeClearCursor(pCur);
5070     }
5071     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5072                         0, pCur->curPagerFlags);
5073     if( rc!=SQLITE_OK ){
5074       pCur->eState = CURSOR_INVALID;
5075       return rc;
5076     }
5077     pCur->iPage = 0;
5078     pCur->curIntKey = pCur->pPage->intKey;
5079   }
5080   pRoot = pCur->pPage;
5081   assert( pRoot->pgno==pCur->pgnoRoot );
5082 
5083   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5084   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5085   ** NULL, the caller expects a table b-tree. If this is not the case,
5086   ** return an SQLITE_CORRUPT error.
5087   **
5088   ** Earlier versions of SQLite assumed that this test could not fail
5089   ** if the root page was already loaded when this function was called (i.e.
5090   ** if pCur->iPage>=0). But this is not so if the database is corrupted
5091   ** in such a way that page pRoot is linked into a second b-tree table
5092   ** (or the freelist).  */
5093   assert( pRoot->intKey==1 || pRoot->intKey==0 );
5094   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5095     return SQLITE_CORRUPT_PAGE(pCur->pPage);
5096   }
5097 
5098 skip_init:
5099   pCur->ix = 0;
5100   pCur->info.nSize = 0;
5101   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5102 
5103   pRoot = pCur->pPage;
5104   if( pRoot->nCell>0 ){
5105     pCur->eState = CURSOR_VALID;
5106   }else if( !pRoot->leaf ){
5107     Pgno subpage;
5108     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5109     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5110     pCur->eState = CURSOR_VALID;
5111     rc = moveToChild(pCur, subpage);
5112   }else{
5113     pCur->eState = CURSOR_INVALID;
5114     rc = SQLITE_EMPTY;
5115   }
5116   return rc;
5117 }
5118 
5119 /*
5120 ** Move the cursor down to the left-most leaf entry beneath the
5121 ** entry to which it is currently pointing.
5122 **
5123 ** The left-most leaf is the one with the smallest key - the first
5124 ** in ascending order.
5125 */
5126 static int moveToLeftmost(BtCursor *pCur){
5127   Pgno pgno;
5128   int rc = SQLITE_OK;
5129   MemPage *pPage;
5130 
5131   assert( cursorOwnsBtShared(pCur) );
5132   assert( pCur->eState==CURSOR_VALID );
5133   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5134     assert( pCur->ix<pPage->nCell );
5135     pgno = get4byte(findCell(pPage, pCur->ix));
5136     rc = moveToChild(pCur, pgno);
5137   }
5138   return rc;
5139 }
5140 
5141 /*
5142 ** Move the cursor down to the right-most leaf entry beneath the
5143 ** page to which it is currently pointing.  Notice the difference
5144 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5145 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5146 ** finds the right-most entry beneath the *page*.
5147 **
5148 ** The right-most entry is the one with the largest key - the last
5149 ** key in ascending order.
5150 */
5151 static int moveToRightmost(BtCursor *pCur){
5152   Pgno pgno;
5153   int rc = SQLITE_OK;
5154   MemPage *pPage = 0;
5155 
5156   assert( cursorOwnsBtShared(pCur) );
5157   assert( pCur->eState==CURSOR_VALID );
5158   while( !(pPage = pCur->pPage)->leaf ){
5159     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5160     pCur->ix = pPage->nCell;
5161     rc = moveToChild(pCur, pgno);
5162     if( rc ) return rc;
5163   }
5164   pCur->ix = pPage->nCell-1;
5165   assert( pCur->info.nSize==0 );
5166   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5167   return SQLITE_OK;
5168 }
5169 
5170 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5171 ** on success.  Set *pRes to 0 if the cursor actually points to something
5172 ** or set *pRes to 1 if the table is empty.
5173 */
5174 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5175   int rc;
5176 
5177   assert( cursorOwnsBtShared(pCur) );
5178   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5179   rc = moveToRoot(pCur);
5180   if( rc==SQLITE_OK ){
5181     assert( pCur->pPage->nCell>0 );
5182     *pRes = 0;
5183     rc = moveToLeftmost(pCur);
5184   }else if( rc==SQLITE_EMPTY ){
5185     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5186     *pRes = 1;
5187     rc = SQLITE_OK;
5188   }
5189   return rc;
5190 }
5191 
5192 /*
5193 ** This function is a no-op if cursor pCur does not point to a valid row.
5194 ** Otherwise, if pCur is valid, configure it so that the next call to
5195 ** sqlite3BtreeNext() is a no-op.
5196 */
5197 #ifndef SQLITE_OMIT_WINDOWFUNC
5198 void sqlite3BtreeSkipNext(BtCursor *pCur){
5199   /* We believe that the cursor must always be in the valid state when
5200   ** this routine is called, but the proof is difficult, so we add an
5201   ** ALWaYS() test just in case we are wrong. */
5202   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
5203     pCur->eState = CURSOR_SKIPNEXT;
5204     pCur->skipNext = 1;
5205   }
5206 }
5207 #endif /* SQLITE_OMIT_WINDOWFUNC */
5208 
5209 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5210 ** on success.  Set *pRes to 0 if the cursor actually points to something
5211 ** or set *pRes to 1 if the table is empty.
5212 */
5213 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5214   int rc;
5215 
5216   assert( cursorOwnsBtShared(pCur) );
5217   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5218 
5219   /* If the cursor already points to the last entry, this is a no-op. */
5220   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5221 #ifdef SQLITE_DEBUG
5222     /* This block serves to assert() that the cursor really does point
5223     ** to the last entry in the b-tree. */
5224     int ii;
5225     for(ii=0; ii<pCur->iPage; ii++){
5226       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5227     }
5228     assert( pCur->ix==pCur->pPage->nCell-1 );
5229     assert( pCur->pPage->leaf );
5230 #endif
5231     return SQLITE_OK;
5232   }
5233 
5234   rc = moveToRoot(pCur);
5235   if( rc==SQLITE_OK ){
5236     assert( pCur->eState==CURSOR_VALID );
5237     *pRes = 0;
5238     rc = moveToRightmost(pCur);
5239     if( rc==SQLITE_OK ){
5240       pCur->curFlags |= BTCF_AtLast;
5241     }else{
5242       pCur->curFlags &= ~BTCF_AtLast;
5243     }
5244   }else if( rc==SQLITE_EMPTY ){
5245     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5246     *pRes = 1;
5247     rc = SQLITE_OK;
5248   }
5249   return rc;
5250 }
5251 
5252 /* Move the cursor so that it points to an entry near the key
5253 ** specified by pIdxKey or intKey.   Return a success code.
5254 **
5255 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
5256 ** must be NULL.  For index tables, pIdxKey is used and intKey
5257 ** is ignored.
5258 **
5259 ** If an exact match is not found, then the cursor is always
5260 ** left pointing at a leaf page which would hold the entry if it
5261 ** were present.  The cursor might point to an entry that comes
5262 ** before or after the key.
5263 **
5264 ** An integer is written into *pRes which is the result of
5265 ** comparing the key with the entry to which the cursor is
5266 ** pointing.  The meaning of the integer written into
5267 ** *pRes is as follows:
5268 **
5269 **     *pRes<0      The cursor is left pointing at an entry that
5270 **                  is smaller than intKey/pIdxKey or if the table is empty
5271 **                  and the cursor is therefore left point to nothing.
5272 **
5273 **     *pRes==0     The cursor is left pointing at an entry that
5274 **                  exactly matches intKey/pIdxKey.
5275 **
5276 **     *pRes>0      The cursor is left pointing at an entry that
5277 **                  is larger than intKey/pIdxKey.
5278 **
5279 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5280 ** exists an entry in the table that exactly matches pIdxKey.
5281 */
5282 int sqlite3BtreeMovetoUnpacked(
5283   BtCursor *pCur,          /* The cursor to be moved */
5284   UnpackedRecord *pIdxKey, /* Unpacked index key */
5285   i64 intKey,              /* The table key */
5286   int biasRight,           /* If true, bias the search to the high end */
5287   int *pRes                /* Write search results here */
5288 ){
5289   int rc;
5290   RecordCompare xRecordCompare;
5291 
5292   assert( cursorOwnsBtShared(pCur) );
5293   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5294   assert( pRes );
5295   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5296   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5297 
5298   /* If the cursor is already positioned at the point we are trying
5299   ** to move to, then just return without doing any work */
5300   if( pIdxKey==0
5301    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5302   ){
5303     if( pCur->info.nKey==intKey ){
5304       *pRes = 0;
5305       return SQLITE_OK;
5306     }
5307     if( pCur->info.nKey<intKey ){
5308       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5309         *pRes = -1;
5310         return SQLITE_OK;
5311       }
5312       /* If the requested key is one more than the previous key, then
5313       ** try to get there using sqlite3BtreeNext() rather than a full
5314       ** binary search.  This is an optimization only.  The correct answer
5315       ** is still obtained without this case, only a little more slowely */
5316       if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5317         *pRes = 0;
5318         rc = sqlite3BtreeNext(pCur, 0);
5319         if( rc==SQLITE_OK ){
5320           getCellInfo(pCur);
5321           if( pCur->info.nKey==intKey ){
5322             return SQLITE_OK;
5323           }
5324         }else if( rc==SQLITE_DONE ){
5325           rc = SQLITE_OK;
5326         }else{
5327           return rc;
5328         }
5329       }
5330     }
5331   }
5332 
5333   if( pIdxKey ){
5334     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5335     pIdxKey->errCode = 0;
5336     assert( pIdxKey->default_rc==1
5337          || pIdxKey->default_rc==0
5338          || pIdxKey->default_rc==-1
5339     );
5340   }else{
5341     xRecordCompare = 0; /* All keys are integers */
5342   }
5343 
5344   rc = moveToRoot(pCur);
5345   if( rc ){
5346     if( rc==SQLITE_EMPTY ){
5347       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5348       *pRes = -1;
5349       return SQLITE_OK;
5350     }
5351     return rc;
5352   }
5353   assert( pCur->pPage );
5354   assert( pCur->pPage->isInit );
5355   assert( pCur->eState==CURSOR_VALID );
5356   assert( pCur->pPage->nCell > 0 );
5357   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5358   assert( pCur->curIntKey || pIdxKey );
5359   for(;;){
5360     int lwr, upr, idx, c;
5361     Pgno chldPg;
5362     MemPage *pPage = pCur->pPage;
5363     u8 *pCell;                          /* Pointer to current cell in pPage */
5364 
5365     /* pPage->nCell must be greater than zero. If this is the root-page
5366     ** the cursor would have been INVALID above and this for(;;) loop
5367     ** not run. If this is not the root-page, then the moveToChild() routine
5368     ** would have already detected db corruption. Similarly, pPage must
5369     ** be the right kind (index or table) of b-tree page. Otherwise
5370     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5371     assert( pPage->nCell>0 );
5372     assert( pPage->intKey==(pIdxKey==0) );
5373     lwr = 0;
5374     upr = pPage->nCell-1;
5375     assert( biasRight==0 || biasRight==1 );
5376     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5377     pCur->ix = (u16)idx;
5378     if( xRecordCompare==0 ){
5379       for(;;){
5380         i64 nCellKey;
5381         pCell = findCellPastPtr(pPage, idx);
5382         if( pPage->intKeyLeaf ){
5383           while( 0x80 <= *(pCell++) ){
5384             if( pCell>=pPage->aDataEnd ){
5385               return SQLITE_CORRUPT_PAGE(pPage);
5386             }
5387           }
5388         }
5389         getVarint(pCell, (u64*)&nCellKey);
5390         if( nCellKey<intKey ){
5391           lwr = idx+1;
5392           if( lwr>upr ){ c = -1; break; }
5393         }else if( nCellKey>intKey ){
5394           upr = idx-1;
5395           if( lwr>upr ){ c = +1; break; }
5396         }else{
5397           assert( nCellKey==intKey );
5398           pCur->ix = (u16)idx;
5399           if( !pPage->leaf ){
5400             lwr = idx;
5401             goto moveto_next_layer;
5402           }else{
5403             pCur->curFlags |= BTCF_ValidNKey;
5404             pCur->info.nKey = nCellKey;
5405             pCur->info.nSize = 0;
5406             *pRes = 0;
5407             return SQLITE_OK;
5408           }
5409         }
5410         assert( lwr+upr>=0 );
5411         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5412       }
5413     }else{
5414       for(;;){
5415         int nCell;  /* Size of the pCell cell in bytes */
5416         pCell = findCellPastPtr(pPage, idx);
5417 
5418         /* The maximum supported page-size is 65536 bytes. This means that
5419         ** the maximum number of record bytes stored on an index B-Tree
5420         ** page is less than 16384 bytes and may be stored as a 2-byte
5421         ** varint. This information is used to attempt to avoid parsing
5422         ** the entire cell by checking for the cases where the record is
5423         ** stored entirely within the b-tree page by inspecting the first
5424         ** 2 bytes of the cell.
5425         */
5426         nCell = pCell[0];
5427         if( nCell<=pPage->max1bytePayload ){
5428           /* This branch runs if the record-size field of the cell is a
5429           ** single byte varint and the record fits entirely on the main
5430           ** b-tree page.  */
5431           testcase( pCell+nCell+1==pPage->aDataEnd );
5432           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5433         }else if( !(pCell[1] & 0x80)
5434           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5435         ){
5436           /* The record-size field is a 2 byte varint and the record
5437           ** fits entirely on the main b-tree page.  */
5438           testcase( pCell+nCell+2==pPage->aDataEnd );
5439           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5440         }else{
5441           /* The record flows over onto one or more overflow pages. In
5442           ** this case the whole cell needs to be parsed, a buffer allocated
5443           ** and accessPayload() used to retrieve the record into the
5444           ** buffer before VdbeRecordCompare() can be called.
5445           **
5446           ** If the record is corrupt, the xRecordCompare routine may read
5447           ** up to two varints past the end of the buffer. An extra 18
5448           ** bytes of padding is allocated at the end of the buffer in
5449           ** case this happens.  */
5450           void *pCellKey;
5451           u8 * const pCellBody = pCell - pPage->childPtrSize;
5452           pPage->xParseCell(pPage, pCellBody, &pCur->info);
5453           nCell = (int)pCur->info.nKey;
5454           testcase( nCell<0 );   /* True if key size is 2^32 or more */
5455           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5456           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5457           testcase( nCell==2 );  /* Minimum legal index key size */
5458           if( nCell<2 ){
5459             rc = SQLITE_CORRUPT_PAGE(pPage);
5460             goto moveto_finish;
5461           }
5462           pCellKey = sqlite3Malloc( nCell+18 );
5463           if( pCellKey==0 ){
5464             rc = SQLITE_NOMEM_BKPT;
5465             goto moveto_finish;
5466           }
5467           pCur->ix = (u16)idx;
5468           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5469           pCur->curFlags &= ~BTCF_ValidOvfl;
5470           if( rc ){
5471             sqlite3_free(pCellKey);
5472             goto moveto_finish;
5473           }
5474           c = xRecordCompare(nCell, pCellKey, pIdxKey);
5475           sqlite3_free(pCellKey);
5476         }
5477         assert(
5478             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5479          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5480         );
5481         if( c<0 ){
5482           lwr = idx+1;
5483         }else if( c>0 ){
5484           upr = idx-1;
5485         }else{
5486           assert( c==0 );
5487           *pRes = 0;
5488           rc = SQLITE_OK;
5489           pCur->ix = (u16)idx;
5490           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5491           goto moveto_finish;
5492         }
5493         if( lwr>upr ) break;
5494         assert( lwr+upr>=0 );
5495         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5496       }
5497     }
5498     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5499     assert( pPage->isInit );
5500     if( pPage->leaf ){
5501       assert( pCur->ix<pCur->pPage->nCell );
5502       pCur->ix = (u16)idx;
5503       *pRes = c;
5504       rc = SQLITE_OK;
5505       goto moveto_finish;
5506     }
5507 moveto_next_layer:
5508     if( lwr>=pPage->nCell ){
5509       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5510     }else{
5511       chldPg = get4byte(findCell(pPage, lwr));
5512     }
5513     pCur->ix = (u16)lwr;
5514     rc = moveToChild(pCur, chldPg);
5515     if( rc ) break;
5516   }
5517 moveto_finish:
5518   pCur->info.nSize = 0;
5519   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5520   return rc;
5521 }
5522 
5523 
5524 /*
5525 ** Return TRUE if the cursor is not pointing at an entry of the table.
5526 **
5527 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5528 ** past the last entry in the table or sqlite3BtreePrev() moves past
5529 ** the first entry.  TRUE is also returned if the table is empty.
5530 */
5531 int sqlite3BtreeEof(BtCursor *pCur){
5532   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5533   ** have been deleted? This API will need to change to return an error code
5534   ** as well as the boolean result value.
5535   */
5536   return (CURSOR_VALID!=pCur->eState);
5537 }
5538 
5539 /*
5540 ** Return an estimate for the number of rows in the table that pCur is
5541 ** pointing to.  Return a negative number if no estimate is currently
5542 ** available.
5543 */
5544 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5545   i64 n;
5546   u8 i;
5547 
5548   assert( cursorOwnsBtShared(pCur) );
5549   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5550 
5551   /* Currently this interface is only called by the OP_IfSmaller
5552   ** opcode, and it that case the cursor will always be valid and
5553   ** will always point to a leaf node. */
5554   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5555   if( NEVER(pCur->pPage->leaf==0) ) return -1;
5556 
5557   n = pCur->pPage->nCell;
5558   for(i=0; i<pCur->iPage; i++){
5559     n *= pCur->apPage[i]->nCell;
5560   }
5561   return n;
5562 }
5563 
5564 /*
5565 ** Advance the cursor to the next entry in the database.
5566 ** Return value:
5567 **
5568 **    SQLITE_OK        success
5569 **    SQLITE_DONE      cursor is already pointing at the last element
5570 **    otherwise        some kind of error occurred
5571 **
5572 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
5573 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5574 ** to the next cell on the current page.  The (slower) btreeNext() helper
5575 ** routine is called when it is necessary to move to a different page or
5576 ** to restore the cursor.
5577 **
5578 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5579 ** cursor corresponds to an SQL index and this routine could have been
5580 ** skipped if the SQL index had been a unique index.  The F argument
5581 ** is a hint to the implement.  SQLite btree implementation does not use
5582 ** this hint, but COMDB2 does.
5583 */
5584 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5585   int rc;
5586   int idx;
5587   MemPage *pPage;
5588 
5589   assert( cursorOwnsBtShared(pCur) );
5590   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5591   if( pCur->eState!=CURSOR_VALID ){
5592     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5593     rc = restoreCursorPosition(pCur);
5594     if( rc!=SQLITE_OK ){
5595       return rc;
5596     }
5597     if( CURSOR_INVALID==pCur->eState ){
5598       return SQLITE_DONE;
5599     }
5600     if( pCur->skipNext ){
5601       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5602       pCur->eState = CURSOR_VALID;
5603       if( pCur->skipNext>0 ){
5604         pCur->skipNext = 0;
5605         return SQLITE_OK;
5606       }
5607       pCur->skipNext = 0;
5608     }
5609   }
5610 
5611   pPage = pCur->pPage;
5612   idx = ++pCur->ix;
5613   if( !pPage->isInit ){
5614     /* The only known way for this to happen is for there to be a
5615     ** recursive SQL function that does a DELETE operation as part of a
5616     ** SELECT which deletes content out from under an active cursor
5617     ** in a corrupt database file where the table being DELETE-ed from
5618     ** has pages in common with the table being queried.  See TH3
5619     ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5620     ** example. */
5621     return SQLITE_CORRUPT_BKPT;
5622   }
5623 
5624   /* If the database file is corrupt, it is possible for the value of idx
5625   ** to be invalid here. This can only occur if a second cursor modifies
5626   ** the page while cursor pCur is holding a reference to it. Which can
5627   ** only happen if the database is corrupt in such a way as to link the
5628   ** page into more than one b-tree structure. */
5629   testcase( idx>pPage->nCell );
5630 
5631   if( idx>=pPage->nCell ){
5632     if( !pPage->leaf ){
5633       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5634       if( rc ) return rc;
5635       return moveToLeftmost(pCur);
5636     }
5637     do{
5638       if( pCur->iPage==0 ){
5639         pCur->eState = CURSOR_INVALID;
5640         return SQLITE_DONE;
5641       }
5642       moveToParent(pCur);
5643       pPage = pCur->pPage;
5644     }while( pCur->ix>=pPage->nCell );
5645     if( pPage->intKey ){
5646       return sqlite3BtreeNext(pCur, 0);
5647     }else{
5648       return SQLITE_OK;
5649     }
5650   }
5651   if( pPage->leaf ){
5652     return SQLITE_OK;
5653   }else{
5654     return moveToLeftmost(pCur);
5655   }
5656 }
5657 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5658   MemPage *pPage;
5659   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5660   assert( cursorOwnsBtShared(pCur) );
5661   assert( flags==0 || flags==1 );
5662   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5663   pCur->info.nSize = 0;
5664   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5665   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5666   pPage = pCur->pPage;
5667   if( (++pCur->ix)>=pPage->nCell ){
5668     pCur->ix--;
5669     return btreeNext(pCur);
5670   }
5671   if( pPage->leaf ){
5672     return SQLITE_OK;
5673   }else{
5674     return moveToLeftmost(pCur);
5675   }
5676 }
5677 
5678 /*
5679 ** Step the cursor to the back to the previous entry in the database.
5680 ** Return values:
5681 **
5682 **     SQLITE_OK     success
5683 **     SQLITE_DONE   the cursor is already on the first element of the table
5684 **     otherwise     some kind of error occurred
5685 **
5686 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
5687 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5688 ** to the previous cell on the current page.  The (slower) btreePrevious()
5689 ** helper routine is called when it is necessary to move to a different page
5690 ** or to restore the cursor.
5691 **
5692 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5693 ** the cursor corresponds to an SQL index and this routine could have been
5694 ** skipped if the SQL index had been a unique index.  The F argument is a
5695 ** hint to the implement.  The native SQLite btree implementation does not
5696 ** use this hint, but COMDB2 does.
5697 */
5698 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5699   int rc;
5700   MemPage *pPage;
5701 
5702   assert( cursorOwnsBtShared(pCur) );
5703   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5704   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5705   assert( pCur->info.nSize==0 );
5706   if( pCur->eState!=CURSOR_VALID ){
5707     rc = restoreCursorPosition(pCur);
5708     if( rc!=SQLITE_OK ){
5709       return rc;
5710     }
5711     if( CURSOR_INVALID==pCur->eState ){
5712       return SQLITE_DONE;
5713     }
5714     if( pCur->skipNext ){
5715       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5716       pCur->eState = CURSOR_VALID;
5717       if( pCur->skipNext<0 ){
5718         pCur->skipNext = 0;
5719         return SQLITE_OK;
5720       }
5721       pCur->skipNext = 0;
5722     }
5723   }
5724 
5725   pPage = pCur->pPage;
5726   assert( pPage->isInit );
5727   if( !pPage->leaf ){
5728     int idx = pCur->ix;
5729     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5730     if( rc ) return rc;
5731     rc = moveToRightmost(pCur);
5732   }else{
5733     while( pCur->ix==0 ){
5734       if( pCur->iPage==0 ){
5735         pCur->eState = CURSOR_INVALID;
5736         return SQLITE_DONE;
5737       }
5738       moveToParent(pCur);
5739     }
5740     assert( pCur->info.nSize==0 );
5741     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5742 
5743     pCur->ix--;
5744     pPage = pCur->pPage;
5745     if( pPage->intKey && !pPage->leaf ){
5746       rc = sqlite3BtreePrevious(pCur, 0);
5747     }else{
5748       rc = SQLITE_OK;
5749     }
5750   }
5751   return rc;
5752 }
5753 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5754   assert( cursorOwnsBtShared(pCur) );
5755   assert( flags==0 || flags==1 );
5756   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5757   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5758   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5759   pCur->info.nSize = 0;
5760   if( pCur->eState!=CURSOR_VALID
5761    || pCur->ix==0
5762    || pCur->pPage->leaf==0
5763   ){
5764     return btreePrevious(pCur);
5765   }
5766   pCur->ix--;
5767   return SQLITE_OK;
5768 }
5769 
5770 /*
5771 ** Allocate a new page from the database file.
5772 **
5773 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
5774 ** has already been called on the new page.)  The new page has also
5775 ** been referenced and the calling routine is responsible for calling
5776 ** sqlite3PagerUnref() on the new page when it is done.
5777 **
5778 ** SQLITE_OK is returned on success.  Any other return value indicates
5779 ** an error.  *ppPage is set to NULL in the event of an error.
5780 **
5781 ** If the "nearby" parameter is not 0, then an effort is made to
5782 ** locate a page close to the page number "nearby".  This can be used in an
5783 ** attempt to keep related pages close to each other in the database file,
5784 ** which in turn can make database access faster.
5785 **
5786 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5787 ** anywhere on the free-list, then it is guaranteed to be returned.  If
5788 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5789 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
5790 ** are no restrictions on which page is returned.
5791 */
5792 static int allocateBtreePage(
5793   BtShared *pBt,         /* The btree */
5794   MemPage **ppPage,      /* Store pointer to the allocated page here */
5795   Pgno *pPgno,           /* Store the page number here */
5796   Pgno nearby,           /* Search for a page near this one */
5797   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5798 ){
5799   MemPage *pPage1;
5800   int rc;
5801   u32 n;     /* Number of pages on the freelist */
5802   u32 k;     /* Number of leaves on the trunk of the freelist */
5803   MemPage *pTrunk = 0;
5804   MemPage *pPrevTrunk = 0;
5805   Pgno mxPage;     /* Total size of the database file */
5806 
5807   assert( sqlite3_mutex_held(pBt->mutex) );
5808   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5809   pPage1 = pBt->pPage1;
5810   mxPage = btreePagecount(pBt);
5811   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5812   ** stores stores the total number of pages on the freelist. */
5813   n = get4byte(&pPage1->aData[36]);
5814   testcase( n==mxPage-1 );
5815   if( n>=mxPage ){
5816     return SQLITE_CORRUPT_BKPT;
5817   }
5818   if( n>0 ){
5819     /* There are pages on the freelist.  Reuse one of those pages. */
5820     Pgno iTrunk;
5821     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5822     u32 nSearch = 0;   /* Count of the number of search attempts */
5823 
5824     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5825     ** shows that the page 'nearby' is somewhere on the free-list, then
5826     ** the entire-list will be searched for that page.
5827     */
5828 #ifndef SQLITE_OMIT_AUTOVACUUM
5829     if( eMode==BTALLOC_EXACT ){
5830       if( nearby<=mxPage ){
5831         u8 eType;
5832         assert( nearby>0 );
5833         assert( pBt->autoVacuum );
5834         rc = ptrmapGet(pBt, nearby, &eType, 0);
5835         if( rc ) return rc;
5836         if( eType==PTRMAP_FREEPAGE ){
5837           searchList = 1;
5838         }
5839       }
5840     }else if( eMode==BTALLOC_LE ){
5841       searchList = 1;
5842     }
5843 #endif
5844 
5845     /* Decrement the free-list count by 1. Set iTrunk to the index of the
5846     ** first free-list trunk page. iPrevTrunk is initially 1.
5847     */
5848     rc = sqlite3PagerWrite(pPage1->pDbPage);
5849     if( rc ) return rc;
5850     put4byte(&pPage1->aData[36], n-1);
5851 
5852     /* The code within this loop is run only once if the 'searchList' variable
5853     ** is not true. Otherwise, it runs once for each trunk-page on the
5854     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5855     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5856     */
5857     do {
5858       pPrevTrunk = pTrunk;
5859       if( pPrevTrunk ){
5860         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5861         ** is the page number of the next freelist trunk page in the list or
5862         ** zero if this is the last freelist trunk page. */
5863         iTrunk = get4byte(&pPrevTrunk->aData[0]);
5864       }else{
5865         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5866         ** stores the page number of the first page of the freelist, or zero if
5867         ** the freelist is empty. */
5868         iTrunk = get4byte(&pPage1->aData[32]);
5869       }
5870       testcase( iTrunk==mxPage );
5871       if( iTrunk>mxPage || nSearch++ > n ){
5872         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
5873       }else{
5874         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
5875       }
5876       if( rc ){
5877         pTrunk = 0;
5878         goto end_allocate_page;
5879       }
5880       assert( pTrunk!=0 );
5881       assert( pTrunk->aData!=0 );
5882       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5883       ** is the number of leaf page pointers to follow. */
5884       k = get4byte(&pTrunk->aData[4]);
5885       if( k==0 && !searchList ){
5886         /* The trunk has no leaves and the list is not being searched.
5887         ** So extract the trunk page itself and use it as the newly
5888         ** allocated page */
5889         assert( pPrevTrunk==0 );
5890         rc = sqlite3PagerWrite(pTrunk->pDbPage);
5891         if( rc ){
5892           goto end_allocate_page;
5893         }
5894         *pPgno = iTrunk;
5895         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5896         *ppPage = pTrunk;
5897         pTrunk = 0;
5898         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5899       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
5900         /* Value of k is out of range.  Database corruption */
5901         rc = SQLITE_CORRUPT_PGNO(iTrunk);
5902         goto end_allocate_page;
5903 #ifndef SQLITE_OMIT_AUTOVACUUM
5904       }else if( searchList
5905             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5906       ){
5907         /* The list is being searched and this trunk page is the page
5908         ** to allocate, regardless of whether it has leaves.
5909         */
5910         *pPgno = iTrunk;
5911         *ppPage = pTrunk;
5912         searchList = 0;
5913         rc = sqlite3PagerWrite(pTrunk->pDbPage);
5914         if( rc ){
5915           goto end_allocate_page;
5916         }
5917         if( k==0 ){
5918           if( !pPrevTrunk ){
5919             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5920           }else{
5921             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5922             if( rc!=SQLITE_OK ){
5923               goto end_allocate_page;
5924             }
5925             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5926           }
5927         }else{
5928           /* The trunk page is required by the caller but it contains
5929           ** pointers to free-list leaves. The first leaf becomes a trunk
5930           ** page in this case.
5931           */
5932           MemPage *pNewTrunk;
5933           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
5934           if( iNewTrunk>mxPage ){
5935             rc = SQLITE_CORRUPT_PGNO(iTrunk);
5936             goto end_allocate_page;
5937           }
5938           testcase( iNewTrunk==mxPage );
5939           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
5940           if( rc!=SQLITE_OK ){
5941             goto end_allocate_page;
5942           }
5943           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
5944           if( rc!=SQLITE_OK ){
5945             releasePage(pNewTrunk);
5946             goto end_allocate_page;
5947           }
5948           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5949           put4byte(&pNewTrunk->aData[4], k-1);
5950           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
5951           releasePage(pNewTrunk);
5952           if( !pPrevTrunk ){
5953             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
5954             put4byte(&pPage1->aData[32], iNewTrunk);
5955           }else{
5956             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5957             if( rc ){
5958               goto end_allocate_page;
5959             }
5960             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5961           }
5962         }
5963         pTrunk = 0;
5964         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5965 #endif
5966       }else if( k>0 ){
5967         /* Extract a leaf from the trunk */
5968         u32 closest;
5969         Pgno iPage;
5970         unsigned char *aData = pTrunk->aData;
5971         if( nearby>0 ){
5972           u32 i;
5973           closest = 0;
5974           if( eMode==BTALLOC_LE ){
5975             for(i=0; i<k; i++){
5976               iPage = get4byte(&aData[8+i*4]);
5977               if( iPage<=nearby ){
5978                 closest = i;
5979                 break;
5980               }
5981             }
5982           }else{
5983             int dist;
5984             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5985             for(i=1; i<k; i++){
5986               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5987               if( d2<dist ){
5988                 closest = i;
5989                 dist = d2;
5990               }
5991             }
5992           }
5993         }else{
5994           closest = 0;
5995         }
5996 
5997         iPage = get4byte(&aData[8+closest*4]);
5998         testcase( iPage==mxPage );
5999         if( iPage>mxPage ){
6000           rc = SQLITE_CORRUPT_PGNO(iTrunk);
6001           goto end_allocate_page;
6002         }
6003         testcase( iPage==mxPage );
6004         if( !searchList
6005          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6006         ){
6007           int noContent;
6008           *pPgno = iPage;
6009           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6010                  ": %d more free pages\n",
6011                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
6012           rc = sqlite3PagerWrite(pTrunk->pDbPage);
6013           if( rc ) goto end_allocate_page;
6014           if( closest<k-1 ){
6015             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6016           }
6017           put4byte(&aData[4], k-1);
6018           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6019           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6020           if( rc==SQLITE_OK ){
6021             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6022             if( rc!=SQLITE_OK ){
6023               releasePage(*ppPage);
6024               *ppPage = 0;
6025             }
6026           }
6027           searchList = 0;
6028         }
6029       }
6030       releasePage(pPrevTrunk);
6031       pPrevTrunk = 0;
6032     }while( searchList );
6033   }else{
6034     /* There are no pages on the freelist, so append a new page to the
6035     ** database image.
6036     **
6037     ** Normally, new pages allocated by this block can be requested from the
6038     ** pager layer with the 'no-content' flag set. This prevents the pager
6039     ** from trying to read the pages content from disk. However, if the
6040     ** current transaction has already run one or more incremental-vacuum
6041     ** steps, then the page we are about to allocate may contain content
6042     ** that is required in the event of a rollback. In this case, do
6043     ** not set the no-content flag. This causes the pager to load and journal
6044     ** the current page content before overwriting it.
6045     **
6046     ** Note that the pager will not actually attempt to load or journal
6047     ** content for any page that really does lie past the end of the database
6048     ** file on disk. So the effects of disabling the no-content optimization
6049     ** here are confined to those pages that lie between the end of the
6050     ** database image and the end of the database file.
6051     */
6052     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6053 
6054     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6055     if( rc ) return rc;
6056     pBt->nPage++;
6057     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6058 
6059 #ifndef SQLITE_OMIT_AUTOVACUUM
6060     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6061       /* If *pPgno refers to a pointer-map page, allocate two new pages
6062       ** at the end of the file instead of one. The first allocated page
6063       ** becomes a new pointer-map page, the second is used by the caller.
6064       */
6065       MemPage *pPg = 0;
6066       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6067       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6068       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6069       if( rc==SQLITE_OK ){
6070         rc = sqlite3PagerWrite(pPg->pDbPage);
6071         releasePage(pPg);
6072       }
6073       if( rc ) return rc;
6074       pBt->nPage++;
6075       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6076     }
6077 #endif
6078     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6079     *pPgno = pBt->nPage;
6080 
6081     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6082     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6083     if( rc ) return rc;
6084     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6085     if( rc!=SQLITE_OK ){
6086       releasePage(*ppPage);
6087       *ppPage = 0;
6088     }
6089     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6090   }
6091 
6092   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6093 
6094 end_allocate_page:
6095   releasePage(pTrunk);
6096   releasePage(pPrevTrunk);
6097   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6098   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6099   return rc;
6100 }
6101 
6102 /*
6103 ** This function is used to add page iPage to the database file free-list.
6104 ** It is assumed that the page is not already a part of the free-list.
6105 **
6106 ** The value passed as the second argument to this function is optional.
6107 ** If the caller happens to have a pointer to the MemPage object
6108 ** corresponding to page iPage handy, it may pass it as the second value.
6109 ** Otherwise, it may pass NULL.
6110 **
6111 ** If a pointer to a MemPage object is passed as the second argument,
6112 ** its reference count is not altered by this function.
6113 */
6114 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6115   MemPage *pTrunk = 0;                /* Free-list trunk page */
6116   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
6117   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
6118   MemPage *pPage;                     /* Page being freed. May be NULL. */
6119   int rc;                             /* Return Code */
6120   int nFree;                          /* Initial number of pages on free-list */
6121 
6122   assert( sqlite3_mutex_held(pBt->mutex) );
6123   assert( CORRUPT_DB || iPage>1 );
6124   assert( !pMemPage || pMemPage->pgno==iPage );
6125 
6126   if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
6127   if( pMemPage ){
6128     pPage = pMemPage;
6129     sqlite3PagerRef(pPage->pDbPage);
6130   }else{
6131     pPage = btreePageLookup(pBt, iPage);
6132   }
6133 
6134   /* Increment the free page count on pPage1 */
6135   rc = sqlite3PagerWrite(pPage1->pDbPage);
6136   if( rc ) goto freepage_out;
6137   nFree = get4byte(&pPage1->aData[36]);
6138   put4byte(&pPage1->aData[36], nFree+1);
6139 
6140   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6141     /* If the secure_delete option is enabled, then
6142     ** always fully overwrite deleted information with zeros.
6143     */
6144     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6145      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6146     ){
6147       goto freepage_out;
6148     }
6149     memset(pPage->aData, 0, pPage->pBt->pageSize);
6150   }
6151 
6152   /* If the database supports auto-vacuum, write an entry in the pointer-map
6153   ** to indicate that the page is free.
6154   */
6155   if( ISAUTOVACUUM ){
6156     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6157     if( rc ) goto freepage_out;
6158   }
6159 
6160   /* Now manipulate the actual database free-list structure. There are two
6161   ** possibilities. If the free-list is currently empty, or if the first
6162   ** trunk page in the free-list is full, then this page will become a
6163   ** new free-list trunk page. Otherwise, it will become a leaf of the
6164   ** first trunk page in the current free-list. This block tests if it
6165   ** is possible to add the page as a new free-list leaf.
6166   */
6167   if( nFree!=0 ){
6168     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6169 
6170     iTrunk = get4byte(&pPage1->aData[32]);
6171     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6172     if( rc!=SQLITE_OK ){
6173       goto freepage_out;
6174     }
6175 
6176     nLeaf = get4byte(&pTrunk->aData[4]);
6177     assert( pBt->usableSize>32 );
6178     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6179       rc = SQLITE_CORRUPT_BKPT;
6180       goto freepage_out;
6181     }
6182     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6183       /* In this case there is room on the trunk page to insert the page
6184       ** being freed as a new leaf.
6185       **
6186       ** Note that the trunk page is not really full until it contains
6187       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6188       ** coded.  But due to a coding error in versions of SQLite prior to
6189       ** 3.6.0, databases with freelist trunk pages holding more than
6190       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6191       ** to maintain backwards compatibility with older versions of SQLite,
6192       ** we will continue to restrict the number of entries to usableSize/4 - 8
6193       ** for now.  At some point in the future (once everyone has upgraded
6194       ** to 3.6.0 or later) we should consider fixing the conditional above
6195       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6196       **
6197       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6198       ** avoid using the last six entries in the freelist trunk page array in
6199       ** order that database files created by newer versions of SQLite can be
6200       ** read by older versions of SQLite.
6201       */
6202       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6203       if( rc==SQLITE_OK ){
6204         put4byte(&pTrunk->aData[4], nLeaf+1);
6205         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6206         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6207           sqlite3PagerDontWrite(pPage->pDbPage);
6208         }
6209         rc = btreeSetHasContent(pBt, iPage);
6210       }
6211       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6212       goto freepage_out;
6213     }
6214   }
6215 
6216   /* If control flows to this point, then it was not possible to add the
6217   ** the page being freed as a leaf page of the first trunk in the free-list.
6218   ** Possibly because the free-list is empty, or possibly because the
6219   ** first trunk in the free-list is full. Either way, the page being freed
6220   ** will become the new first trunk page in the free-list.
6221   */
6222   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6223     goto freepage_out;
6224   }
6225   rc = sqlite3PagerWrite(pPage->pDbPage);
6226   if( rc!=SQLITE_OK ){
6227     goto freepage_out;
6228   }
6229   put4byte(pPage->aData, iTrunk);
6230   put4byte(&pPage->aData[4], 0);
6231   put4byte(&pPage1->aData[32], iPage);
6232   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6233 
6234 freepage_out:
6235   if( pPage ){
6236     pPage->isInit = 0;
6237   }
6238   releasePage(pPage);
6239   releasePage(pTrunk);
6240   return rc;
6241 }
6242 static void freePage(MemPage *pPage, int *pRC){
6243   if( (*pRC)==SQLITE_OK ){
6244     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6245   }
6246 }
6247 
6248 /*
6249 ** Free any overflow pages associated with the given Cell.  Store
6250 ** size information about the cell in pInfo.
6251 */
6252 static int clearCell(
6253   MemPage *pPage,          /* The page that contains the Cell */
6254   unsigned char *pCell,    /* First byte of the Cell */
6255   CellInfo *pInfo          /* Size information about the cell */
6256 ){
6257   BtShared *pBt;
6258   Pgno ovflPgno;
6259   int rc;
6260   int nOvfl;
6261   u32 ovflPageSize;
6262 
6263   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6264   pPage->xParseCell(pPage, pCell, pInfo);
6265   if( pInfo->nLocal==pInfo->nPayload ){
6266     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
6267   }
6268   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6269   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6270   if( pCell + pInfo->nSize > pPage->aDataEnd ){
6271     /* Cell extends past end of page */
6272     return SQLITE_CORRUPT_PAGE(pPage);
6273   }
6274   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6275   pBt = pPage->pBt;
6276   assert( pBt->usableSize > 4 );
6277   ovflPageSize = pBt->usableSize - 4;
6278   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6279   assert( nOvfl>0 ||
6280     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6281   );
6282   while( nOvfl-- ){
6283     Pgno iNext = 0;
6284     MemPage *pOvfl = 0;
6285     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6286       /* 0 is not a legal page number and page 1 cannot be an
6287       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6288       ** file the database must be corrupt. */
6289       return SQLITE_CORRUPT_BKPT;
6290     }
6291     if( nOvfl ){
6292       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6293       if( rc ) return rc;
6294     }
6295 
6296     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6297      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6298     ){
6299       /* There is no reason any cursor should have an outstanding reference
6300       ** to an overflow page belonging to a cell that is being deleted/updated.
6301       ** So if there exists more than one reference to this page, then it
6302       ** must not really be an overflow page and the database must be corrupt.
6303       ** It is helpful to detect this before calling freePage2(), as
6304       ** freePage2() may zero the page contents if secure-delete mode is
6305       ** enabled. If this 'overflow' page happens to be a page that the
6306       ** caller is iterating through or using in some other way, this
6307       ** can be problematic.
6308       */
6309       rc = SQLITE_CORRUPT_BKPT;
6310     }else{
6311       rc = freePage2(pBt, pOvfl, ovflPgno);
6312     }
6313 
6314     if( pOvfl ){
6315       sqlite3PagerUnref(pOvfl->pDbPage);
6316     }
6317     if( rc ) return rc;
6318     ovflPgno = iNext;
6319   }
6320   return SQLITE_OK;
6321 }
6322 
6323 /*
6324 ** Create the byte sequence used to represent a cell on page pPage
6325 ** and write that byte sequence into pCell[].  Overflow pages are
6326 ** allocated and filled in as necessary.  The calling procedure
6327 ** is responsible for making sure sufficient space has been allocated
6328 ** for pCell[].
6329 **
6330 ** Note that pCell does not necessary need to point to the pPage->aData
6331 ** area.  pCell might point to some temporary storage.  The cell will
6332 ** be constructed in this temporary area then copied into pPage->aData
6333 ** later.
6334 */
6335 static int fillInCell(
6336   MemPage *pPage,                /* The page that contains the cell */
6337   unsigned char *pCell,          /* Complete text of the cell */
6338   const BtreePayload *pX,        /* Payload with which to construct the cell */
6339   int *pnSize                    /* Write cell size here */
6340 ){
6341   int nPayload;
6342   const u8 *pSrc;
6343   int nSrc, n, rc, mn;
6344   int spaceLeft;
6345   MemPage *pToRelease;
6346   unsigned char *pPrior;
6347   unsigned char *pPayload;
6348   BtShared *pBt;
6349   Pgno pgnoOvfl;
6350   int nHeader;
6351 
6352   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6353 
6354   /* pPage is not necessarily writeable since pCell might be auxiliary
6355   ** buffer space that is separate from the pPage buffer area */
6356   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6357             || sqlite3PagerIswriteable(pPage->pDbPage) );
6358 
6359   /* Fill in the header. */
6360   nHeader = pPage->childPtrSize;
6361   if( pPage->intKey ){
6362     nPayload = pX->nData + pX->nZero;
6363     pSrc = pX->pData;
6364     nSrc = pX->nData;
6365     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6366     nHeader += putVarint32(&pCell[nHeader], nPayload);
6367     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6368   }else{
6369     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6370     nSrc = nPayload = (int)pX->nKey;
6371     pSrc = pX->pKey;
6372     nHeader += putVarint32(&pCell[nHeader], nPayload);
6373   }
6374 
6375   /* Fill in the payload */
6376   pPayload = &pCell[nHeader];
6377   if( nPayload<=pPage->maxLocal ){
6378     /* This is the common case where everything fits on the btree page
6379     ** and no overflow pages are required. */
6380     n = nHeader + nPayload;
6381     testcase( n==3 );
6382     testcase( n==4 );
6383     if( n<4 ) n = 4;
6384     *pnSize = n;
6385     assert( nSrc<=nPayload );
6386     testcase( nSrc<nPayload );
6387     memcpy(pPayload, pSrc, nSrc);
6388     memset(pPayload+nSrc, 0, nPayload-nSrc);
6389     return SQLITE_OK;
6390   }
6391 
6392   /* If we reach this point, it means that some of the content will need
6393   ** to spill onto overflow pages.
6394   */
6395   mn = pPage->minLocal;
6396   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6397   testcase( n==pPage->maxLocal );
6398   testcase( n==pPage->maxLocal+1 );
6399   if( n > pPage->maxLocal ) n = mn;
6400   spaceLeft = n;
6401   *pnSize = n + nHeader + 4;
6402   pPrior = &pCell[nHeader+n];
6403   pToRelease = 0;
6404   pgnoOvfl = 0;
6405   pBt = pPage->pBt;
6406 
6407   /* At this point variables should be set as follows:
6408   **
6409   **   nPayload           Total payload size in bytes
6410   **   pPayload           Begin writing payload here
6411   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6412   **                      that means content must spill into overflow pages.
6413   **   *pnSize            Size of the local cell (not counting overflow pages)
6414   **   pPrior             Where to write the pgno of the first overflow page
6415   **
6416   ** Use a call to btreeParseCellPtr() to verify that the values above
6417   ** were computed correctly.
6418   */
6419 #ifdef SQLITE_DEBUG
6420   {
6421     CellInfo info;
6422     pPage->xParseCell(pPage, pCell, &info);
6423     assert( nHeader==(int)(info.pPayload - pCell) );
6424     assert( info.nKey==pX->nKey );
6425     assert( *pnSize == info.nSize );
6426     assert( spaceLeft == info.nLocal );
6427   }
6428 #endif
6429 
6430   /* Write the payload into the local Cell and any extra into overflow pages */
6431   while( 1 ){
6432     n = nPayload;
6433     if( n>spaceLeft ) n = spaceLeft;
6434 
6435     /* If pToRelease is not zero than pPayload points into the data area
6436     ** of pToRelease.  Make sure pToRelease is still writeable. */
6437     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6438 
6439     /* If pPayload is part of the data area of pPage, then make sure pPage
6440     ** is still writeable */
6441     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6442             || sqlite3PagerIswriteable(pPage->pDbPage) );
6443 
6444     if( nSrc>=n ){
6445       memcpy(pPayload, pSrc, n);
6446     }else if( nSrc>0 ){
6447       n = nSrc;
6448       memcpy(pPayload, pSrc, n);
6449     }else{
6450       memset(pPayload, 0, n);
6451     }
6452     nPayload -= n;
6453     if( nPayload<=0 ) break;
6454     pPayload += n;
6455     pSrc += n;
6456     nSrc -= n;
6457     spaceLeft -= n;
6458     if( spaceLeft==0 ){
6459       MemPage *pOvfl = 0;
6460 #ifndef SQLITE_OMIT_AUTOVACUUM
6461       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6462       if( pBt->autoVacuum ){
6463         do{
6464           pgnoOvfl++;
6465         } while(
6466           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6467         );
6468       }
6469 #endif
6470       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6471 #ifndef SQLITE_OMIT_AUTOVACUUM
6472       /* If the database supports auto-vacuum, and the second or subsequent
6473       ** overflow page is being allocated, add an entry to the pointer-map
6474       ** for that page now.
6475       **
6476       ** If this is the first overflow page, then write a partial entry
6477       ** to the pointer-map. If we write nothing to this pointer-map slot,
6478       ** then the optimistic overflow chain processing in clearCell()
6479       ** may misinterpret the uninitialized values and delete the
6480       ** wrong pages from the database.
6481       */
6482       if( pBt->autoVacuum && rc==SQLITE_OK ){
6483         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6484         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6485         if( rc ){
6486           releasePage(pOvfl);
6487         }
6488       }
6489 #endif
6490       if( rc ){
6491         releasePage(pToRelease);
6492         return rc;
6493       }
6494 
6495       /* If pToRelease is not zero than pPrior points into the data area
6496       ** of pToRelease.  Make sure pToRelease is still writeable. */
6497       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6498 
6499       /* If pPrior is part of the data area of pPage, then make sure pPage
6500       ** is still writeable */
6501       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6502             || sqlite3PagerIswriteable(pPage->pDbPage) );
6503 
6504       put4byte(pPrior, pgnoOvfl);
6505       releasePage(pToRelease);
6506       pToRelease = pOvfl;
6507       pPrior = pOvfl->aData;
6508       put4byte(pPrior, 0);
6509       pPayload = &pOvfl->aData[4];
6510       spaceLeft = pBt->usableSize - 4;
6511     }
6512   }
6513   releasePage(pToRelease);
6514   return SQLITE_OK;
6515 }
6516 
6517 /*
6518 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6519 ** The cell content is not freed or deallocated.  It is assumed that
6520 ** the cell content has been copied someplace else.  This routine just
6521 ** removes the reference to the cell from pPage.
6522 **
6523 ** "sz" must be the number of bytes in the cell.
6524 */
6525 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6526   u32 pc;         /* Offset to cell content of cell being deleted */
6527   u8 *data;       /* pPage->aData */
6528   u8 *ptr;        /* Used to move bytes around within data[] */
6529   int rc;         /* The return code */
6530   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6531 
6532   if( *pRC ) return;
6533   assert( idx>=0 && idx<pPage->nCell );
6534   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6535   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6536   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6537   data = pPage->aData;
6538   ptr = &pPage->aCellIdx[2*idx];
6539   pc = get2byte(ptr);
6540   hdr = pPage->hdrOffset;
6541   testcase( pc==get2byte(&data[hdr+5]) );
6542   testcase( pc+sz==pPage->pBt->usableSize );
6543   if( pc+sz > pPage->pBt->usableSize ){
6544     *pRC = SQLITE_CORRUPT_BKPT;
6545     return;
6546   }
6547   rc = freeSpace(pPage, pc, sz);
6548   if( rc ){
6549     *pRC = rc;
6550     return;
6551   }
6552   pPage->nCell--;
6553   if( pPage->nCell==0 ){
6554     memset(&data[hdr+1], 0, 4);
6555     data[hdr+7] = 0;
6556     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6557     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6558                        - pPage->childPtrSize - 8;
6559   }else{
6560     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6561     put2byte(&data[hdr+3], pPage->nCell);
6562     pPage->nFree += 2;
6563   }
6564 }
6565 
6566 /*
6567 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6568 ** content of the cell.
6569 **
6570 ** If the cell content will fit on the page, then put it there.  If it
6571 ** will not fit, then make a copy of the cell content into pTemp if
6572 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6573 ** in pPage->apOvfl[] and make it point to the cell content (either
6574 ** in pTemp or the original pCell) and also record its index.
6575 ** Allocating a new entry in pPage->aCell[] implies that
6576 ** pPage->nOverflow is incremented.
6577 **
6578 ** *pRC must be SQLITE_OK when this routine is called.
6579 */
6580 static void insertCell(
6581   MemPage *pPage,   /* Page into which we are copying */
6582   int i,            /* New cell becomes the i-th cell of the page */
6583   u8 *pCell,        /* Content of the new cell */
6584   int sz,           /* Bytes of content in pCell */
6585   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6586   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6587   int *pRC          /* Read and write return code from here */
6588 ){
6589   int idx = 0;      /* Where to write new cell content in data[] */
6590   int j;            /* Loop counter */
6591   u8 *data;         /* The content of the whole page */
6592   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6593 
6594   assert( *pRC==SQLITE_OK );
6595   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6596   assert( MX_CELL(pPage->pBt)<=10921 );
6597   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6598   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6599   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6600   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6601   /* The cell should normally be sized correctly.  However, when moving a
6602   ** malformed cell from a leaf page to an interior page, if the cell size
6603   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6604   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
6605   ** the term after the || in the following assert(). */
6606   assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
6607   if( pPage->nOverflow || sz+2>pPage->nFree ){
6608     if( pTemp ){
6609       memcpy(pTemp, pCell, sz);
6610       pCell = pTemp;
6611     }
6612     if( iChild ){
6613       put4byte(pCell, iChild);
6614     }
6615     j = pPage->nOverflow++;
6616     /* Comparison against ArraySize-1 since we hold back one extra slot
6617     ** as a contingency.  In other words, never need more than 3 overflow
6618     ** slots but 4 are allocated, just to be safe. */
6619     assert( j < ArraySize(pPage->apOvfl)-1 );
6620     pPage->apOvfl[j] = pCell;
6621     pPage->aiOvfl[j] = (u16)i;
6622 
6623     /* When multiple overflows occur, they are always sequential and in
6624     ** sorted order.  This invariants arise because multiple overflows can
6625     ** only occur when inserting divider cells into the parent page during
6626     ** balancing, and the dividers are adjacent and sorted.
6627     */
6628     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6629     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6630   }else{
6631     int rc = sqlite3PagerWrite(pPage->pDbPage);
6632     if( rc!=SQLITE_OK ){
6633       *pRC = rc;
6634       return;
6635     }
6636     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6637     data = pPage->aData;
6638     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6639     rc = allocateSpace(pPage, sz, &idx);
6640     if( rc ){ *pRC = rc; return; }
6641     /* The allocateSpace() routine guarantees the following properties
6642     ** if it returns successfully */
6643     assert( idx >= 0 );
6644     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6645     assert( idx+sz <= (int)pPage->pBt->usableSize );
6646     pPage->nFree -= (u16)(2 + sz);
6647     memcpy(&data[idx], pCell, sz);
6648     if( iChild ){
6649       put4byte(&data[idx], iChild);
6650     }
6651     pIns = pPage->aCellIdx + i*2;
6652     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6653     put2byte(pIns, idx);
6654     pPage->nCell++;
6655     /* increment the cell count */
6656     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6657     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
6658 #ifndef SQLITE_OMIT_AUTOVACUUM
6659     if( pPage->pBt->autoVacuum ){
6660       /* The cell may contain a pointer to an overflow page. If so, write
6661       ** the entry for the overflow page into the pointer map.
6662       */
6663       ptrmapPutOvflPtr(pPage, pCell, pRC);
6664     }
6665 #endif
6666   }
6667 }
6668 
6669 /*
6670 ** A CellArray object contains a cache of pointers and sizes for a
6671 ** consecutive sequence of cells that might be held on multiple pages.
6672 */
6673 typedef struct CellArray CellArray;
6674 struct CellArray {
6675   int nCell;              /* Number of cells in apCell[] */
6676   MemPage *pRef;          /* Reference page */
6677   u8 **apCell;            /* All cells begin balanced */
6678   u16 *szCell;            /* Local size of all cells in apCell[] */
6679 };
6680 
6681 /*
6682 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6683 ** computed.
6684 */
6685 static void populateCellCache(CellArray *p, int idx, int N){
6686   assert( idx>=0 && idx+N<=p->nCell );
6687   while( N>0 ){
6688     assert( p->apCell[idx]!=0 );
6689     if( p->szCell[idx]==0 ){
6690       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6691     }else{
6692       assert( CORRUPT_DB ||
6693               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6694     }
6695     idx++;
6696     N--;
6697   }
6698 }
6699 
6700 /*
6701 ** Return the size of the Nth element of the cell array
6702 */
6703 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6704   assert( N>=0 && N<p->nCell );
6705   assert( p->szCell[N]==0 );
6706   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6707   return p->szCell[N];
6708 }
6709 static u16 cachedCellSize(CellArray *p, int N){
6710   assert( N>=0 && N<p->nCell );
6711   if( p->szCell[N] ) return p->szCell[N];
6712   return computeCellSize(p, N);
6713 }
6714 
6715 /*
6716 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6717 ** szCell[] array contains the size in bytes of each cell. This function
6718 ** replaces the current contents of page pPg with the contents of the cell
6719 ** array.
6720 **
6721 ** Some of the cells in apCell[] may currently be stored in pPg. This
6722 ** function works around problems caused by this by making a copy of any
6723 ** such cells before overwriting the page data.
6724 **
6725 ** The MemPage.nFree field is invalidated by this function. It is the
6726 ** responsibility of the caller to set it correctly.
6727 */
6728 static int rebuildPage(
6729   MemPage *pPg,                   /* Edit this page */
6730   int nCell,                      /* Final number of cells on page */
6731   u8 **apCell,                    /* Array of cells */
6732   u16 *szCell                     /* Array of cell sizes */
6733 ){
6734   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
6735   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
6736   const int usableSize = pPg->pBt->usableSize;
6737   u8 * const pEnd = &aData[usableSize];
6738   int i;
6739   u8 *pCellptr = pPg->aCellIdx;
6740   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6741   u8 *pData;
6742 
6743   i = get2byte(&aData[hdr+5]);
6744   memcpy(&pTmp[i], &aData[i], usableSize - i);
6745 
6746   pData = pEnd;
6747   for(i=0; i<nCell; i++){
6748     u8 *pCell = apCell[i];
6749     if( SQLITE_WITHIN(pCell,aData,pEnd) ){
6750       pCell = &pTmp[pCell - aData];
6751     }
6752     pData -= szCell[i];
6753     put2byte(pCellptr, (pData - aData));
6754     pCellptr += 2;
6755     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6756     memcpy(pData, pCell, szCell[i]);
6757     assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
6758     testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
6759   }
6760 
6761   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
6762   pPg->nCell = nCell;
6763   pPg->nOverflow = 0;
6764 
6765   put2byte(&aData[hdr+1], 0);
6766   put2byte(&aData[hdr+3], pPg->nCell);
6767   put2byte(&aData[hdr+5], pData - aData);
6768   aData[hdr+7] = 0x00;
6769   return SQLITE_OK;
6770 }
6771 
6772 /*
6773 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6774 ** contains the size in bytes of each such cell. This function attempts to
6775 ** add the cells stored in the array to page pPg. If it cannot (because
6776 ** the page needs to be defragmented before the cells will fit), non-zero
6777 ** is returned. Otherwise, if the cells are added successfully, zero is
6778 ** returned.
6779 **
6780 ** Argument pCellptr points to the first entry in the cell-pointer array
6781 ** (part of page pPg) to populate. After cell apCell[0] is written to the
6782 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
6783 ** cell in the array. It is the responsibility of the caller to ensure
6784 ** that it is safe to overwrite this part of the cell-pointer array.
6785 **
6786 ** When this function is called, *ppData points to the start of the
6787 ** content area on page pPg. If the size of the content area is extended,
6788 ** *ppData is updated to point to the new start of the content area
6789 ** before returning.
6790 **
6791 ** Finally, argument pBegin points to the byte immediately following the
6792 ** end of the space required by this page for the cell-pointer area (for
6793 ** all cells - not just those inserted by the current call). If the content
6794 ** area must be extended to before this point in order to accomodate all
6795 ** cells in apCell[], then the cells do not fit and non-zero is returned.
6796 */
6797 static int pageInsertArray(
6798   MemPage *pPg,                   /* Page to add cells to */
6799   u8 *pBegin,                     /* End of cell-pointer array */
6800   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
6801   u8 *pCellptr,                   /* Pointer to cell-pointer area */
6802   int iFirst,                     /* Index of first cell to add */
6803   int nCell,                      /* Number of cells to add to pPg */
6804   CellArray *pCArray              /* Array of cells */
6805 ){
6806   int i;
6807   u8 *aData = pPg->aData;
6808   u8 *pData = *ppData;
6809   int iEnd = iFirst + nCell;
6810   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
6811   for(i=iFirst; i<iEnd; i++){
6812     int sz, rc;
6813     u8 *pSlot;
6814     sz = cachedCellSize(pCArray, i);
6815     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
6816       if( (pData - pBegin)<sz ) return 1;
6817       pData -= sz;
6818       pSlot = pData;
6819     }
6820     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6821     ** database.  But they might for a corrupt database.  Hence use memmove()
6822     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6823     assert( (pSlot+sz)<=pCArray->apCell[i]
6824          || pSlot>=(pCArray->apCell[i]+sz)
6825          || CORRUPT_DB );
6826     memmove(pSlot, pCArray->apCell[i], sz);
6827     put2byte(pCellptr, (pSlot - aData));
6828     pCellptr += 2;
6829   }
6830   *ppData = pData;
6831   return 0;
6832 }
6833 
6834 /*
6835 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6836 ** contains the size in bytes of each such cell. This function adds the
6837 ** space associated with each cell in the array that is currently stored
6838 ** within the body of pPg to the pPg free-list. The cell-pointers and other
6839 ** fields of the page are not updated.
6840 **
6841 ** This function returns the total number of cells added to the free-list.
6842 */
6843 static int pageFreeArray(
6844   MemPage *pPg,                   /* Page to edit */
6845   int iFirst,                     /* First cell to delete */
6846   int nCell,                      /* Cells to delete */
6847   CellArray *pCArray              /* Array of cells */
6848 ){
6849   u8 * const aData = pPg->aData;
6850   u8 * const pEnd = &aData[pPg->pBt->usableSize];
6851   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
6852   int nRet = 0;
6853   int i;
6854   int iEnd = iFirst + nCell;
6855   u8 *pFree = 0;
6856   int szFree = 0;
6857 
6858   for(i=iFirst; i<iEnd; i++){
6859     u8 *pCell = pCArray->apCell[i];
6860     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
6861       int sz;
6862       /* No need to use cachedCellSize() here.  The sizes of all cells that
6863       ** are to be freed have already been computing while deciding which
6864       ** cells need freeing */
6865       sz = pCArray->szCell[i];  assert( sz>0 );
6866       if( pFree!=(pCell + sz) ){
6867         if( pFree ){
6868           assert( pFree>aData && (pFree - aData)<65536 );
6869           freeSpace(pPg, (u16)(pFree - aData), szFree);
6870         }
6871         pFree = pCell;
6872         szFree = sz;
6873         if( pFree+sz>pEnd ) return 0;
6874       }else{
6875         pFree = pCell;
6876         szFree += sz;
6877       }
6878       nRet++;
6879     }
6880   }
6881   if( pFree ){
6882     assert( pFree>aData && (pFree - aData)<65536 );
6883     freeSpace(pPg, (u16)(pFree - aData), szFree);
6884   }
6885   return nRet;
6886 }
6887 
6888 /*
6889 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6890 ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
6891 ** with apCell[iOld].  After balancing, this page should hold nNew cells
6892 ** starting at apCell[iNew].
6893 **
6894 ** This routine makes the necessary adjustments to pPg so that it contains
6895 ** the correct cells after being balanced.
6896 **
6897 ** The pPg->nFree field is invalid when this function returns. It is the
6898 ** responsibility of the caller to set it correctly.
6899 */
6900 static int editPage(
6901   MemPage *pPg,                   /* Edit this page */
6902   int iOld,                       /* Index of first cell currently on page */
6903   int iNew,                       /* Index of new first cell on page */
6904   int nNew,                       /* Final number of cells on page */
6905   CellArray *pCArray              /* Array of cells and sizes */
6906 ){
6907   u8 * const aData = pPg->aData;
6908   const int hdr = pPg->hdrOffset;
6909   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6910   int nCell = pPg->nCell;       /* Cells stored on pPg */
6911   u8 *pData;
6912   u8 *pCellptr;
6913   int i;
6914   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6915   int iNewEnd = iNew + nNew;
6916 
6917 #ifdef SQLITE_DEBUG
6918   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6919   memcpy(pTmp, aData, pPg->pBt->usableSize);
6920 #endif
6921 
6922   /* Remove cells from the start and end of the page */
6923   if( iOld<iNew ){
6924     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
6925     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6926     nCell -= nShift;
6927   }
6928   if( iNewEnd < iOldEnd ){
6929     nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
6930   }
6931 
6932   pData = &aData[get2byteNotZero(&aData[hdr+5])];
6933   if( pData<pBegin ) goto editpage_fail;
6934 
6935   /* Add cells to the start of the page */
6936   if( iNew<iOld ){
6937     int nAdd = MIN(nNew,iOld-iNew);
6938     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
6939     pCellptr = pPg->aCellIdx;
6940     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6941     if( pageInsertArray(
6942           pPg, pBegin, &pData, pCellptr,
6943           iNew, nAdd, pCArray
6944     ) ) goto editpage_fail;
6945     nCell += nAdd;
6946   }
6947 
6948   /* Add any overflow cells */
6949   for(i=0; i<pPg->nOverflow; i++){
6950     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6951     if( iCell>=0 && iCell<nNew ){
6952       pCellptr = &pPg->aCellIdx[iCell * 2];
6953       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6954       nCell++;
6955       if( pageInsertArray(
6956             pPg, pBegin, &pData, pCellptr,
6957             iCell+iNew, 1, pCArray
6958       ) ) goto editpage_fail;
6959     }
6960   }
6961 
6962   /* Append cells to the end of the page */
6963   pCellptr = &pPg->aCellIdx[nCell*2];
6964   if( pageInsertArray(
6965         pPg, pBegin, &pData, pCellptr,
6966         iNew+nCell, nNew-nCell, pCArray
6967   ) ) goto editpage_fail;
6968 
6969   pPg->nCell = nNew;
6970   pPg->nOverflow = 0;
6971 
6972   put2byte(&aData[hdr+3], pPg->nCell);
6973   put2byte(&aData[hdr+5], pData - aData);
6974 
6975 #ifdef SQLITE_DEBUG
6976   for(i=0; i<nNew && !CORRUPT_DB; i++){
6977     u8 *pCell = pCArray->apCell[i+iNew];
6978     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
6979     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
6980       pCell = &pTmp[pCell - aData];
6981     }
6982     assert( 0==memcmp(pCell, &aData[iOff],
6983             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
6984   }
6985 #endif
6986 
6987   return SQLITE_OK;
6988  editpage_fail:
6989   /* Unable to edit this page. Rebuild it from scratch instead. */
6990   populateCellCache(pCArray, iNew, nNew);
6991   return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
6992 }
6993 
6994 /*
6995 ** The following parameters determine how many adjacent pages get involved
6996 ** in a balancing operation.  NN is the number of neighbors on either side
6997 ** of the page that participate in the balancing operation.  NB is the
6998 ** total number of pages that participate, including the target page and
6999 ** NN neighbors on either side.
7000 **
7001 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
7002 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7003 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7004 ** The value of NN appears to give the best results overall.
7005 */
7006 #define NN 1             /* Number of neighbors on either side of pPage */
7007 #define NB (NN*2+1)      /* Total pages involved in the balance */
7008 
7009 
7010 #ifndef SQLITE_OMIT_QUICKBALANCE
7011 /*
7012 ** This version of balance() handles the common special case where
7013 ** a new entry is being inserted on the extreme right-end of the
7014 ** tree, in other words, when the new entry will become the largest
7015 ** entry in the tree.
7016 **
7017 ** Instead of trying to balance the 3 right-most leaf pages, just add
7018 ** a new page to the right-hand side and put the one new entry in
7019 ** that page.  This leaves the right side of the tree somewhat
7020 ** unbalanced.  But odds are that we will be inserting new entries
7021 ** at the end soon afterwards so the nearly empty page will quickly
7022 ** fill up.  On average.
7023 **
7024 ** pPage is the leaf page which is the right-most page in the tree.
7025 ** pParent is its parent.  pPage must have a single overflow entry
7026 ** which is also the right-most entry on the page.
7027 **
7028 ** The pSpace buffer is used to store a temporary copy of the divider
7029 ** cell that will be inserted into pParent. Such a cell consists of a 4
7030 ** byte page number followed by a variable length integer. In other
7031 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7032 ** least 13 bytes in size.
7033 */
7034 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7035   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7036   MemPage *pNew;                       /* Newly allocated page */
7037   int rc;                              /* Return Code */
7038   Pgno pgnoNew;                        /* Page number of pNew */
7039 
7040   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7041   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7042   assert( pPage->nOverflow==1 );
7043 
7044   /* This error condition is now caught prior to reaching this function */
7045   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
7046 
7047   /* Allocate a new page. This page will become the right-sibling of
7048   ** pPage. Make the parent page writable, so that the new divider cell
7049   ** may be inserted. If both these operations are successful, proceed.
7050   */
7051   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7052 
7053   if( rc==SQLITE_OK ){
7054 
7055     u8 *pOut = &pSpace[4];
7056     u8 *pCell = pPage->apOvfl[0];
7057     u16 szCell = pPage->xCellSize(pPage, pCell);
7058     u8 *pStop;
7059 
7060     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7061     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7062     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7063     rc = rebuildPage(pNew, 1, &pCell, &szCell);
7064     if( NEVER(rc) ) return rc;
7065     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7066 
7067     /* If this is an auto-vacuum database, update the pointer map
7068     ** with entries for the new page, and any pointer from the
7069     ** cell on the page to an overflow page. If either of these
7070     ** operations fails, the return code is set, but the contents
7071     ** of the parent page are still manipulated by thh code below.
7072     ** That is Ok, at this point the parent page is guaranteed to
7073     ** be marked as dirty. Returning an error code will cause a
7074     ** rollback, undoing any changes made to the parent page.
7075     */
7076     if( ISAUTOVACUUM ){
7077       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7078       if( szCell>pNew->minLocal ){
7079         ptrmapPutOvflPtr(pNew, pCell, &rc);
7080       }
7081     }
7082 
7083     /* Create a divider cell to insert into pParent. The divider cell
7084     ** consists of a 4-byte page number (the page number of pPage) and
7085     ** a variable length key value (which must be the same value as the
7086     ** largest key on pPage).
7087     **
7088     ** To find the largest key value on pPage, first find the right-most
7089     ** cell on pPage. The first two fields of this cell are the
7090     ** record-length (a variable length integer at most 32-bits in size)
7091     ** and the key value (a variable length integer, may have any value).
7092     ** The first of the while(...) loops below skips over the record-length
7093     ** field. The second while(...) loop copies the key value from the
7094     ** cell on pPage into the pSpace buffer.
7095     */
7096     pCell = findCell(pPage, pPage->nCell-1);
7097     pStop = &pCell[9];
7098     while( (*(pCell++)&0x80) && pCell<pStop );
7099     pStop = &pCell[9];
7100     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7101 
7102     /* Insert the new divider cell into pParent. */
7103     if( rc==SQLITE_OK ){
7104       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7105                    0, pPage->pgno, &rc);
7106     }
7107 
7108     /* Set the right-child pointer of pParent to point to the new page. */
7109     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7110 
7111     /* Release the reference to the new page. */
7112     releasePage(pNew);
7113   }
7114 
7115   return rc;
7116 }
7117 #endif /* SQLITE_OMIT_QUICKBALANCE */
7118 
7119 #if 0
7120 /*
7121 ** This function does not contribute anything to the operation of SQLite.
7122 ** it is sometimes activated temporarily while debugging code responsible
7123 ** for setting pointer-map entries.
7124 */
7125 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7126   int i, j;
7127   for(i=0; i<nPage; i++){
7128     Pgno n;
7129     u8 e;
7130     MemPage *pPage = apPage[i];
7131     BtShared *pBt = pPage->pBt;
7132     assert( pPage->isInit );
7133 
7134     for(j=0; j<pPage->nCell; j++){
7135       CellInfo info;
7136       u8 *z;
7137 
7138       z = findCell(pPage, j);
7139       pPage->xParseCell(pPage, z, &info);
7140       if( info.nLocal<info.nPayload ){
7141         Pgno ovfl = get4byte(&z[info.nSize-4]);
7142         ptrmapGet(pBt, ovfl, &e, &n);
7143         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7144       }
7145       if( !pPage->leaf ){
7146         Pgno child = get4byte(z);
7147         ptrmapGet(pBt, child, &e, &n);
7148         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7149       }
7150     }
7151     if( !pPage->leaf ){
7152       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7153       ptrmapGet(pBt, child, &e, &n);
7154       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7155     }
7156   }
7157   return 1;
7158 }
7159 #endif
7160 
7161 /*
7162 ** This function is used to copy the contents of the b-tree node stored
7163 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7164 ** the pointer-map entries for each child page are updated so that the
7165 ** parent page stored in the pointer map is page pTo. If pFrom contained
7166 ** any cells with overflow page pointers, then the corresponding pointer
7167 ** map entries are also updated so that the parent page is page pTo.
7168 **
7169 ** If pFrom is currently carrying any overflow cells (entries in the
7170 ** MemPage.apOvfl[] array), they are not copied to pTo.
7171 **
7172 ** Before returning, page pTo is reinitialized using btreeInitPage().
7173 **
7174 ** The performance of this function is not critical. It is only used by
7175 ** the balance_shallower() and balance_deeper() procedures, neither of
7176 ** which are called often under normal circumstances.
7177 */
7178 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7179   if( (*pRC)==SQLITE_OK ){
7180     BtShared * const pBt = pFrom->pBt;
7181     u8 * const aFrom = pFrom->aData;
7182     u8 * const aTo = pTo->aData;
7183     int const iFromHdr = pFrom->hdrOffset;
7184     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7185     int rc;
7186     int iData;
7187 
7188 
7189     assert( pFrom->isInit );
7190     assert( pFrom->nFree>=iToHdr );
7191     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7192 
7193     /* Copy the b-tree node content from page pFrom to page pTo. */
7194     iData = get2byte(&aFrom[iFromHdr+5]);
7195     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7196     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7197 
7198     /* Reinitialize page pTo so that the contents of the MemPage structure
7199     ** match the new data. The initialization of pTo can actually fail under
7200     ** fairly obscure circumstances, even though it is a copy of initialized
7201     ** page pFrom.
7202     */
7203     pTo->isInit = 0;
7204     rc = btreeInitPage(pTo);
7205     if( rc!=SQLITE_OK ){
7206       *pRC = rc;
7207       return;
7208     }
7209 
7210     /* If this is an auto-vacuum database, update the pointer-map entries
7211     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7212     */
7213     if( ISAUTOVACUUM ){
7214       *pRC = setChildPtrmaps(pTo);
7215     }
7216   }
7217 }
7218 
7219 /*
7220 ** This routine redistributes cells on the iParentIdx'th child of pParent
7221 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7222 ** same amount of free space. Usually a single sibling on either side of the
7223 ** page are used in the balancing, though both siblings might come from one
7224 ** side if the page is the first or last child of its parent. If the page
7225 ** has fewer than 2 siblings (something which can only happen if the page
7226 ** is a root page or a child of a root page) then all available siblings
7227 ** participate in the balancing.
7228 **
7229 ** The number of siblings of the page might be increased or decreased by
7230 ** one or two in an effort to keep pages nearly full but not over full.
7231 **
7232 ** Note that when this routine is called, some of the cells on the page
7233 ** might not actually be stored in MemPage.aData[]. This can happen
7234 ** if the page is overfull. This routine ensures that all cells allocated
7235 ** to the page and its siblings fit into MemPage.aData[] before returning.
7236 **
7237 ** In the course of balancing the page and its siblings, cells may be
7238 ** inserted into or removed from the parent page (pParent). Doing so
7239 ** may cause the parent page to become overfull or underfull. If this
7240 ** happens, it is the responsibility of the caller to invoke the correct
7241 ** balancing routine to fix this problem (see the balance() routine).
7242 **
7243 ** If this routine fails for any reason, it might leave the database
7244 ** in a corrupted state. So if this routine fails, the database should
7245 ** be rolled back.
7246 **
7247 ** The third argument to this function, aOvflSpace, is a pointer to a
7248 ** buffer big enough to hold one page. If while inserting cells into the parent
7249 ** page (pParent) the parent page becomes overfull, this buffer is
7250 ** used to store the parent's overflow cells. Because this function inserts
7251 ** a maximum of four divider cells into the parent page, and the maximum
7252 ** size of a cell stored within an internal node is always less than 1/4
7253 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7254 ** enough for all overflow cells.
7255 **
7256 ** If aOvflSpace is set to a null pointer, this function returns
7257 ** SQLITE_NOMEM.
7258 */
7259 static int balance_nonroot(
7260   MemPage *pParent,               /* Parent page of siblings being balanced */
7261   int iParentIdx,                 /* Index of "the page" in pParent */
7262   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7263   int isRoot,                     /* True if pParent is a root-page */
7264   int bBulk                       /* True if this call is part of a bulk load */
7265 ){
7266   BtShared *pBt;               /* The whole database */
7267   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7268   int nNew = 0;                /* Number of pages in apNew[] */
7269   int nOld;                    /* Number of pages in apOld[] */
7270   int i, j, k;                 /* Loop counters */
7271   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7272   int rc = SQLITE_OK;          /* The return code */
7273   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7274   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7275   int usableSpace;             /* Bytes in pPage beyond the header */
7276   int pageFlags;               /* Value of pPage->aData[0] */
7277   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7278   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7279   int szScratch;               /* Size of scratch memory requested */
7280   MemPage *apOld[NB];          /* pPage and up to two siblings */
7281   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7282   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7283   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7284   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7285   int cntOld[NB+2];            /* Old index in b.apCell[] */
7286   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7287   u8 *aSpace1;                 /* Space for copies of dividers cells */
7288   Pgno pgno;                   /* Temp var to store a page number in */
7289   u8 abDone[NB+2];             /* True after i'th new page is populated */
7290   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7291   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7292   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7293   CellArray b;                  /* Parsed information on cells being balanced */
7294 
7295   memset(abDone, 0, sizeof(abDone));
7296   b.nCell = 0;
7297   b.apCell = 0;
7298   pBt = pParent->pBt;
7299   assert( sqlite3_mutex_held(pBt->mutex) );
7300   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7301 
7302 #if 0
7303   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
7304 #endif
7305 
7306   /* At this point pParent may have at most one overflow cell. And if
7307   ** this overflow cell is present, it must be the cell with
7308   ** index iParentIdx. This scenario comes about when this function
7309   ** is called (indirectly) from sqlite3BtreeDelete().
7310   */
7311   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7312   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7313 
7314   if( !aOvflSpace ){
7315     return SQLITE_NOMEM_BKPT;
7316   }
7317 
7318   /* Find the sibling pages to balance. Also locate the cells in pParent
7319   ** that divide the siblings. An attempt is made to find NN siblings on
7320   ** either side of pPage. More siblings are taken from one side, however,
7321   ** if there are fewer than NN siblings on the other side. If pParent
7322   ** has NB or fewer children then all children of pParent are taken.
7323   **
7324   ** This loop also drops the divider cells from the parent page. This
7325   ** way, the remainder of the function does not have to deal with any
7326   ** overflow cells in the parent page, since if any existed they will
7327   ** have already been removed.
7328   */
7329   i = pParent->nOverflow + pParent->nCell;
7330   if( i<2 ){
7331     nxDiv = 0;
7332   }else{
7333     assert( bBulk==0 || bBulk==1 );
7334     if( iParentIdx==0 ){
7335       nxDiv = 0;
7336     }else if( iParentIdx==i ){
7337       nxDiv = i-2+bBulk;
7338     }else{
7339       nxDiv = iParentIdx-1;
7340     }
7341     i = 2-bBulk;
7342   }
7343   nOld = i+1;
7344   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7345     pRight = &pParent->aData[pParent->hdrOffset+8];
7346   }else{
7347     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7348   }
7349   pgno = get4byte(pRight);
7350   while( 1 ){
7351     rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7352     if( rc ){
7353       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7354       goto balance_cleanup;
7355     }
7356     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
7357     if( (i--)==0 ) break;
7358 
7359     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7360       apDiv[i] = pParent->apOvfl[0];
7361       pgno = get4byte(apDiv[i]);
7362       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7363       pParent->nOverflow = 0;
7364     }else{
7365       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7366       pgno = get4byte(apDiv[i]);
7367       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7368 
7369       /* Drop the cell from the parent page. apDiv[i] still points to
7370       ** the cell within the parent, even though it has been dropped.
7371       ** This is safe because dropping a cell only overwrites the first
7372       ** four bytes of it, and this function does not need the first
7373       ** four bytes of the divider cell. So the pointer is safe to use
7374       ** later on.
7375       **
7376       ** But not if we are in secure-delete mode. In secure-delete mode,
7377       ** the dropCell() routine will overwrite the entire cell with zeroes.
7378       ** In this case, temporarily copy the cell into the aOvflSpace[]
7379       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7380       ** is allocated.  */
7381       if( pBt->btsFlags & BTS_FAST_SECURE ){
7382         int iOff;
7383 
7384         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7385         if( (iOff+szNew[i])>(int)pBt->usableSize ){
7386           rc = SQLITE_CORRUPT_BKPT;
7387           memset(apOld, 0, (i+1)*sizeof(MemPage*));
7388           goto balance_cleanup;
7389         }else{
7390           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7391           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7392         }
7393       }
7394       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7395     }
7396   }
7397 
7398   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7399   ** alignment */
7400   nMaxCells = (nMaxCells + 3)&~3;
7401 
7402   /*
7403   ** Allocate space for memory structures
7404   */
7405   szScratch =
7406        nMaxCells*sizeof(u8*)                       /* b.apCell */
7407      + nMaxCells*sizeof(u16)                       /* b.szCell */
7408      + pBt->pageSize;                              /* aSpace1 */
7409 
7410   assert( szScratch<=6*(int)pBt->pageSize );
7411   b.apCell = sqlite3StackAllocRaw(0, szScratch );
7412   if( b.apCell==0 ){
7413     rc = SQLITE_NOMEM_BKPT;
7414     goto balance_cleanup;
7415   }
7416   b.szCell = (u16*)&b.apCell[nMaxCells];
7417   aSpace1 = (u8*)&b.szCell[nMaxCells];
7418   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7419 
7420   /*
7421   ** Load pointers to all cells on sibling pages and the divider cells
7422   ** into the local b.apCell[] array.  Make copies of the divider cells
7423   ** into space obtained from aSpace1[]. The divider cells have already
7424   ** been removed from pParent.
7425   **
7426   ** If the siblings are on leaf pages, then the child pointers of the
7427   ** divider cells are stripped from the cells before they are copied
7428   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7429   ** child pointers.  If siblings are not leaves, then all cell in
7430   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7431   ** are alike.
7432   **
7433   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7434   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7435   */
7436   b.pRef = apOld[0];
7437   leafCorrection = b.pRef->leaf*4;
7438   leafData = b.pRef->intKeyLeaf;
7439   for(i=0; i<nOld; i++){
7440     MemPage *pOld = apOld[i];
7441     int limit = pOld->nCell;
7442     u8 *aData = pOld->aData;
7443     u16 maskPage = pOld->maskPage;
7444     u8 *piCell = aData + pOld->cellOffset;
7445     u8 *piEnd;
7446 
7447     /* Verify that all sibling pages are of the same "type" (table-leaf,
7448     ** table-interior, index-leaf, or index-interior).
7449     */
7450     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7451       rc = SQLITE_CORRUPT_BKPT;
7452       goto balance_cleanup;
7453     }
7454 
7455     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7456     ** contains overflow cells, include them in the b.apCell[] array
7457     ** in the correct spot.
7458     **
7459     ** Note that when there are multiple overflow cells, it is always the
7460     ** case that they are sequential and adjacent.  This invariant arises
7461     ** because multiple overflows can only occurs when inserting divider
7462     ** cells into a parent on a prior balance, and divider cells are always
7463     ** adjacent and are inserted in order.  There is an assert() tagged
7464     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7465     ** invariant.
7466     **
7467     ** This must be done in advance.  Once the balance starts, the cell
7468     ** offset section of the btree page will be overwritten and we will no
7469     ** long be able to find the cells if a pointer to each cell is not saved
7470     ** first.
7471     */
7472     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7473     if( pOld->nOverflow>0 ){
7474       limit = pOld->aiOvfl[0];
7475       for(j=0; j<limit; j++){
7476         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7477         piCell += 2;
7478         b.nCell++;
7479       }
7480       for(k=0; k<pOld->nOverflow; k++){
7481         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7482         b.apCell[b.nCell] = pOld->apOvfl[k];
7483         b.nCell++;
7484       }
7485     }
7486     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7487     while( piCell<piEnd ){
7488       assert( b.nCell<nMaxCells );
7489       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7490       piCell += 2;
7491       b.nCell++;
7492     }
7493 
7494     cntOld[i] = b.nCell;
7495     if( i<nOld-1 && !leafData){
7496       u16 sz = (u16)szNew[i];
7497       u8 *pTemp;
7498       assert( b.nCell<nMaxCells );
7499       b.szCell[b.nCell] = sz;
7500       pTemp = &aSpace1[iSpace1];
7501       iSpace1 += sz;
7502       assert( sz<=pBt->maxLocal+23 );
7503       assert( iSpace1 <= (int)pBt->pageSize );
7504       memcpy(pTemp, apDiv[i], sz);
7505       b.apCell[b.nCell] = pTemp+leafCorrection;
7506       assert( leafCorrection==0 || leafCorrection==4 );
7507       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7508       if( !pOld->leaf ){
7509         assert( leafCorrection==0 );
7510         assert( pOld->hdrOffset==0 );
7511         /* The right pointer of the child page pOld becomes the left
7512         ** pointer of the divider cell */
7513         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7514       }else{
7515         assert( leafCorrection==4 );
7516         while( b.szCell[b.nCell]<4 ){
7517           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7518           ** does exist, pad it with 0x00 bytes. */
7519           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7520           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7521           aSpace1[iSpace1++] = 0x00;
7522           b.szCell[b.nCell]++;
7523         }
7524       }
7525       b.nCell++;
7526     }
7527   }
7528 
7529   /*
7530   ** Figure out the number of pages needed to hold all b.nCell cells.
7531   ** Store this number in "k".  Also compute szNew[] which is the total
7532   ** size of all cells on the i-th page and cntNew[] which is the index
7533   ** in b.apCell[] of the cell that divides page i from page i+1.
7534   ** cntNew[k] should equal b.nCell.
7535   **
7536   ** Values computed by this block:
7537   **
7538   **           k: The total number of sibling pages
7539   **    szNew[i]: Spaced used on the i-th sibling page.
7540   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7541   **              the right of the i-th sibling page.
7542   ** usableSpace: Number of bytes of space available on each sibling.
7543   **
7544   */
7545   usableSpace = pBt->usableSize - 12 + leafCorrection;
7546   for(i=0; i<nOld; i++){
7547     MemPage *p = apOld[i];
7548     szNew[i] = usableSpace - p->nFree;
7549     for(j=0; j<p->nOverflow; j++){
7550       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7551     }
7552     cntNew[i] = cntOld[i];
7553   }
7554   k = nOld;
7555   for(i=0; i<k; i++){
7556     int sz;
7557     while( szNew[i]>usableSpace ){
7558       if( i+1>=k ){
7559         k = i+2;
7560         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7561         szNew[k-1] = 0;
7562         cntNew[k-1] = b.nCell;
7563       }
7564       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7565       szNew[i] -= sz;
7566       if( !leafData ){
7567         if( cntNew[i]<b.nCell ){
7568           sz = 2 + cachedCellSize(&b, cntNew[i]);
7569         }else{
7570           sz = 0;
7571         }
7572       }
7573       szNew[i+1] += sz;
7574       cntNew[i]--;
7575     }
7576     while( cntNew[i]<b.nCell ){
7577       sz = 2 + cachedCellSize(&b, cntNew[i]);
7578       if( szNew[i]+sz>usableSpace ) break;
7579       szNew[i] += sz;
7580       cntNew[i]++;
7581       if( !leafData ){
7582         if( cntNew[i]<b.nCell ){
7583           sz = 2 + cachedCellSize(&b, cntNew[i]);
7584         }else{
7585           sz = 0;
7586         }
7587       }
7588       szNew[i+1] -= sz;
7589     }
7590     if( cntNew[i]>=b.nCell ){
7591       k = i+1;
7592     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7593       rc = SQLITE_CORRUPT_BKPT;
7594       goto balance_cleanup;
7595     }
7596   }
7597 
7598   /*
7599   ** The packing computed by the previous block is biased toward the siblings
7600   ** on the left side (siblings with smaller keys). The left siblings are
7601   ** always nearly full, while the right-most sibling might be nearly empty.
7602   ** The next block of code attempts to adjust the packing of siblings to
7603   ** get a better balance.
7604   **
7605   ** This adjustment is more than an optimization.  The packing above might
7606   ** be so out of balance as to be illegal.  For example, the right-most
7607   ** sibling might be completely empty.  This adjustment is not optional.
7608   */
7609   for(i=k-1; i>0; i--){
7610     int szRight = szNew[i];  /* Size of sibling on the right */
7611     int szLeft = szNew[i-1]; /* Size of sibling on the left */
7612     int r;              /* Index of right-most cell in left sibling */
7613     int d;              /* Index of first cell to the left of right sibling */
7614 
7615     r = cntNew[i-1] - 1;
7616     d = r + 1 - leafData;
7617     (void)cachedCellSize(&b, d);
7618     do{
7619       assert( d<nMaxCells );
7620       assert( r<nMaxCells );
7621       (void)cachedCellSize(&b, r);
7622       if( szRight!=0
7623        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7624         break;
7625       }
7626       szRight += b.szCell[d] + 2;
7627       szLeft -= b.szCell[r] + 2;
7628       cntNew[i-1] = r;
7629       r--;
7630       d--;
7631     }while( r>=0 );
7632     szNew[i] = szRight;
7633     szNew[i-1] = szLeft;
7634     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7635       rc = SQLITE_CORRUPT_BKPT;
7636       goto balance_cleanup;
7637     }
7638   }
7639 
7640   /* Sanity check:  For a non-corrupt database file one of the follwing
7641   ** must be true:
7642   **    (1) We found one or more cells (cntNew[0])>0), or
7643   **    (2) pPage is a virtual root page.  A virtual root page is when
7644   **        the real root page is page 1 and we are the only child of
7645   **        that page.
7646   */
7647   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7648   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7649     apOld[0]->pgno, apOld[0]->nCell,
7650     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7651     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7652   ));
7653 
7654   /*
7655   ** Allocate k new pages.  Reuse old pages where possible.
7656   */
7657   pageFlags = apOld[0]->aData[0];
7658   for(i=0; i<k; i++){
7659     MemPage *pNew;
7660     if( i<nOld ){
7661       pNew = apNew[i] = apOld[i];
7662       apOld[i] = 0;
7663       rc = sqlite3PagerWrite(pNew->pDbPage);
7664       nNew++;
7665       if( rc ) goto balance_cleanup;
7666     }else{
7667       assert( i>0 );
7668       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7669       if( rc ) goto balance_cleanup;
7670       zeroPage(pNew, pageFlags);
7671       apNew[i] = pNew;
7672       nNew++;
7673       cntOld[i] = b.nCell;
7674 
7675       /* Set the pointer-map entry for the new sibling page. */
7676       if( ISAUTOVACUUM ){
7677         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7678         if( rc!=SQLITE_OK ){
7679           goto balance_cleanup;
7680         }
7681       }
7682     }
7683   }
7684 
7685   /*
7686   ** Reassign page numbers so that the new pages are in ascending order.
7687   ** This helps to keep entries in the disk file in order so that a scan
7688   ** of the table is closer to a linear scan through the file. That in turn
7689   ** helps the operating system to deliver pages from the disk more rapidly.
7690   **
7691   ** An O(n^2) insertion sort algorithm is used, but since n is never more
7692   ** than (NB+2) (a small constant), that should not be a problem.
7693   **
7694   ** When NB==3, this one optimization makes the database about 25% faster
7695   ** for large insertions and deletions.
7696   */
7697   for(i=0; i<nNew; i++){
7698     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
7699     aPgFlags[i] = apNew[i]->pDbPage->flags;
7700     for(j=0; j<i; j++){
7701       if( aPgno[j]==aPgno[i] ){
7702         /* This branch is taken if the set of sibling pages somehow contains
7703         ** duplicate entries. This can happen if the database is corrupt.
7704         ** It would be simpler to detect this as part of the loop below, but
7705         ** we do the detection here in order to avoid populating the pager
7706         ** cache with two separate objects associated with the same
7707         ** page number.  */
7708         assert( CORRUPT_DB );
7709         rc = SQLITE_CORRUPT_BKPT;
7710         goto balance_cleanup;
7711       }
7712     }
7713   }
7714   for(i=0; i<nNew; i++){
7715     int iBest = 0;                /* aPgno[] index of page number to use */
7716     for(j=1; j<nNew; j++){
7717       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
7718     }
7719     pgno = aPgOrder[iBest];
7720     aPgOrder[iBest] = 0xffffffff;
7721     if( iBest!=i ){
7722       if( iBest>i ){
7723         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7724       }
7725       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7726       apNew[i]->pgno = pgno;
7727     }
7728   }
7729 
7730   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7731          "%d(%d nc=%d) %d(%d nc=%d)\n",
7732     apNew[0]->pgno, szNew[0], cntNew[0],
7733     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
7734     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
7735     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
7736     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
7737     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
7738     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7739     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7740     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7741   ));
7742 
7743   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7744   put4byte(pRight, apNew[nNew-1]->pgno);
7745 
7746   /* If the sibling pages are not leaves, ensure that the right-child pointer
7747   ** of the right-most new sibling page is set to the value that was
7748   ** originally in the same field of the right-most old sibling page. */
7749   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7750     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7751     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7752   }
7753 
7754   /* Make any required updates to pointer map entries associated with
7755   ** cells stored on sibling pages following the balance operation. Pointer
7756   ** map entries associated with divider cells are set by the insertCell()
7757   ** routine. The associated pointer map entries are:
7758   **
7759   **   a) if the cell contains a reference to an overflow chain, the
7760   **      entry associated with the first page in the overflow chain, and
7761   **
7762   **   b) if the sibling pages are not leaves, the child page associated
7763   **      with the cell.
7764   **
7765   ** If the sibling pages are not leaves, then the pointer map entry
7766   ** associated with the right-child of each sibling may also need to be
7767   ** updated. This happens below, after the sibling pages have been
7768   ** populated, not here.
7769   */
7770   if( ISAUTOVACUUM ){
7771     MemPage *pNew = apNew[0];
7772     u8 *aOld = pNew->aData;
7773     int cntOldNext = pNew->nCell + pNew->nOverflow;
7774     int usableSize = pBt->usableSize;
7775     int iNew = 0;
7776     int iOld = 0;
7777 
7778     for(i=0; i<b.nCell; i++){
7779       u8 *pCell = b.apCell[i];
7780       if( i==cntOldNext ){
7781         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7782         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7783         aOld = pOld->aData;
7784       }
7785       if( i==cntNew[iNew] ){
7786         pNew = apNew[++iNew];
7787         if( !leafData ) continue;
7788       }
7789 
7790       /* Cell pCell is destined for new sibling page pNew. Originally, it
7791       ** was either part of sibling page iOld (possibly an overflow cell),
7792       ** or else the divider cell to the left of sibling page iOld. So,
7793       ** if sibling page iOld had the same page number as pNew, and if
7794       ** pCell really was a part of sibling page iOld (not a divider or
7795       ** overflow cell), we can skip updating the pointer map entries.  */
7796       if( iOld>=nNew
7797        || pNew->pgno!=aPgno[iOld]
7798        || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
7799       ){
7800         if( !leafCorrection ){
7801           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7802         }
7803         if( cachedCellSize(&b,i)>pNew->minLocal ){
7804           ptrmapPutOvflPtr(pNew, pCell, &rc);
7805         }
7806         if( rc ) goto balance_cleanup;
7807       }
7808     }
7809   }
7810 
7811   /* Insert new divider cells into pParent. */
7812   for(i=0; i<nNew-1; i++){
7813     u8 *pCell;
7814     u8 *pTemp;
7815     int sz;
7816     MemPage *pNew = apNew[i];
7817     j = cntNew[i];
7818 
7819     assert( j<nMaxCells );
7820     assert( b.apCell[j]!=0 );
7821     pCell = b.apCell[j];
7822     sz = b.szCell[j] + leafCorrection;
7823     pTemp = &aOvflSpace[iOvflSpace];
7824     if( !pNew->leaf ){
7825       memcpy(&pNew->aData[8], pCell, 4);
7826     }else if( leafData ){
7827       /* If the tree is a leaf-data tree, and the siblings are leaves,
7828       ** then there is no divider cell in b.apCell[]. Instead, the divider
7829       ** cell consists of the integer key for the right-most cell of
7830       ** the sibling-page assembled above only.
7831       */
7832       CellInfo info;
7833       j--;
7834       pNew->xParseCell(pNew, b.apCell[j], &info);
7835       pCell = pTemp;
7836       sz = 4 + putVarint(&pCell[4], info.nKey);
7837       pTemp = 0;
7838     }else{
7839       pCell -= 4;
7840       /* Obscure case for non-leaf-data trees: If the cell at pCell was
7841       ** previously stored on a leaf node, and its reported size was 4
7842       ** bytes, then it may actually be smaller than this
7843       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7844       ** any cell). But it is important to pass the correct size to
7845       ** insertCell(), so reparse the cell now.
7846       **
7847       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7848       ** and WITHOUT ROWID tables with exactly one column which is the
7849       ** primary key.
7850       */
7851       if( b.szCell[j]==4 ){
7852         assert(leafCorrection==4);
7853         sz = pParent->xCellSize(pParent, pCell);
7854       }
7855     }
7856     iOvflSpace += sz;
7857     assert( sz<=pBt->maxLocal+23 );
7858     assert( iOvflSpace <= (int)pBt->pageSize );
7859     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7860     if( rc!=SQLITE_OK ) goto balance_cleanup;
7861     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7862   }
7863 
7864   /* Now update the actual sibling pages. The order in which they are updated
7865   ** is important, as this code needs to avoid disrupting any page from which
7866   ** cells may still to be read. In practice, this means:
7867   **
7868   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7869   **      then it is not safe to update page apNew[iPg] until after
7870   **      the left-hand sibling apNew[iPg-1] has been updated.
7871   **
7872   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7873   **      then it is not safe to update page apNew[iPg] until after
7874   **      the right-hand sibling apNew[iPg+1] has been updated.
7875   **
7876   ** If neither of the above apply, the page is safe to update.
7877   **
7878   ** The iPg value in the following loop starts at nNew-1 goes down
7879   ** to 0, then back up to nNew-1 again, thus making two passes over
7880   ** the pages.  On the initial downward pass, only condition (1) above
7881   ** needs to be tested because (2) will always be true from the previous
7882   ** step.  On the upward pass, both conditions are always true, so the
7883   ** upwards pass simply processes pages that were missed on the downward
7884   ** pass.
7885   */
7886   for(i=1-nNew; i<nNew; i++){
7887     int iPg = i<0 ? -i : i;
7888     assert( iPg>=0 && iPg<nNew );
7889     if( abDone[iPg] ) continue;         /* Skip pages already processed */
7890     if( i>=0                            /* On the upwards pass, or... */
7891      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
7892     ){
7893       int iNew;
7894       int iOld;
7895       int nNewCell;
7896 
7897       /* Verify condition (1):  If cells are moving left, update iPg
7898       ** only after iPg-1 has already been updated. */
7899       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7900 
7901       /* Verify condition (2):  If cells are moving right, update iPg
7902       ** only after iPg+1 has already been updated. */
7903       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7904 
7905       if( iPg==0 ){
7906         iNew = iOld = 0;
7907         nNewCell = cntNew[0];
7908       }else{
7909         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
7910         iNew = cntNew[iPg-1] + !leafData;
7911         nNewCell = cntNew[iPg] - iNew;
7912       }
7913 
7914       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
7915       if( rc ) goto balance_cleanup;
7916       abDone[iPg]++;
7917       apNew[iPg]->nFree = usableSpace-szNew[iPg];
7918       assert( apNew[iPg]->nOverflow==0 );
7919       assert( apNew[iPg]->nCell==nNewCell );
7920     }
7921   }
7922 
7923   /* All pages have been processed exactly once */
7924   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7925 
7926   assert( nOld>0 );
7927   assert( nNew>0 );
7928 
7929   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7930     /* The root page of the b-tree now contains no cells. The only sibling
7931     ** page is the right-child of the parent. Copy the contents of the
7932     ** child page into the parent, decreasing the overall height of the
7933     ** b-tree structure by one. This is described as the "balance-shallower"
7934     ** sub-algorithm in some documentation.
7935     **
7936     ** If this is an auto-vacuum database, the call to copyNodeContent()
7937     ** sets all pointer-map entries corresponding to database image pages
7938     ** for which the pointer is stored within the content being copied.
7939     **
7940     ** It is critical that the child page be defragmented before being
7941     ** copied into the parent, because if the parent is page 1 then it will
7942     ** by smaller than the child due to the database header, and so all the
7943     ** free space needs to be up front.
7944     */
7945     assert( nNew==1 || CORRUPT_DB );
7946     rc = defragmentPage(apNew[0], -1);
7947     testcase( rc!=SQLITE_OK );
7948     assert( apNew[0]->nFree ==
7949         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7950       || rc!=SQLITE_OK
7951     );
7952     copyNodeContent(apNew[0], pParent, &rc);
7953     freePage(apNew[0], &rc);
7954   }else if( ISAUTOVACUUM && !leafCorrection ){
7955     /* Fix the pointer map entries associated with the right-child of each
7956     ** sibling page. All other pointer map entries have already been taken
7957     ** care of.  */
7958     for(i=0; i<nNew; i++){
7959       u32 key = get4byte(&apNew[i]->aData[8]);
7960       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
7961     }
7962   }
7963 
7964   assert( pParent->isInit );
7965   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7966           nOld, nNew, b.nCell));
7967 
7968   /* Free any old pages that were not reused as new pages.
7969   */
7970   for(i=nNew; i<nOld; i++){
7971     freePage(apOld[i], &rc);
7972   }
7973 
7974 #if 0
7975   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
7976     /* The ptrmapCheckPages() contains assert() statements that verify that
7977     ** all pointer map pages are set correctly. This is helpful while
7978     ** debugging. This is usually disabled because a corrupt database may
7979     ** cause an assert() statement to fail.  */
7980     ptrmapCheckPages(apNew, nNew);
7981     ptrmapCheckPages(&pParent, 1);
7982   }
7983 #endif
7984 
7985   /*
7986   ** Cleanup before returning.
7987   */
7988 balance_cleanup:
7989   sqlite3StackFree(0, b.apCell);
7990   for(i=0; i<nOld; i++){
7991     releasePage(apOld[i]);
7992   }
7993   for(i=0; i<nNew; i++){
7994     releasePage(apNew[i]);
7995   }
7996 
7997   return rc;
7998 }
7999 
8000 
8001 /*
8002 ** This function is called when the root page of a b-tree structure is
8003 ** overfull (has one or more overflow pages).
8004 **
8005 ** A new child page is allocated and the contents of the current root
8006 ** page, including overflow cells, are copied into the child. The root
8007 ** page is then overwritten to make it an empty page with the right-child
8008 ** pointer pointing to the new page.
8009 **
8010 ** Before returning, all pointer-map entries corresponding to pages
8011 ** that the new child-page now contains pointers to are updated. The
8012 ** entry corresponding to the new right-child pointer of the root
8013 ** page is also updated.
8014 **
8015 ** If successful, *ppChild is set to contain a reference to the child
8016 ** page and SQLITE_OK is returned. In this case the caller is required
8017 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8018 ** an error code is returned and *ppChild is set to 0.
8019 */
8020 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8021   int rc;                        /* Return value from subprocedures */
8022   MemPage *pChild = 0;           /* Pointer to a new child page */
8023   Pgno pgnoChild = 0;            /* Page number of the new child page */
8024   BtShared *pBt = pRoot->pBt;    /* The BTree */
8025 
8026   assert( pRoot->nOverflow>0 );
8027   assert( sqlite3_mutex_held(pBt->mutex) );
8028 
8029   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8030   ** page that will become the new right-child of pPage. Copy the contents
8031   ** of the node stored on pRoot into the new child page.
8032   */
8033   rc = sqlite3PagerWrite(pRoot->pDbPage);
8034   if( rc==SQLITE_OK ){
8035     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8036     copyNodeContent(pRoot, pChild, &rc);
8037     if( ISAUTOVACUUM ){
8038       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8039     }
8040   }
8041   if( rc ){
8042     *ppChild = 0;
8043     releasePage(pChild);
8044     return rc;
8045   }
8046   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8047   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8048   assert( pChild->nCell==pRoot->nCell );
8049 
8050   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8051 
8052   /* Copy the overflow cells from pRoot to pChild */
8053   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8054          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8055   memcpy(pChild->apOvfl, pRoot->apOvfl,
8056          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8057   pChild->nOverflow = pRoot->nOverflow;
8058 
8059   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8060   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8061   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8062 
8063   *ppChild = pChild;
8064   return SQLITE_OK;
8065 }
8066 
8067 /*
8068 ** The page that pCur currently points to has just been modified in
8069 ** some way. This function figures out if this modification means the
8070 ** tree needs to be balanced, and if so calls the appropriate balancing
8071 ** routine. Balancing routines are:
8072 **
8073 **   balance_quick()
8074 **   balance_deeper()
8075 **   balance_nonroot()
8076 */
8077 static int balance(BtCursor *pCur){
8078   int rc = SQLITE_OK;
8079   const int nMin = pCur->pBt->usableSize * 2 / 3;
8080   u8 aBalanceQuickSpace[13];
8081   u8 *pFree = 0;
8082 
8083   VVA_ONLY( int balance_quick_called = 0 );
8084   VVA_ONLY( int balance_deeper_called = 0 );
8085 
8086   do {
8087     int iPage = pCur->iPage;
8088     MemPage *pPage = pCur->pPage;
8089 
8090     if( iPage==0 ){
8091       if( pPage->nOverflow ){
8092         /* The root page of the b-tree is overfull. In this case call the
8093         ** balance_deeper() function to create a new child for the root-page
8094         ** and copy the current contents of the root-page to it. The
8095         ** next iteration of the do-loop will balance the child page.
8096         */
8097         assert( balance_deeper_called==0 );
8098         VVA_ONLY( balance_deeper_called++ );
8099         rc = balance_deeper(pPage, &pCur->apPage[1]);
8100         if( rc==SQLITE_OK ){
8101           pCur->iPage = 1;
8102           pCur->ix = 0;
8103           pCur->aiIdx[0] = 0;
8104           pCur->apPage[0] = pPage;
8105           pCur->pPage = pCur->apPage[1];
8106           assert( pCur->pPage->nOverflow );
8107         }
8108       }else{
8109         break;
8110       }
8111     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8112       break;
8113     }else{
8114       MemPage * const pParent = pCur->apPage[iPage-1];
8115       int const iIdx = pCur->aiIdx[iPage-1];
8116 
8117       rc = sqlite3PagerWrite(pParent->pDbPage);
8118       if( rc==SQLITE_OK ){
8119 #ifndef SQLITE_OMIT_QUICKBALANCE
8120         if( pPage->intKeyLeaf
8121          && pPage->nOverflow==1
8122          && pPage->aiOvfl[0]==pPage->nCell
8123          && pParent->pgno!=1
8124          && pParent->nCell==iIdx
8125         ){
8126           /* Call balance_quick() to create a new sibling of pPage on which
8127           ** to store the overflow cell. balance_quick() inserts a new cell
8128           ** into pParent, which may cause pParent overflow. If this
8129           ** happens, the next iteration of the do-loop will balance pParent
8130           ** use either balance_nonroot() or balance_deeper(). Until this
8131           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8132           ** buffer.
8133           **
8134           ** The purpose of the following assert() is to check that only a
8135           ** single call to balance_quick() is made for each call to this
8136           ** function. If this were not verified, a subtle bug involving reuse
8137           ** of the aBalanceQuickSpace[] might sneak in.
8138           */
8139           assert( balance_quick_called==0 );
8140           VVA_ONLY( balance_quick_called++ );
8141           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8142         }else
8143 #endif
8144         {
8145           /* In this case, call balance_nonroot() to redistribute cells
8146           ** between pPage and up to 2 of its sibling pages. This involves
8147           ** modifying the contents of pParent, which may cause pParent to
8148           ** become overfull or underfull. The next iteration of the do-loop
8149           ** will balance the parent page to correct this.
8150           **
8151           ** If the parent page becomes overfull, the overflow cell or cells
8152           ** are stored in the pSpace buffer allocated immediately below.
8153           ** A subsequent iteration of the do-loop will deal with this by
8154           ** calling balance_nonroot() (balance_deeper() may be called first,
8155           ** but it doesn't deal with overflow cells - just moves them to a
8156           ** different page). Once this subsequent call to balance_nonroot()
8157           ** has completed, it is safe to release the pSpace buffer used by
8158           ** the previous call, as the overflow cell data will have been
8159           ** copied either into the body of a database page or into the new
8160           ** pSpace buffer passed to the latter call to balance_nonroot().
8161           */
8162           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8163           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8164                                pCur->hints&BTREE_BULKLOAD);
8165           if( pFree ){
8166             /* If pFree is not NULL, it points to the pSpace buffer used
8167             ** by a previous call to balance_nonroot(). Its contents are
8168             ** now stored either on real database pages or within the
8169             ** new pSpace buffer, so it may be safely freed here. */
8170             sqlite3PageFree(pFree);
8171           }
8172 
8173           /* The pSpace buffer will be freed after the next call to
8174           ** balance_nonroot(), or just before this function returns, whichever
8175           ** comes first. */
8176           pFree = pSpace;
8177         }
8178       }
8179 
8180       pPage->nOverflow = 0;
8181 
8182       /* The next iteration of the do-loop balances the parent page. */
8183       releasePage(pPage);
8184       pCur->iPage--;
8185       assert( pCur->iPage>=0 );
8186       pCur->pPage = pCur->apPage[pCur->iPage];
8187     }
8188   }while( rc==SQLITE_OK );
8189 
8190   if( pFree ){
8191     sqlite3PageFree(pFree);
8192   }
8193   return rc;
8194 }
8195 
8196 /* Overwrite content from pX into pDest.  Only do the write if the
8197 ** content is different from what is already there.
8198 */
8199 static int btreeOverwriteContent(
8200   MemPage *pPage,           /* MemPage on which writing will occur */
8201   u8 *pDest,                /* Pointer to the place to start writing */
8202   const BtreePayload *pX,   /* Source of data to write */
8203   int iOffset,              /* Offset of first byte to write */
8204   int iAmt                  /* Number of bytes to be written */
8205 ){
8206   int nData = pX->nData - iOffset;
8207   if( nData<=0 ){
8208     /* Overwritting with zeros */
8209     int i;
8210     for(i=0; i<iAmt && pDest[i]==0; i++){}
8211     if( i<iAmt ){
8212       int rc = sqlite3PagerWrite(pPage->pDbPage);
8213       if( rc ) return rc;
8214       memset(pDest + i, 0, iAmt - i);
8215     }
8216   }else{
8217     if( nData<iAmt ){
8218       /* Mixed read data and zeros at the end.  Make a recursive call
8219       ** to write the zeros then fall through to write the real data */
8220       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8221                                  iAmt-nData);
8222       if( rc ) return rc;
8223       iAmt = nData;
8224     }
8225     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8226       int rc = sqlite3PagerWrite(pPage->pDbPage);
8227       if( rc ) return rc;
8228       memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8229     }
8230   }
8231   return SQLITE_OK;
8232 }
8233 
8234 /*
8235 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8236 ** contained in pX.
8237 */
8238 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8239   int iOffset;                        /* Next byte of pX->pData to write */
8240   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8241   int rc;                             /* Return code */
8242   MemPage *pPage = pCur->pPage;       /* Page being written */
8243   BtShared *pBt;                      /* Btree */
8244   Pgno ovflPgno;                      /* Next overflow page to write */
8245   u32 ovflPageSize;                   /* Size to write on overflow page */
8246 
8247   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
8248     return SQLITE_CORRUPT_BKPT;
8249   }
8250   /* Overwrite the local portion first */
8251   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8252                              0, pCur->info.nLocal);
8253   if( rc ) return rc;
8254   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8255 
8256   /* Now overwrite the overflow pages */
8257   iOffset = pCur->info.nLocal;
8258   assert( nTotal>=0 );
8259   assert( iOffset>=0 );
8260   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8261   pBt = pPage->pBt;
8262   ovflPageSize = pBt->usableSize - 4;
8263   do{
8264     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8265     if( rc ) return rc;
8266     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8267       rc = SQLITE_CORRUPT_BKPT;
8268     }else{
8269       if( iOffset+ovflPageSize<(u32)nTotal ){
8270         ovflPgno = get4byte(pPage->aData);
8271       }else{
8272         ovflPageSize = nTotal - iOffset;
8273       }
8274       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8275                                  iOffset, ovflPageSize);
8276     }
8277     sqlite3PagerUnref(pPage->pDbPage);
8278     if( rc ) return rc;
8279     iOffset += ovflPageSize;
8280   }while( iOffset<nTotal );
8281   return SQLITE_OK;
8282 }
8283 
8284 
8285 /*
8286 ** Insert a new record into the BTree.  The content of the new record
8287 ** is described by the pX object.  The pCur cursor is used only to
8288 ** define what table the record should be inserted into, and is left
8289 ** pointing at a random location.
8290 **
8291 ** For a table btree (used for rowid tables), only the pX.nKey value of
8292 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8293 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8294 ** hold the content of the row.
8295 **
8296 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8297 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8298 ** pX.pData,nData,nZero fields must be zero.
8299 **
8300 ** If the seekResult parameter is non-zero, then a successful call to
8301 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8302 ** been performed.  In other words, if seekResult!=0 then the cursor
8303 ** is currently pointing to a cell that will be adjacent to the cell
8304 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8305 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8306 ** that is larger than (pKey,nKey).
8307 **
8308 ** If seekResult==0, that means pCur is pointing at some unknown location.
8309 ** In that case, this routine must seek the cursor to the correct insertion
8310 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8311 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8312 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8313 ** to decode the key.
8314 */
8315 int sqlite3BtreeInsert(
8316   BtCursor *pCur,                /* Insert data into the table of this cursor */
8317   const BtreePayload *pX,        /* Content of the row to be inserted */
8318   int flags,                     /* True if this is likely an append */
8319   int seekResult                 /* Result of prior MovetoUnpacked() call */
8320 ){
8321   int rc;
8322   int loc = seekResult;          /* -1: before desired location  +1: after */
8323   int szNew = 0;
8324   int idx;
8325   MemPage *pPage;
8326   Btree *p = pCur->pBtree;
8327   BtShared *pBt = p->pBt;
8328   unsigned char *oldCell;
8329   unsigned char *newCell = 0;
8330 
8331   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8332 
8333   if( pCur->eState==CURSOR_FAULT ){
8334     assert( pCur->skipNext!=SQLITE_OK );
8335     return pCur->skipNext;
8336   }
8337 
8338   assert( cursorOwnsBtShared(pCur) );
8339   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8340               && pBt->inTransaction==TRANS_WRITE
8341               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8342   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8343 
8344   /* Assert that the caller has been consistent. If this cursor was opened
8345   ** expecting an index b-tree, then the caller should be inserting blob
8346   ** keys with no associated data. If the cursor was opened expecting an
8347   ** intkey table, the caller should be inserting integer keys with a
8348   ** blob of associated data.  */
8349   assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
8350 
8351   /* Save the positions of any other cursors open on this table.
8352   **
8353   ** In some cases, the call to btreeMoveto() below is a no-op. For
8354   ** example, when inserting data into a table with auto-generated integer
8355   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8356   ** integer key to use. It then calls this function to actually insert the
8357   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8358   ** that the cursor is already where it needs to be and returns without
8359   ** doing any work. To avoid thwarting these optimizations, it is important
8360   ** not to clear the cursor here.
8361   */
8362   if( pCur->curFlags & BTCF_Multiple ){
8363     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8364     if( rc ) return rc;
8365   }
8366 
8367   if( pCur->pKeyInfo==0 ){
8368     assert( pX->pKey==0 );
8369     /* If this is an insert into a table b-tree, invalidate any incrblob
8370     ** cursors open on the row being replaced */
8371     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8372 
8373     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8374     ** to a row with the same key as the new entry being inserted.
8375     */
8376 #ifdef SQLITE_DEBUG
8377     if( flags & BTREE_SAVEPOSITION ){
8378       assert( pCur->curFlags & BTCF_ValidNKey );
8379       assert( pX->nKey==pCur->info.nKey );
8380       assert( pCur->info.nSize!=0 );
8381       assert( loc==0 );
8382     }
8383 #endif
8384 
8385     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8386     ** that the cursor is not pointing to a row to be overwritten.
8387     ** So do a complete check.
8388     */
8389     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8390       /* The cursor is pointing to the entry that is to be
8391       ** overwritten */
8392       assert( pX->nData>=0 && pX->nZero>=0 );
8393       if( pCur->info.nSize!=0
8394        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8395       ){
8396         /* New entry is the same size as the old.  Do an overwrite */
8397         return btreeOverwriteCell(pCur, pX);
8398       }
8399       assert( loc==0 );
8400     }else if( loc==0 ){
8401       /* The cursor is *not* pointing to the cell to be overwritten, nor
8402       ** to an adjacent cell.  Move the cursor so that it is pointing either
8403       ** to the cell to be overwritten or an adjacent cell.
8404       */
8405       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8406       if( rc ) return rc;
8407     }
8408   }else{
8409     /* This is an index or a WITHOUT ROWID table */
8410 
8411     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8412     ** to a row with the same key as the new entry being inserted.
8413     */
8414     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8415 
8416     /* If the cursor is not already pointing either to the cell to be
8417     ** overwritten, or if a new cell is being inserted, if the cursor is
8418     ** not pointing to an immediately adjacent cell, then move the cursor
8419     ** so that it does.
8420     */
8421     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8422       if( pX->nMem ){
8423         UnpackedRecord r;
8424         r.pKeyInfo = pCur->pKeyInfo;
8425         r.aMem = pX->aMem;
8426         r.nField = pX->nMem;
8427         r.default_rc = 0;
8428         r.errCode = 0;
8429         r.r1 = 0;
8430         r.r2 = 0;
8431         r.eqSeen = 0;
8432         rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8433       }else{
8434         rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8435       }
8436       if( rc ) return rc;
8437     }
8438 
8439     /* If the cursor is currently pointing to an entry to be overwritten
8440     ** and the new content is the same as as the old, then use the
8441     ** overwrite optimization.
8442     */
8443     if( loc==0 ){
8444       getCellInfo(pCur);
8445       if( pCur->info.nKey==pX->nKey ){
8446         BtreePayload x2;
8447         x2.pData = pX->pKey;
8448         x2.nData = pX->nKey;
8449         x2.nZero = 0;
8450         return btreeOverwriteCell(pCur, &x2);
8451       }
8452     }
8453 
8454   }
8455   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
8456 
8457   pPage = pCur->pPage;
8458   assert( pPage->intKey || pX->nKey>=0 );
8459   assert( pPage->leaf || !pPage->intKey );
8460 
8461   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8462           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8463           loc==0 ? "overwrite" : "new entry"));
8464   assert( pPage->isInit );
8465   newCell = pBt->pTmpSpace;
8466   assert( newCell!=0 );
8467   rc = fillInCell(pPage, newCell, pX, &szNew);
8468   if( rc ) goto end_insert;
8469   assert( szNew==pPage->xCellSize(pPage, newCell) );
8470   assert( szNew <= MX_CELL_SIZE(pBt) );
8471   idx = pCur->ix;
8472   if( loc==0 ){
8473     CellInfo info;
8474     assert( idx<pPage->nCell );
8475     rc = sqlite3PagerWrite(pPage->pDbPage);
8476     if( rc ){
8477       goto end_insert;
8478     }
8479     oldCell = findCell(pPage, idx);
8480     if( !pPage->leaf ){
8481       memcpy(newCell, oldCell, 4);
8482     }
8483     rc = clearCell(pPage, oldCell, &info);
8484     if( info.nSize==szNew && info.nLocal==info.nPayload
8485      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8486     ){
8487       /* Overwrite the old cell with the new if they are the same size.
8488       ** We could also try to do this if the old cell is smaller, then add
8489       ** the leftover space to the free list.  But experiments show that
8490       ** doing that is no faster then skipping this optimization and just
8491       ** calling dropCell() and insertCell().
8492       **
8493       ** This optimization cannot be used on an autovacuum database if the
8494       ** new entry uses overflow pages, as the insertCell() call below is
8495       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
8496       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8497       if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
8498       memcpy(oldCell, newCell, szNew);
8499       return SQLITE_OK;
8500     }
8501     dropCell(pPage, idx, info.nSize, &rc);
8502     if( rc ) goto end_insert;
8503   }else if( loc<0 && pPage->nCell>0 ){
8504     assert( pPage->leaf );
8505     idx = ++pCur->ix;
8506     pCur->curFlags &= ~BTCF_ValidNKey;
8507   }else{
8508     assert( pPage->leaf );
8509   }
8510   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8511   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8512   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8513 
8514   /* If no error has occurred and pPage has an overflow cell, call balance()
8515   ** to redistribute the cells within the tree. Since balance() may move
8516   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8517   ** variables.
8518   **
8519   ** Previous versions of SQLite called moveToRoot() to move the cursor
8520   ** back to the root page as balance() used to invalidate the contents
8521   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8522   ** set the cursor state to "invalid". This makes common insert operations
8523   ** slightly faster.
8524   **
8525   ** There is a subtle but important optimization here too. When inserting
8526   ** multiple records into an intkey b-tree using a single cursor (as can
8527   ** happen while processing an "INSERT INTO ... SELECT" statement), it
8528   ** is advantageous to leave the cursor pointing to the last entry in
8529   ** the b-tree if possible. If the cursor is left pointing to the last
8530   ** entry in the table, and the next row inserted has an integer key
8531   ** larger than the largest existing key, it is possible to insert the
8532   ** row without seeking the cursor. This can be a big performance boost.
8533   */
8534   pCur->info.nSize = 0;
8535   if( pPage->nOverflow ){
8536     assert( rc==SQLITE_OK );
8537     pCur->curFlags &= ~(BTCF_ValidNKey);
8538     rc = balance(pCur);
8539 
8540     /* Must make sure nOverflow is reset to zero even if the balance()
8541     ** fails. Internal data structure corruption will result otherwise.
8542     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8543     ** from trying to save the current position of the cursor.  */
8544     pCur->pPage->nOverflow = 0;
8545     pCur->eState = CURSOR_INVALID;
8546     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8547       btreeReleaseAllCursorPages(pCur);
8548       if( pCur->pKeyInfo ){
8549         assert( pCur->pKey==0 );
8550         pCur->pKey = sqlite3Malloc( pX->nKey );
8551         if( pCur->pKey==0 ){
8552           rc = SQLITE_NOMEM;
8553         }else{
8554           memcpy(pCur->pKey, pX->pKey, pX->nKey);
8555         }
8556       }
8557       pCur->eState = CURSOR_REQUIRESEEK;
8558       pCur->nKey = pX->nKey;
8559     }
8560   }
8561   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8562 
8563 end_insert:
8564   return rc;
8565 }
8566 
8567 /*
8568 ** Delete the entry that the cursor is pointing to.
8569 **
8570 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8571 ** the cursor is left pointing at an arbitrary location after the delete.
8572 ** But if that bit is set, then the cursor is left in a state such that
8573 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
8574 ** as it would have been on if the call to BtreeDelete() had been omitted.
8575 **
8576 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8577 ** associated with a single table entry and its indexes.  Only one of those
8578 ** deletes is considered the "primary" delete.  The primary delete occurs
8579 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
8580 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8581 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
8582 ** but which might be used by alternative storage engines.
8583 */
8584 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
8585   Btree *p = pCur->pBtree;
8586   BtShared *pBt = p->pBt;
8587   int rc;                              /* Return code */
8588   MemPage *pPage;                      /* Page to delete cell from */
8589   unsigned char *pCell;                /* Pointer to cell to delete */
8590   int iCellIdx;                        /* Index of cell to delete */
8591   int iCellDepth;                      /* Depth of node containing pCell */
8592   CellInfo info;                       /* Size of the cell being deleted */
8593   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
8594   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
8595 
8596   assert( cursorOwnsBtShared(pCur) );
8597   assert( pBt->inTransaction==TRANS_WRITE );
8598   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8599   assert( pCur->curFlags & BTCF_WriteFlag );
8600   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8601   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
8602   assert( pCur->ix<pCur->pPage->nCell );
8603   assert( pCur->eState==CURSOR_VALID );
8604   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
8605 
8606   iCellDepth = pCur->iPage;
8607   iCellIdx = pCur->ix;
8608   pPage = pCur->pPage;
8609   pCell = findCell(pPage, iCellIdx);
8610 
8611   /* If the bPreserve flag is set to true, then the cursor position must
8612   ** be preserved following this delete operation. If the current delete
8613   ** will cause a b-tree rebalance, then this is done by saving the cursor
8614   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8615   ** returning.
8616   **
8617   ** Or, if the current delete will not cause a rebalance, then the cursor
8618   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8619   ** before or after the deleted entry. In this case set bSkipnext to true.  */
8620   if( bPreserve ){
8621     if( !pPage->leaf
8622      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8623     ){
8624       /* A b-tree rebalance will be required after deleting this entry.
8625       ** Save the cursor key.  */
8626       rc = saveCursorKey(pCur);
8627       if( rc ) return rc;
8628     }else{
8629       bSkipnext = 1;
8630     }
8631   }
8632 
8633   /* If the page containing the entry to delete is not a leaf page, move
8634   ** the cursor to the largest entry in the tree that is smaller than
8635   ** the entry being deleted. This cell will replace the cell being deleted
8636   ** from the internal node. The 'previous' entry is used for this instead
8637   ** of the 'next' entry, as the previous entry is always a part of the
8638   ** sub-tree headed by the child page of the cell being deleted. This makes
8639   ** balancing the tree following the delete operation easier.  */
8640   if( !pPage->leaf ){
8641     rc = sqlite3BtreePrevious(pCur, 0);
8642     assert( rc!=SQLITE_DONE );
8643     if( rc ) return rc;
8644   }
8645 
8646   /* Save the positions of any other cursors open on this table before
8647   ** making any modifications.  */
8648   if( pCur->curFlags & BTCF_Multiple ){
8649     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8650     if( rc ) return rc;
8651   }
8652 
8653   /* If this is a delete operation to remove a row from a table b-tree,
8654   ** invalidate any incrblob cursors open on the row being deleted.  */
8655   if( pCur->pKeyInfo==0 ){
8656     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
8657   }
8658 
8659   /* Make the page containing the entry to be deleted writable. Then free any
8660   ** overflow pages associated with the entry and finally remove the cell
8661   ** itself from within the page.  */
8662   rc = sqlite3PagerWrite(pPage->pDbPage);
8663   if( rc ) return rc;
8664   rc = clearCell(pPage, pCell, &info);
8665   dropCell(pPage, iCellIdx, info.nSize, &rc);
8666   if( rc ) return rc;
8667 
8668   /* If the cell deleted was not located on a leaf page, then the cursor
8669   ** is currently pointing to the largest entry in the sub-tree headed
8670   ** by the child-page of the cell that was just deleted from an internal
8671   ** node. The cell from the leaf node needs to be moved to the internal
8672   ** node to replace the deleted cell.  */
8673   if( !pPage->leaf ){
8674     MemPage *pLeaf = pCur->pPage;
8675     int nCell;
8676     Pgno n;
8677     unsigned char *pTmp;
8678 
8679     if( iCellDepth<pCur->iPage-1 ){
8680       n = pCur->apPage[iCellDepth+1]->pgno;
8681     }else{
8682       n = pCur->pPage->pgno;
8683     }
8684     pCell = findCell(pLeaf, pLeaf->nCell-1);
8685     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
8686     nCell = pLeaf->xCellSize(pLeaf, pCell);
8687     assert( MX_CELL_SIZE(pBt) >= nCell );
8688     pTmp = pBt->pTmpSpace;
8689     assert( pTmp!=0 );
8690     rc = sqlite3PagerWrite(pLeaf->pDbPage);
8691     if( rc==SQLITE_OK ){
8692       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8693     }
8694     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
8695     if( rc ) return rc;
8696   }
8697 
8698   /* Balance the tree. If the entry deleted was located on a leaf page,
8699   ** then the cursor still points to that page. In this case the first
8700   ** call to balance() repairs the tree, and the if(...) condition is
8701   ** never true.
8702   **
8703   ** Otherwise, if the entry deleted was on an internal node page, then
8704   ** pCur is pointing to the leaf page from which a cell was removed to
8705   ** replace the cell deleted from the internal node. This is slightly
8706   ** tricky as the leaf node may be underfull, and the internal node may
8707   ** be either under or overfull. In this case run the balancing algorithm
8708   ** on the leaf node first. If the balance proceeds far enough up the
8709   ** tree that we can be sure that any problem in the internal node has
8710   ** been corrected, so be it. Otherwise, after balancing the leaf node,
8711   ** walk the cursor up the tree to the internal node and balance it as
8712   ** well.  */
8713   rc = balance(pCur);
8714   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8715     releasePageNotNull(pCur->pPage);
8716     pCur->iPage--;
8717     while( pCur->iPage>iCellDepth ){
8718       releasePage(pCur->apPage[pCur->iPage--]);
8719     }
8720     pCur->pPage = pCur->apPage[pCur->iPage];
8721     rc = balance(pCur);
8722   }
8723 
8724   if( rc==SQLITE_OK ){
8725     if( bSkipnext ){
8726       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
8727       assert( pPage==pCur->pPage || CORRUPT_DB );
8728       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
8729       pCur->eState = CURSOR_SKIPNEXT;
8730       if( iCellIdx>=pPage->nCell ){
8731         pCur->skipNext = -1;
8732         pCur->ix = pPage->nCell-1;
8733       }else{
8734         pCur->skipNext = 1;
8735       }
8736     }else{
8737       rc = moveToRoot(pCur);
8738       if( bPreserve ){
8739         btreeReleaseAllCursorPages(pCur);
8740         pCur->eState = CURSOR_REQUIRESEEK;
8741       }
8742       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
8743     }
8744   }
8745   return rc;
8746 }
8747 
8748 /*
8749 ** Create a new BTree table.  Write into *piTable the page
8750 ** number for the root page of the new table.
8751 **
8752 ** The type of type is determined by the flags parameter.  Only the
8753 ** following values of flags are currently in use.  Other values for
8754 ** flags might not work:
8755 **
8756 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
8757 **     BTREE_ZERODATA                  Used for SQL indices
8758 */
8759 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
8760   BtShared *pBt = p->pBt;
8761   MemPage *pRoot;
8762   Pgno pgnoRoot;
8763   int rc;
8764   int ptfFlags;          /* Page-type flage for the root page of new table */
8765 
8766   assert( sqlite3BtreeHoldsMutex(p) );
8767   assert( pBt->inTransaction==TRANS_WRITE );
8768   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8769 
8770 #ifdef SQLITE_OMIT_AUTOVACUUM
8771   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8772   if( rc ){
8773     return rc;
8774   }
8775 #else
8776   if( pBt->autoVacuum ){
8777     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
8778     MemPage *pPageMove; /* The page to move to. */
8779 
8780     /* Creating a new table may probably require moving an existing database
8781     ** to make room for the new tables root page. In case this page turns
8782     ** out to be an overflow page, delete all overflow page-map caches
8783     ** held by open cursors.
8784     */
8785     invalidateAllOverflowCache(pBt);
8786 
8787     /* Read the value of meta[3] from the database to determine where the
8788     ** root page of the new table should go. meta[3] is the largest root-page
8789     ** created so far, so the new root-page is (meta[3]+1).
8790     */
8791     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
8792     pgnoRoot++;
8793 
8794     /* The new root-page may not be allocated on a pointer-map page, or the
8795     ** PENDING_BYTE page.
8796     */
8797     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
8798         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
8799       pgnoRoot++;
8800     }
8801     assert( pgnoRoot>=3 || CORRUPT_DB );
8802     testcase( pgnoRoot<3 );
8803 
8804     /* Allocate a page. The page that currently resides at pgnoRoot will
8805     ** be moved to the allocated page (unless the allocated page happens
8806     ** to reside at pgnoRoot).
8807     */
8808     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
8809     if( rc!=SQLITE_OK ){
8810       return rc;
8811     }
8812 
8813     if( pgnoMove!=pgnoRoot ){
8814       /* pgnoRoot is the page that will be used for the root-page of
8815       ** the new table (assuming an error did not occur). But we were
8816       ** allocated pgnoMove. If required (i.e. if it was not allocated
8817       ** by extending the file), the current page at position pgnoMove
8818       ** is already journaled.
8819       */
8820       u8 eType = 0;
8821       Pgno iPtrPage = 0;
8822 
8823       /* Save the positions of any open cursors. This is required in
8824       ** case they are holding a reference to an xFetch reference
8825       ** corresponding to page pgnoRoot.  */
8826       rc = saveAllCursors(pBt, 0, 0);
8827       releasePage(pPageMove);
8828       if( rc!=SQLITE_OK ){
8829         return rc;
8830       }
8831 
8832       /* Move the page currently at pgnoRoot to pgnoMove. */
8833       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8834       if( rc!=SQLITE_OK ){
8835         return rc;
8836       }
8837       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
8838       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8839         rc = SQLITE_CORRUPT_BKPT;
8840       }
8841       if( rc!=SQLITE_OK ){
8842         releasePage(pRoot);
8843         return rc;
8844       }
8845       assert( eType!=PTRMAP_ROOTPAGE );
8846       assert( eType!=PTRMAP_FREEPAGE );
8847       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
8848       releasePage(pRoot);
8849 
8850       /* Obtain the page at pgnoRoot */
8851       if( rc!=SQLITE_OK ){
8852         return rc;
8853       }
8854       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8855       if( rc!=SQLITE_OK ){
8856         return rc;
8857       }
8858       rc = sqlite3PagerWrite(pRoot->pDbPage);
8859       if( rc!=SQLITE_OK ){
8860         releasePage(pRoot);
8861         return rc;
8862       }
8863     }else{
8864       pRoot = pPageMove;
8865     }
8866 
8867     /* Update the pointer-map and meta-data with the new root-page number. */
8868     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
8869     if( rc ){
8870       releasePage(pRoot);
8871       return rc;
8872     }
8873 
8874     /* When the new root page was allocated, page 1 was made writable in
8875     ** order either to increase the database filesize, or to decrement the
8876     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8877     */
8878     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
8879     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
8880     if( NEVER(rc) ){
8881       releasePage(pRoot);
8882       return rc;
8883     }
8884 
8885   }else{
8886     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8887     if( rc ) return rc;
8888   }
8889 #endif
8890   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8891   if( createTabFlags & BTREE_INTKEY ){
8892     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8893   }else{
8894     ptfFlags = PTF_ZERODATA | PTF_LEAF;
8895   }
8896   zeroPage(pRoot, ptfFlags);
8897   sqlite3PagerUnref(pRoot->pDbPage);
8898   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
8899   *piTable = (int)pgnoRoot;
8900   return SQLITE_OK;
8901 }
8902 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8903   int rc;
8904   sqlite3BtreeEnter(p);
8905   rc = btreeCreateTable(p, piTable, flags);
8906   sqlite3BtreeLeave(p);
8907   return rc;
8908 }
8909 
8910 /*
8911 ** Erase the given database page and all its children.  Return
8912 ** the page to the freelist.
8913 */
8914 static int clearDatabasePage(
8915   BtShared *pBt,           /* The BTree that contains the table */
8916   Pgno pgno,               /* Page number to clear */
8917   int freePageFlag,        /* Deallocate page if true */
8918   int *pnChange            /* Add number of Cells freed to this counter */
8919 ){
8920   MemPage *pPage;
8921   int rc;
8922   unsigned char *pCell;
8923   int i;
8924   int hdr;
8925   CellInfo info;
8926 
8927   assert( sqlite3_mutex_held(pBt->mutex) );
8928   if( pgno>btreePagecount(pBt) ){
8929     return SQLITE_CORRUPT_BKPT;
8930   }
8931   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
8932   if( rc ) return rc;
8933   if( pPage->bBusy ){
8934     rc = SQLITE_CORRUPT_BKPT;
8935     goto cleardatabasepage_out;
8936   }
8937   pPage->bBusy = 1;
8938   hdr = pPage->hdrOffset;
8939   for(i=0; i<pPage->nCell; i++){
8940     pCell = findCell(pPage, i);
8941     if( !pPage->leaf ){
8942       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
8943       if( rc ) goto cleardatabasepage_out;
8944     }
8945     rc = clearCell(pPage, pCell, &info);
8946     if( rc ) goto cleardatabasepage_out;
8947   }
8948   if( !pPage->leaf ){
8949     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
8950     if( rc ) goto cleardatabasepage_out;
8951   }else if( pnChange ){
8952     assert( pPage->intKey || CORRUPT_DB );
8953     testcase( !pPage->intKey );
8954     *pnChange += pPage->nCell;
8955   }
8956   if( freePageFlag ){
8957     freePage(pPage, &rc);
8958   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
8959     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
8960   }
8961 
8962 cleardatabasepage_out:
8963   pPage->bBusy = 0;
8964   releasePage(pPage);
8965   return rc;
8966 }
8967 
8968 /*
8969 ** Delete all information from a single table in the database.  iTable is
8970 ** the page number of the root of the table.  After this routine returns,
8971 ** the root page is empty, but still exists.
8972 **
8973 ** This routine will fail with SQLITE_LOCKED if there are any open
8974 ** read cursors on the table.  Open write cursors are moved to the
8975 ** root of the table.
8976 **
8977 ** If pnChange is not NULL, then table iTable must be an intkey table. The
8978 ** integer value pointed to by pnChange is incremented by the number of
8979 ** entries in the table.
8980 */
8981 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
8982   int rc;
8983   BtShared *pBt = p->pBt;
8984   sqlite3BtreeEnter(p);
8985   assert( p->inTrans==TRANS_WRITE );
8986 
8987   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
8988 
8989   if( SQLITE_OK==rc ){
8990     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8991     ** is the root of a table b-tree - if it is not, the following call is
8992     ** a no-op).  */
8993     invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
8994     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
8995   }
8996   sqlite3BtreeLeave(p);
8997   return rc;
8998 }
8999 
9000 /*
9001 ** Delete all information from the single table that pCur is open on.
9002 **
9003 ** This routine only work for pCur on an ephemeral table.
9004 */
9005 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9006   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9007 }
9008 
9009 /*
9010 ** Erase all information in a table and add the root of the table to
9011 ** the freelist.  Except, the root of the principle table (the one on
9012 ** page 1) is never added to the freelist.
9013 **
9014 ** This routine will fail with SQLITE_LOCKED if there are any open
9015 ** cursors on the table.
9016 **
9017 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9018 ** root page in the database file, then the last root page
9019 ** in the database file is moved into the slot formerly occupied by
9020 ** iTable and that last slot formerly occupied by the last root page
9021 ** is added to the freelist instead of iTable.  In this say, all
9022 ** root pages are kept at the beginning of the database file, which
9023 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9024 ** page number that used to be the last root page in the file before
9025 ** the move.  If no page gets moved, *piMoved is set to 0.
9026 ** The last root page is recorded in meta[3] and the value of
9027 ** meta[3] is updated by this procedure.
9028 */
9029 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9030   int rc;
9031   MemPage *pPage = 0;
9032   BtShared *pBt = p->pBt;
9033 
9034   assert( sqlite3BtreeHoldsMutex(p) );
9035   assert( p->inTrans==TRANS_WRITE );
9036   assert( iTable>=2 );
9037 
9038   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9039   if( rc ) return rc;
9040   rc = sqlite3BtreeClearTable(p, iTable, 0);
9041   if( rc ){
9042     releasePage(pPage);
9043     return rc;
9044   }
9045 
9046   *piMoved = 0;
9047 
9048 #ifdef SQLITE_OMIT_AUTOVACUUM
9049   freePage(pPage, &rc);
9050   releasePage(pPage);
9051 #else
9052   if( pBt->autoVacuum ){
9053     Pgno maxRootPgno;
9054     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9055 
9056     if( iTable==maxRootPgno ){
9057       /* If the table being dropped is the table with the largest root-page
9058       ** number in the database, put the root page on the free list.
9059       */
9060       freePage(pPage, &rc);
9061       releasePage(pPage);
9062       if( rc!=SQLITE_OK ){
9063         return rc;
9064       }
9065     }else{
9066       /* The table being dropped does not have the largest root-page
9067       ** number in the database. So move the page that does into the
9068       ** gap left by the deleted root-page.
9069       */
9070       MemPage *pMove;
9071       releasePage(pPage);
9072       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9073       if( rc!=SQLITE_OK ){
9074         return rc;
9075       }
9076       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9077       releasePage(pMove);
9078       if( rc!=SQLITE_OK ){
9079         return rc;
9080       }
9081       pMove = 0;
9082       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9083       freePage(pMove, &rc);
9084       releasePage(pMove);
9085       if( rc!=SQLITE_OK ){
9086         return rc;
9087       }
9088       *piMoved = maxRootPgno;
9089     }
9090 
9091     /* Set the new 'max-root-page' value in the database header. This
9092     ** is the old value less one, less one more if that happens to
9093     ** be a root-page number, less one again if that is the
9094     ** PENDING_BYTE_PAGE.
9095     */
9096     maxRootPgno--;
9097     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9098            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9099       maxRootPgno--;
9100     }
9101     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9102 
9103     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9104   }else{
9105     freePage(pPage, &rc);
9106     releasePage(pPage);
9107   }
9108 #endif
9109   return rc;
9110 }
9111 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9112   int rc;
9113   sqlite3BtreeEnter(p);
9114   rc = btreeDropTable(p, iTable, piMoved);
9115   sqlite3BtreeLeave(p);
9116   return rc;
9117 }
9118 
9119 
9120 /*
9121 ** This function may only be called if the b-tree connection already
9122 ** has a read or write transaction open on the database.
9123 **
9124 ** Read the meta-information out of a database file.  Meta[0]
9125 ** is the number of free pages currently in the database.  Meta[1]
9126 ** through meta[15] are available for use by higher layers.  Meta[0]
9127 ** is read-only, the others are read/write.
9128 **
9129 ** The schema layer numbers meta values differently.  At the schema
9130 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9131 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
9132 **
9133 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
9134 ** of reading the value out of the header, it instead loads the "DataVersion"
9135 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
9136 ** database file.  It is a number computed by the pager.  But its access
9137 ** pattern is the same as header meta values, and so it is convenient to
9138 ** read it from this routine.
9139 */
9140 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9141   BtShared *pBt = p->pBt;
9142 
9143   sqlite3BtreeEnter(p);
9144   assert( p->inTrans>TRANS_NONE );
9145   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
9146   assert( pBt->pPage1 );
9147   assert( idx>=0 && idx<=15 );
9148 
9149   if( idx==BTREE_DATA_VERSION ){
9150     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
9151   }else{
9152     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9153   }
9154 
9155   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9156   ** database, mark the database as read-only.  */
9157 #ifdef SQLITE_OMIT_AUTOVACUUM
9158   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9159     pBt->btsFlags |= BTS_READ_ONLY;
9160   }
9161 #endif
9162 
9163   sqlite3BtreeLeave(p);
9164 }
9165 
9166 /*
9167 ** Write meta-information back into the database.  Meta[0] is
9168 ** read-only and may not be written.
9169 */
9170 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9171   BtShared *pBt = p->pBt;
9172   unsigned char *pP1;
9173   int rc;
9174   assert( idx>=1 && idx<=15 );
9175   sqlite3BtreeEnter(p);
9176   assert( p->inTrans==TRANS_WRITE );
9177   assert( pBt->pPage1!=0 );
9178   pP1 = pBt->pPage1->aData;
9179   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9180   if( rc==SQLITE_OK ){
9181     put4byte(&pP1[36 + idx*4], iMeta);
9182 #ifndef SQLITE_OMIT_AUTOVACUUM
9183     if( idx==BTREE_INCR_VACUUM ){
9184       assert( pBt->autoVacuum || iMeta==0 );
9185       assert( iMeta==0 || iMeta==1 );
9186       pBt->incrVacuum = (u8)iMeta;
9187     }
9188 #endif
9189   }
9190   sqlite3BtreeLeave(p);
9191   return rc;
9192 }
9193 
9194 #ifndef SQLITE_OMIT_BTREECOUNT
9195 /*
9196 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9197 ** number of entries in the b-tree and write the result to *pnEntry.
9198 **
9199 ** SQLITE_OK is returned if the operation is successfully executed.
9200 ** Otherwise, if an error is encountered (i.e. an IO error or database
9201 ** corruption) an SQLite error code is returned.
9202 */
9203 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
9204   i64 nEntry = 0;                      /* Value to return in *pnEntry */
9205   int rc;                              /* Return code */
9206 
9207   rc = moveToRoot(pCur);
9208   if( rc==SQLITE_EMPTY ){
9209     *pnEntry = 0;
9210     return SQLITE_OK;
9211   }
9212 
9213   /* Unless an error occurs, the following loop runs one iteration for each
9214   ** page in the B-Tree structure (not including overflow pages).
9215   */
9216   while( rc==SQLITE_OK ){
9217     int iIdx;                          /* Index of child node in parent */
9218     MemPage *pPage;                    /* Current page of the b-tree */
9219 
9220     /* If this is a leaf page or the tree is not an int-key tree, then
9221     ** this page contains countable entries. Increment the entry counter
9222     ** accordingly.
9223     */
9224     pPage = pCur->pPage;
9225     if( pPage->leaf || !pPage->intKey ){
9226       nEntry += pPage->nCell;
9227     }
9228 
9229     /* pPage is a leaf node. This loop navigates the cursor so that it
9230     ** points to the first interior cell that it points to the parent of
9231     ** the next page in the tree that has not yet been visited. The
9232     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9233     ** of the page, or to the number of cells in the page if the next page
9234     ** to visit is the right-child of its parent.
9235     **
9236     ** If all pages in the tree have been visited, return SQLITE_OK to the
9237     ** caller.
9238     */
9239     if( pPage->leaf ){
9240       do {
9241         if( pCur->iPage==0 ){
9242           /* All pages of the b-tree have been visited. Return successfully. */
9243           *pnEntry = nEntry;
9244           return moveToRoot(pCur);
9245         }
9246         moveToParent(pCur);
9247       }while ( pCur->ix>=pCur->pPage->nCell );
9248 
9249       pCur->ix++;
9250       pPage = pCur->pPage;
9251     }
9252 
9253     /* Descend to the child node of the cell that the cursor currently
9254     ** points at. This is the right-child if (iIdx==pPage->nCell).
9255     */
9256     iIdx = pCur->ix;
9257     if( iIdx==pPage->nCell ){
9258       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9259     }else{
9260       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9261     }
9262   }
9263 
9264   /* An error has occurred. Return an error code. */
9265   return rc;
9266 }
9267 #endif
9268 
9269 /*
9270 ** Return the pager associated with a BTree.  This routine is used for
9271 ** testing and debugging only.
9272 */
9273 Pager *sqlite3BtreePager(Btree *p){
9274   return p->pBt->pPager;
9275 }
9276 
9277 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9278 /*
9279 ** Append a message to the error message string.
9280 */
9281 static void checkAppendMsg(
9282   IntegrityCk *pCheck,
9283   const char *zFormat,
9284   ...
9285 ){
9286   va_list ap;
9287   if( !pCheck->mxErr ) return;
9288   pCheck->mxErr--;
9289   pCheck->nErr++;
9290   va_start(ap, zFormat);
9291   if( pCheck->errMsg.nChar ){
9292     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9293   }
9294   if( pCheck->zPfx ){
9295     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9296   }
9297   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9298   va_end(ap);
9299   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9300     pCheck->mallocFailed = 1;
9301   }
9302 }
9303 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9304 
9305 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9306 
9307 /*
9308 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9309 ** corresponds to page iPg is already set.
9310 */
9311 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9312   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9313   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9314 }
9315 
9316 /*
9317 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9318 */
9319 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9320   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9321   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9322 }
9323 
9324 
9325 /*
9326 ** Add 1 to the reference count for page iPage.  If this is the second
9327 ** reference to the page, add an error message to pCheck->zErrMsg.
9328 ** Return 1 if there are 2 or more references to the page and 0 if
9329 ** if this is the first reference to the page.
9330 **
9331 ** Also check that the page number is in bounds.
9332 */
9333 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9334   if( iPage==0 ) return 1;
9335   if( iPage>pCheck->nPage ){
9336     checkAppendMsg(pCheck, "invalid page number %d", iPage);
9337     return 1;
9338   }
9339   if( getPageReferenced(pCheck, iPage) ){
9340     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9341     return 1;
9342   }
9343   setPageReferenced(pCheck, iPage);
9344   return 0;
9345 }
9346 
9347 #ifndef SQLITE_OMIT_AUTOVACUUM
9348 /*
9349 ** Check that the entry in the pointer-map for page iChild maps to
9350 ** page iParent, pointer type ptrType. If not, append an error message
9351 ** to pCheck.
9352 */
9353 static void checkPtrmap(
9354   IntegrityCk *pCheck,   /* Integrity check context */
9355   Pgno iChild,           /* Child page number */
9356   u8 eType,              /* Expected pointer map type */
9357   Pgno iParent           /* Expected pointer map parent page number */
9358 ){
9359   int rc;
9360   u8 ePtrmapType;
9361   Pgno iPtrmapParent;
9362 
9363   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9364   if( rc!=SQLITE_OK ){
9365     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
9366     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9367     return;
9368   }
9369 
9370   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9371     checkAppendMsg(pCheck,
9372       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9373       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9374   }
9375 }
9376 #endif
9377 
9378 /*
9379 ** Check the integrity of the freelist or of an overflow page list.
9380 ** Verify that the number of pages on the list is N.
9381 */
9382 static void checkList(
9383   IntegrityCk *pCheck,  /* Integrity checking context */
9384   int isFreeList,       /* True for a freelist.  False for overflow page list */
9385   int iPage,            /* Page number for first page in the list */
9386   int N                 /* Expected number of pages in the list */
9387 ){
9388   int i;
9389   int expected = N;
9390   int iFirst = iPage;
9391   while( N-- > 0 && pCheck->mxErr ){
9392     DbPage *pOvflPage;
9393     unsigned char *pOvflData;
9394     if( iPage<1 ){
9395       checkAppendMsg(pCheck,
9396          "%d of %d pages missing from overflow list starting at %d",
9397           N+1, expected, iFirst);
9398       break;
9399     }
9400     if( checkRef(pCheck, iPage) ) break;
9401     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9402       checkAppendMsg(pCheck, "failed to get page %d", iPage);
9403       break;
9404     }
9405     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9406     if( isFreeList ){
9407       int n = get4byte(&pOvflData[4]);
9408 #ifndef SQLITE_OMIT_AUTOVACUUM
9409       if( pCheck->pBt->autoVacuum ){
9410         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9411       }
9412 #endif
9413       if( n>(int)pCheck->pBt->usableSize/4-2 ){
9414         checkAppendMsg(pCheck,
9415            "freelist leaf count too big on page %d", iPage);
9416         N--;
9417       }else{
9418         for(i=0; i<n; i++){
9419           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9420 #ifndef SQLITE_OMIT_AUTOVACUUM
9421           if( pCheck->pBt->autoVacuum ){
9422             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9423           }
9424 #endif
9425           checkRef(pCheck, iFreePage);
9426         }
9427         N -= n;
9428       }
9429     }
9430 #ifndef SQLITE_OMIT_AUTOVACUUM
9431     else{
9432       /* If this database supports auto-vacuum and iPage is not the last
9433       ** page in this overflow list, check that the pointer-map entry for
9434       ** the following page matches iPage.
9435       */
9436       if( pCheck->pBt->autoVacuum && N>0 ){
9437         i = get4byte(pOvflData);
9438         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9439       }
9440     }
9441 #endif
9442     iPage = get4byte(pOvflData);
9443     sqlite3PagerUnref(pOvflPage);
9444 
9445     if( isFreeList && N<(iPage!=0) ){
9446       checkAppendMsg(pCheck, "free-page count in header is too small");
9447     }
9448   }
9449 }
9450 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9451 
9452 /*
9453 ** An implementation of a min-heap.
9454 **
9455 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
9456 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
9457 ** and aHeap[N*2+1].
9458 **
9459 ** The heap property is this:  Every node is less than or equal to both
9460 ** of its daughter nodes.  A consequence of the heap property is that the
9461 ** root node aHeap[1] is always the minimum value currently in the heap.
9462 **
9463 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9464 ** the heap, preserving the heap property.  The btreeHeapPull() routine
9465 ** removes the root element from the heap (the minimum value in the heap)
9466 ** and then moves other nodes around as necessary to preserve the heap
9467 ** property.
9468 **
9469 ** This heap is used for cell overlap and coverage testing.  Each u32
9470 ** entry represents the span of a cell or freeblock on a btree page.
9471 ** The upper 16 bits are the index of the first byte of a range and the
9472 ** lower 16 bits are the index of the last byte of that range.
9473 */
9474 static void btreeHeapInsert(u32 *aHeap, u32 x){
9475   u32 j, i = ++aHeap[0];
9476   aHeap[i] = x;
9477   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9478     x = aHeap[j];
9479     aHeap[j] = aHeap[i];
9480     aHeap[i] = x;
9481     i = j;
9482   }
9483 }
9484 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9485   u32 j, i, x;
9486   if( (x = aHeap[0])==0 ) return 0;
9487   *pOut = aHeap[1];
9488   aHeap[1] = aHeap[x];
9489   aHeap[x] = 0xffffffff;
9490   aHeap[0]--;
9491   i = 1;
9492   while( (j = i*2)<=aHeap[0] ){
9493     if( aHeap[j]>aHeap[j+1] ) j++;
9494     if( aHeap[i]<aHeap[j] ) break;
9495     x = aHeap[i];
9496     aHeap[i] = aHeap[j];
9497     aHeap[j] = x;
9498     i = j;
9499   }
9500   return 1;
9501 }
9502 
9503 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9504 /*
9505 ** Do various sanity checks on a single page of a tree.  Return
9506 ** the tree depth.  Root pages return 0.  Parents of root pages
9507 ** return 1, and so forth.
9508 **
9509 ** These checks are done:
9510 **
9511 **      1.  Make sure that cells and freeblocks do not overlap
9512 **          but combine to completely cover the page.
9513 **      2.  Make sure integer cell keys are in order.
9514 **      3.  Check the integrity of overflow pages.
9515 **      4.  Recursively call checkTreePage on all children.
9516 **      5.  Verify that the depth of all children is the same.
9517 */
9518 static int checkTreePage(
9519   IntegrityCk *pCheck,  /* Context for the sanity check */
9520   int iPage,            /* Page number of the page to check */
9521   i64 *piMinKey,        /* Write minimum integer primary key here */
9522   i64 maxKey            /* Error if integer primary key greater than this */
9523 ){
9524   MemPage *pPage = 0;      /* The page being analyzed */
9525   int i;                   /* Loop counter */
9526   int rc;                  /* Result code from subroutine call */
9527   int depth = -1, d2;      /* Depth of a subtree */
9528   int pgno;                /* Page number */
9529   int nFrag;               /* Number of fragmented bytes on the page */
9530   int hdr;                 /* Offset to the page header */
9531   int cellStart;           /* Offset to the start of the cell pointer array */
9532   int nCell;               /* Number of cells */
9533   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9534   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
9535                            ** False if IPK must be strictly less than maxKey */
9536   u8 *data;                /* Page content */
9537   u8 *pCell;               /* Cell content */
9538   u8 *pCellIdx;            /* Next element of the cell pointer array */
9539   BtShared *pBt;           /* The BtShared object that owns pPage */
9540   u32 pc;                  /* Address of a cell */
9541   u32 usableSize;          /* Usable size of the page */
9542   u32 contentOffset;       /* Offset to the start of the cell content area */
9543   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
9544   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
9545   const char *saved_zPfx = pCheck->zPfx;
9546   int saved_v1 = pCheck->v1;
9547   int saved_v2 = pCheck->v2;
9548   u8 savedIsInit = 0;
9549 
9550   /* Check that the page exists
9551   */
9552   pBt = pCheck->pBt;
9553   usableSize = pBt->usableSize;
9554   if( iPage==0 ) return 0;
9555   if( checkRef(pCheck, iPage) ) return 0;
9556   pCheck->zPfx = "Page %d: ";
9557   pCheck->v1 = iPage;
9558   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
9559     checkAppendMsg(pCheck,
9560        "unable to get the page. error code=%d", rc);
9561     goto end_of_check;
9562   }
9563 
9564   /* Clear MemPage.isInit to make sure the corruption detection code in
9565   ** btreeInitPage() is executed.  */
9566   savedIsInit = pPage->isInit;
9567   pPage->isInit = 0;
9568   if( (rc = btreeInitPage(pPage))!=0 ){
9569     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
9570     checkAppendMsg(pCheck,
9571                    "btreeInitPage() returns error code %d", rc);
9572     goto end_of_check;
9573   }
9574   data = pPage->aData;
9575   hdr = pPage->hdrOffset;
9576 
9577   /* Set up for cell analysis */
9578   pCheck->zPfx = "On tree page %d cell %d: ";
9579   contentOffset = get2byteNotZero(&data[hdr+5]);
9580   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
9581 
9582   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9583   ** number of cells on the page. */
9584   nCell = get2byte(&data[hdr+3]);
9585   assert( pPage->nCell==nCell );
9586 
9587   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9588   ** immediately follows the b-tree page header. */
9589   cellStart = hdr + 12 - 4*pPage->leaf;
9590   assert( pPage->aCellIdx==&data[cellStart] );
9591   pCellIdx = &data[cellStart + 2*(nCell-1)];
9592 
9593   if( !pPage->leaf ){
9594     /* Analyze the right-child page of internal pages */
9595     pgno = get4byte(&data[hdr+8]);
9596 #ifndef SQLITE_OMIT_AUTOVACUUM
9597     if( pBt->autoVacuum ){
9598       pCheck->zPfx = "On page %d at right child: ";
9599       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9600     }
9601 #endif
9602     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9603     keyCanBeEqual = 0;
9604   }else{
9605     /* For leaf pages, the coverage check will occur in the same loop
9606     ** as the other cell checks, so initialize the heap.  */
9607     heap = pCheck->heap;
9608     heap[0] = 0;
9609   }
9610 
9611   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9612   ** integer offsets to the cell contents. */
9613   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
9614     CellInfo info;
9615 
9616     /* Check cell size */
9617     pCheck->v2 = i;
9618     assert( pCellIdx==&data[cellStart + i*2] );
9619     pc = get2byteAligned(pCellIdx);
9620     pCellIdx -= 2;
9621     if( pc<contentOffset || pc>usableSize-4 ){
9622       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9623                              pc, contentOffset, usableSize-4);
9624       doCoverageCheck = 0;
9625       continue;
9626     }
9627     pCell = &data[pc];
9628     pPage->xParseCell(pPage, pCell, &info);
9629     if( pc+info.nSize>usableSize ){
9630       checkAppendMsg(pCheck, "Extends off end of page");
9631       doCoverageCheck = 0;
9632       continue;
9633     }
9634 
9635     /* Check for integer primary key out of range */
9636     if( pPage->intKey ){
9637       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9638         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9639       }
9640       maxKey = info.nKey;
9641       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
9642     }
9643 
9644     /* Check the content overflow list */
9645     if( info.nPayload>info.nLocal ){
9646       int nPage;       /* Number of pages on the overflow chain */
9647       Pgno pgnoOvfl;   /* First page of the overflow chain */
9648       assert( pc + info.nSize - 4 <= usableSize );
9649       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
9650       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
9651 #ifndef SQLITE_OMIT_AUTOVACUUM
9652       if( pBt->autoVacuum ){
9653         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
9654       }
9655 #endif
9656       checkList(pCheck, 0, pgnoOvfl, nPage);
9657     }
9658 
9659     if( !pPage->leaf ){
9660       /* Check sanity of left child page for internal pages */
9661       pgno = get4byte(pCell);
9662 #ifndef SQLITE_OMIT_AUTOVACUUM
9663       if( pBt->autoVacuum ){
9664         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9665       }
9666 #endif
9667       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9668       keyCanBeEqual = 0;
9669       if( d2!=depth ){
9670         checkAppendMsg(pCheck, "Child page depth differs");
9671         depth = d2;
9672       }
9673     }else{
9674       /* Populate the coverage-checking heap for leaf pages */
9675       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
9676     }
9677   }
9678   *piMinKey = maxKey;
9679 
9680   /* Check for complete coverage of the page
9681   */
9682   pCheck->zPfx = 0;
9683   if( doCoverageCheck && pCheck->mxErr>0 ){
9684     /* For leaf pages, the min-heap has already been initialized and the
9685     ** cells have already been inserted.  But for internal pages, that has
9686     ** not yet been done, so do it now */
9687     if( !pPage->leaf ){
9688       heap = pCheck->heap;
9689       heap[0] = 0;
9690       for(i=nCell-1; i>=0; i--){
9691         u32 size;
9692         pc = get2byteAligned(&data[cellStart+i*2]);
9693         size = pPage->xCellSize(pPage, &data[pc]);
9694         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
9695       }
9696     }
9697     /* Add the freeblocks to the min-heap
9698     **
9699     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
9700     ** is the offset of the first freeblock, or zero if there are no
9701     ** freeblocks on the page.
9702     */
9703     i = get2byte(&data[hdr+1]);
9704     while( i>0 ){
9705       int size, j;
9706       assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
9707       size = get2byte(&data[i+2]);
9708       assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
9709       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
9710       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9711       ** big-endian integer which is the offset in the b-tree page of the next
9712       ** freeblock in the chain, or zero if the freeblock is the last on the
9713       ** chain. */
9714       j = get2byte(&data[i]);
9715       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9716       ** increasing offset. */
9717       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
9718       assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
9719       i = j;
9720     }
9721     /* Analyze the min-heap looking for overlap between cells and/or
9722     ** freeblocks, and counting the number of untracked bytes in nFrag.
9723     **
9724     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
9725     ** There is an implied first entry the covers the page header, the cell
9726     ** pointer index, and the gap between the cell pointer index and the start
9727     ** of cell content.
9728     **
9729     ** The loop below pulls entries from the min-heap in order and compares
9730     ** the start_address against the previous end_address.  If there is an
9731     ** overlap, that means bytes are used multiple times.  If there is a gap,
9732     ** that gap is added to the fragmentation count.
9733     */
9734     nFrag = 0;
9735     prev = contentOffset - 1;   /* Implied first min-heap entry */
9736     while( btreeHeapPull(heap,&x) ){
9737       if( (prev&0xffff)>=(x>>16) ){
9738         checkAppendMsg(pCheck,
9739           "Multiple uses for byte %u of page %d", x>>16, iPage);
9740         break;
9741       }else{
9742         nFrag += (x>>16) - (prev&0xffff) - 1;
9743         prev = x;
9744       }
9745     }
9746     nFrag += usableSize - (prev&0xffff) - 1;
9747     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9748     ** is stored in the fifth field of the b-tree page header.
9749     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9750     ** number of fragmented free bytes within the cell content area.
9751     */
9752     if( heap[0]==0 && nFrag!=data[hdr+7] ){
9753       checkAppendMsg(pCheck,
9754           "Fragmentation of %d bytes reported as %d on page %d",
9755           nFrag, data[hdr+7], iPage);
9756     }
9757   }
9758 
9759 end_of_check:
9760   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
9761   releasePage(pPage);
9762   pCheck->zPfx = saved_zPfx;
9763   pCheck->v1 = saved_v1;
9764   pCheck->v2 = saved_v2;
9765   return depth+1;
9766 }
9767 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9768 
9769 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9770 /*
9771 ** This routine does a complete check of the given BTree file.  aRoot[] is
9772 ** an array of pages numbers were each page number is the root page of
9773 ** a table.  nRoot is the number of entries in aRoot.
9774 **
9775 ** A read-only or read-write transaction must be opened before calling
9776 ** this function.
9777 **
9778 ** Write the number of error seen in *pnErr.  Except for some memory
9779 ** allocation errors,  an error message held in memory obtained from
9780 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
9781 ** returned.  If a memory allocation error occurs, NULL is returned.
9782 */
9783 char *sqlite3BtreeIntegrityCheck(
9784   Btree *p,     /* The btree to be checked */
9785   int *aRoot,   /* An array of root pages numbers for individual trees */
9786   int nRoot,    /* Number of entries in aRoot[] */
9787   int mxErr,    /* Stop reporting errors after this many */
9788   int *pnErr    /* Write number of errors seen to this variable */
9789 ){
9790   Pgno i;
9791   IntegrityCk sCheck;
9792   BtShared *pBt = p->pBt;
9793   int savedDbFlags = pBt->db->flags;
9794   char zErr[100];
9795   VVA_ONLY( int nRef );
9796 
9797   sqlite3BtreeEnter(p);
9798   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
9799   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9800   assert( nRef>=0 );
9801   sCheck.pBt = pBt;
9802   sCheck.pPager = pBt->pPager;
9803   sCheck.nPage = btreePagecount(sCheck.pBt);
9804   sCheck.mxErr = mxErr;
9805   sCheck.nErr = 0;
9806   sCheck.mallocFailed = 0;
9807   sCheck.zPfx = 0;
9808   sCheck.v1 = 0;
9809   sCheck.v2 = 0;
9810   sCheck.aPgRef = 0;
9811   sCheck.heap = 0;
9812   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
9813   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
9814   if( sCheck.nPage==0 ){
9815     goto integrity_ck_cleanup;
9816   }
9817 
9818   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9819   if( !sCheck.aPgRef ){
9820     sCheck.mallocFailed = 1;
9821     goto integrity_ck_cleanup;
9822   }
9823   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9824   if( sCheck.heap==0 ){
9825     sCheck.mallocFailed = 1;
9826     goto integrity_ck_cleanup;
9827   }
9828 
9829   i = PENDING_BYTE_PAGE(pBt);
9830   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
9831 
9832   /* Check the integrity of the freelist
9833   */
9834   sCheck.zPfx = "Main freelist: ";
9835   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
9836             get4byte(&pBt->pPage1->aData[36]));
9837   sCheck.zPfx = 0;
9838 
9839   /* Check all the tables.
9840   */
9841   testcase( pBt->db->flags & SQLITE_CellSizeCk );
9842   pBt->db->flags &= ~SQLITE_CellSizeCk;
9843   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
9844     i64 notUsed;
9845     if( aRoot[i]==0 ) continue;
9846 #ifndef SQLITE_OMIT_AUTOVACUUM
9847     if( pBt->autoVacuum && aRoot[i]>1 ){
9848       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
9849     }
9850 #endif
9851     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
9852   }
9853   pBt->db->flags = savedDbFlags;
9854 
9855   /* Make sure every page in the file is referenced
9856   */
9857   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
9858 #ifdef SQLITE_OMIT_AUTOVACUUM
9859     if( getPageReferenced(&sCheck, i)==0 ){
9860       checkAppendMsg(&sCheck, "Page %d is never used", i);
9861     }
9862 #else
9863     /* If the database supports auto-vacuum, make sure no tables contain
9864     ** references to pointer-map pages.
9865     */
9866     if( getPageReferenced(&sCheck, i)==0 &&
9867        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
9868       checkAppendMsg(&sCheck, "Page %d is never used", i);
9869     }
9870     if( getPageReferenced(&sCheck, i)!=0 &&
9871        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
9872       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
9873     }
9874 #endif
9875   }
9876 
9877   /* Clean  up and report errors.
9878   */
9879 integrity_ck_cleanup:
9880   sqlite3PageFree(sCheck.heap);
9881   sqlite3_free(sCheck.aPgRef);
9882   if( sCheck.mallocFailed ){
9883     sqlite3_str_reset(&sCheck.errMsg);
9884     sCheck.nErr++;
9885   }
9886   *pnErr = sCheck.nErr;
9887   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
9888   /* Make sure this analysis did not leave any unref() pages. */
9889   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9890   sqlite3BtreeLeave(p);
9891   return sqlite3StrAccumFinish(&sCheck.errMsg);
9892 }
9893 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9894 
9895 /*
9896 ** Return the full pathname of the underlying database file.  Return
9897 ** an empty string if the database is in-memory or a TEMP database.
9898 **
9899 ** The pager filename is invariant as long as the pager is
9900 ** open so it is safe to access without the BtShared mutex.
9901 */
9902 const char *sqlite3BtreeGetFilename(Btree *p){
9903   assert( p->pBt->pPager!=0 );
9904   return sqlite3PagerFilename(p->pBt->pPager, 1);
9905 }
9906 
9907 /*
9908 ** Return the pathname of the journal file for this database. The return
9909 ** value of this routine is the same regardless of whether the journal file
9910 ** has been created or not.
9911 **
9912 ** The pager journal filename is invariant as long as the pager is
9913 ** open so it is safe to access without the BtShared mutex.
9914 */
9915 const char *sqlite3BtreeGetJournalname(Btree *p){
9916   assert( p->pBt->pPager!=0 );
9917   return sqlite3PagerJournalname(p->pBt->pPager);
9918 }
9919 
9920 /*
9921 ** Return non-zero if a transaction is active.
9922 */
9923 int sqlite3BtreeIsInTrans(Btree *p){
9924   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
9925   return (p && (p->inTrans==TRANS_WRITE));
9926 }
9927 
9928 #ifndef SQLITE_OMIT_WAL
9929 /*
9930 ** Run a checkpoint on the Btree passed as the first argument.
9931 **
9932 ** Return SQLITE_LOCKED if this or any other connection has an open
9933 ** transaction on the shared-cache the argument Btree is connected to.
9934 **
9935 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
9936 */
9937 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
9938   int rc = SQLITE_OK;
9939   if( p ){
9940     BtShared *pBt = p->pBt;
9941     sqlite3BtreeEnter(p);
9942     if( pBt->inTransaction!=TRANS_NONE ){
9943       rc = SQLITE_LOCKED;
9944     }else{
9945       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
9946     }
9947     sqlite3BtreeLeave(p);
9948   }
9949   return rc;
9950 }
9951 #endif
9952 
9953 /*
9954 ** Return non-zero if a read (or write) transaction is active.
9955 */
9956 int sqlite3BtreeIsInReadTrans(Btree *p){
9957   assert( p );
9958   assert( sqlite3_mutex_held(p->db->mutex) );
9959   return p->inTrans!=TRANS_NONE;
9960 }
9961 
9962 int sqlite3BtreeIsInBackup(Btree *p){
9963   assert( p );
9964   assert( sqlite3_mutex_held(p->db->mutex) );
9965   return p->nBackup!=0;
9966 }
9967 
9968 /*
9969 ** This function returns a pointer to a blob of memory associated with
9970 ** a single shared-btree. The memory is used by client code for its own
9971 ** purposes (for example, to store a high-level schema associated with
9972 ** the shared-btree). The btree layer manages reference counting issues.
9973 **
9974 ** The first time this is called on a shared-btree, nBytes bytes of memory
9975 ** are allocated, zeroed, and returned to the caller. For each subsequent
9976 ** call the nBytes parameter is ignored and a pointer to the same blob
9977 ** of memory returned.
9978 **
9979 ** If the nBytes parameter is 0 and the blob of memory has not yet been
9980 ** allocated, a null pointer is returned. If the blob has already been
9981 ** allocated, it is returned as normal.
9982 **
9983 ** Just before the shared-btree is closed, the function passed as the
9984 ** xFree argument when the memory allocation was made is invoked on the
9985 ** blob of allocated memory. The xFree function should not call sqlite3_free()
9986 ** on the memory, the btree layer does that.
9987 */
9988 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9989   BtShared *pBt = p->pBt;
9990   sqlite3BtreeEnter(p);
9991   if( !pBt->pSchema && nBytes ){
9992     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
9993     pBt->xFreeSchema = xFree;
9994   }
9995   sqlite3BtreeLeave(p);
9996   return pBt->pSchema;
9997 }
9998 
9999 /*
10000 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10001 ** btree as the argument handle holds an exclusive lock on the
10002 ** sqlite_master table. Otherwise SQLITE_OK.
10003 */
10004 int sqlite3BtreeSchemaLocked(Btree *p){
10005   int rc;
10006   assert( sqlite3_mutex_held(p->db->mutex) );
10007   sqlite3BtreeEnter(p);
10008   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
10009   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10010   sqlite3BtreeLeave(p);
10011   return rc;
10012 }
10013 
10014 
10015 #ifndef SQLITE_OMIT_SHARED_CACHE
10016 /*
10017 ** Obtain a lock on the table whose root page is iTab.  The
10018 ** lock is a write lock if isWritelock is true or a read lock
10019 ** if it is false.
10020 */
10021 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10022   int rc = SQLITE_OK;
10023   assert( p->inTrans!=TRANS_NONE );
10024   if( p->sharable ){
10025     u8 lockType = READ_LOCK + isWriteLock;
10026     assert( READ_LOCK+1==WRITE_LOCK );
10027     assert( isWriteLock==0 || isWriteLock==1 );
10028 
10029     sqlite3BtreeEnter(p);
10030     rc = querySharedCacheTableLock(p, iTab, lockType);
10031     if( rc==SQLITE_OK ){
10032       rc = setSharedCacheTableLock(p, iTab, lockType);
10033     }
10034     sqlite3BtreeLeave(p);
10035   }
10036   return rc;
10037 }
10038 #endif
10039 
10040 #ifndef SQLITE_OMIT_INCRBLOB
10041 /*
10042 ** Argument pCsr must be a cursor opened for writing on an
10043 ** INTKEY table currently pointing at a valid table entry.
10044 ** This function modifies the data stored as part of that entry.
10045 **
10046 ** Only the data content may only be modified, it is not possible to
10047 ** change the length of the data stored. If this function is called with
10048 ** parameters that attempt to write past the end of the existing data,
10049 ** no modifications are made and SQLITE_CORRUPT is returned.
10050 */
10051 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10052   int rc;
10053   assert( cursorOwnsBtShared(pCsr) );
10054   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10055   assert( pCsr->curFlags & BTCF_Incrblob );
10056 
10057   rc = restoreCursorPosition(pCsr);
10058   if( rc!=SQLITE_OK ){
10059     return rc;
10060   }
10061   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10062   if( pCsr->eState!=CURSOR_VALID ){
10063     return SQLITE_ABORT;
10064   }
10065 
10066   /* Save the positions of all other cursors open on this table. This is
10067   ** required in case any of them are holding references to an xFetch
10068   ** version of the b-tree page modified by the accessPayload call below.
10069   **
10070   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10071   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10072   ** saveAllCursors can only return SQLITE_OK.
10073   */
10074   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10075   assert( rc==SQLITE_OK );
10076 
10077   /* Check some assumptions:
10078   **   (a) the cursor is open for writing,
10079   **   (b) there is a read/write transaction open,
10080   **   (c) the connection holds a write-lock on the table (if required),
10081   **   (d) there are no conflicting read-locks, and
10082   **   (e) the cursor points at a valid row of an intKey table.
10083   */
10084   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10085     return SQLITE_READONLY;
10086   }
10087   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10088               && pCsr->pBt->inTransaction==TRANS_WRITE );
10089   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10090   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10091   assert( pCsr->pPage->intKey );
10092 
10093   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10094 }
10095 
10096 /*
10097 ** Mark this cursor as an incremental blob cursor.
10098 */
10099 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10100   pCur->curFlags |= BTCF_Incrblob;
10101   pCur->pBtree->hasIncrblobCur = 1;
10102 }
10103 #endif
10104 
10105 /*
10106 ** Set both the "read version" (single byte at byte offset 18) and
10107 ** "write version" (single byte at byte offset 19) fields in the database
10108 ** header to iVersion.
10109 */
10110 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10111   BtShared *pBt = pBtree->pBt;
10112   int rc;                         /* Return code */
10113 
10114   assert( iVersion==1 || iVersion==2 );
10115 
10116   /* If setting the version fields to 1, do not automatically open the
10117   ** WAL connection, even if the version fields are currently set to 2.
10118   */
10119   pBt->btsFlags &= ~BTS_NO_WAL;
10120   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10121 
10122   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10123   if( rc==SQLITE_OK ){
10124     u8 *aData = pBt->pPage1->aData;
10125     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10126       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10127       if( rc==SQLITE_OK ){
10128         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10129         if( rc==SQLITE_OK ){
10130           aData[18] = (u8)iVersion;
10131           aData[19] = (u8)iVersion;
10132         }
10133       }
10134     }
10135   }
10136 
10137   pBt->btsFlags &= ~BTS_NO_WAL;
10138   return rc;
10139 }
10140 
10141 /*
10142 ** Return true if the cursor has a hint specified.  This routine is
10143 ** only used from within assert() statements
10144 */
10145 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10146   return (pCsr->hints & mask)!=0;
10147 }
10148 
10149 /*
10150 ** Return true if the given Btree is read-only.
10151 */
10152 int sqlite3BtreeIsReadonly(Btree *p){
10153   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10154 }
10155 
10156 /*
10157 ** Return the size of the header added to each page by this module.
10158 */
10159 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10160 
10161 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10162 /*
10163 ** Return true if the Btree passed as the only argument is sharable.
10164 */
10165 int sqlite3BtreeSharable(Btree *p){
10166   return p->sharable;
10167 }
10168 
10169 /*
10170 ** Return the number of connections to the BtShared object accessed by
10171 ** the Btree handle passed as the only argument. For private caches
10172 ** this is always 1. For shared caches it may be 1 or greater.
10173 */
10174 int sqlite3BtreeConnectionCount(Btree *p){
10175   testcase( p->sharable );
10176   return p->pBt->nRef;
10177 }
10178 #endif
10179