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