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