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