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