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