xref: /sqlite-3.40.0/src/btree.c (revision 69871baa)
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_MAIN.
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 #ifdef SQLITE_DEBUG
116 /*
117 ** Return and reset the seek counter for a Btree object.
118 */
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120   u64 n =  pBt->nSeek;
121   pBt->nSeek = 0;
122   return n;
123 }
124 #endif
125 
126 /*
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
129 **
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
134 */
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137   char *zMsg;
138   sqlite3BeginBenignMalloc();
139   zMsg = sqlite3_mprintf("database corruption page %d of %s",
140       (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
141   );
142   sqlite3EndBenignMalloc();
143   if( zMsg ){
144     sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
145   }
146   sqlite3_free(zMsg);
147   return SQLITE_CORRUPT_BKPT;
148 }
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
153 
154 #ifndef SQLITE_OMIT_SHARED_CACHE
155 
156 #ifdef SQLITE_DEBUG
157 /*
158 **** This function is only used as part of an assert() statement. ***
159 **
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot.   Return 1 if it does and 0 if not.
162 **
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
165 **
166 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
167 **
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
174 **
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
178 */
179 static int hasSharedCacheTableLock(
180   Btree *pBtree,         /* Handle that must hold lock */
181   Pgno iRoot,            /* Root page of b-tree */
182   int isIndex,           /* True if iRoot is the root of an index b-tree */
183   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
184 ){
185   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186   Pgno iTab = 0;
187   BtLock *pLock;
188 
189   /* If this database is not shareable, or if the client is reading
190   ** and has the read-uncommitted flag set, then no lock is required.
191   ** Return true immediately.
192   */
193   if( (pBtree->sharable==0)
194    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
195   ){
196     return 1;
197   }
198 
199   /* If the client is reading  or writing an index and the schema is
200   ** not loaded, then it is too difficult to actually check to see if
201   ** the correct locks are held.  So do not bother - just return true.
202   ** This case does not come up very often anyhow.
203   */
204   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205     return 1;
206   }
207 
208   /* Figure out the root-page that the lock should be held on. For table
209   ** b-trees, this is just the root page of the b-tree being read or
210   ** written. For index b-trees, it is the root page of the associated
211   ** table.  */
212   if( isIndex ){
213     HashElem *p;
214     int bSeen = 0;
215     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216       Index *pIdx = (Index *)sqliteHashData(p);
217       if( pIdx->tnum==(int)iRoot ){
218         if( bSeen ){
219           /* Two or more indexes share the same root page.  There must
220           ** be imposter tables.  So just return true.  The assert is not
221           ** useful in that case. */
222           return 1;
223         }
224         iTab = pIdx->pTable->tnum;
225         bSeen = 1;
226       }
227     }
228   }else{
229     iTab = iRoot;
230   }
231 
232   /* Search for the required lock. Either a write-lock on root-page iTab, a
233   ** write-lock on the schema table, or (if the client is reading) a
234   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
235   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236     if( pLock->pBtree==pBtree
237      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238      && pLock->eLock>=eLockType
239     ){
240       return 1;
241     }
242   }
243 
244   /* Failed to find the required lock. */
245   return 0;
246 }
247 #endif /* SQLITE_DEBUG */
248 
249 #ifdef SQLITE_DEBUG
250 /*
251 **** This function may be used as part of assert() statements only. ****
252 **
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
256 **
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table.  Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
262 **
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
265 **
266 **    assert( !hasReadConflicts(pBtree, iRoot) );
267 */
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269   BtCursor *p;
270   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271     if( p->pgnoRoot==iRoot
272      && p->pBtree!=pBtree
273      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
274     ){
275       return 1;
276     }
277   }
278   return 0;
279 }
280 #endif    /* #ifdef SQLITE_DEBUG */
281 
282 /*
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
287 */
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289   BtShared *pBt = p->pBt;
290   BtLock *pIter;
291 
292   assert( sqlite3BtreeHoldsMutex(p) );
293   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294   assert( p->db!=0 );
295   assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
296 
297   /* If requesting a write-lock, then the Btree must have an open write
298   ** transaction on this file. And, obviously, for this to be so there
299   ** must be an open write transaction on the file itself.
300   */
301   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
303 
304   /* This routine is a no-op if the shared-cache is not enabled */
305   if( !p->sharable ){
306     return SQLITE_OK;
307   }
308 
309   /* If some other connection is holding an exclusive lock, the
310   ** requested lock may not be obtained.
311   */
312   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314     return SQLITE_LOCKED_SHAREDCACHE;
315   }
316 
317   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318     /* The condition (pIter->eLock!=eLock) in the following if(...)
319     ** statement is a simplification of:
320     **
321     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
322     **
323     ** since we know that if eLock==WRITE_LOCK, then no other connection
324     ** may hold a WRITE_LOCK on any table in this file (since there can
325     ** only be a single writer).
326     */
327     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331       if( eLock==WRITE_LOCK ){
332         assert( p==pBt->pWriter );
333         pBt->btsFlags |= BTS_PENDING;
334       }
335       return SQLITE_LOCKED_SHAREDCACHE;
336     }
337   }
338   return SQLITE_OK;
339 }
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
341 
342 #ifndef SQLITE_OMIT_SHARED_CACHE
343 /*
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
347 **
348 ** This function assumes the following:
349 **
350 **   (a) The specified Btree object p is connected to a sharable
351 **       database (one with the BtShared.sharable flag set), and
352 **
353 **   (b) No other Btree objects hold a lock that conflicts
354 **       with the requested lock (i.e. querySharedCacheTableLock() has
355 **       already been called and returned SQLITE_OK).
356 **
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
359 */
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361   BtShared *pBt = p->pBt;
362   BtLock *pLock = 0;
363   BtLock *pIter;
364 
365   assert( sqlite3BtreeHoldsMutex(p) );
366   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367   assert( p->db!=0 );
368 
369   /* A connection with the read-uncommitted flag set will never try to
370   ** obtain a read-lock using this function. The only read-lock obtained
371   ** by a connection in read-uncommitted mode is on the sqlite_schema
372   ** table, and that lock is obtained in BtreeBeginTrans().  */
373   assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
374 
375   /* This function should only be called on a sharable b-tree after it
376   ** has been determined that no other b-tree holds a conflicting lock.  */
377   assert( p->sharable );
378   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
379 
380   /* First search the list for an existing lock on this table. */
381   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382     if( pIter->iTable==iTable && pIter->pBtree==p ){
383       pLock = pIter;
384       break;
385     }
386   }
387 
388   /* If the above search did not find a BtLock struct associating Btree p
389   ** with table iTable, allocate one and link it into the list.
390   */
391   if( !pLock ){
392     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393     if( !pLock ){
394       return SQLITE_NOMEM_BKPT;
395     }
396     pLock->iTable = iTable;
397     pLock->pBtree = p;
398     pLock->pNext = pBt->pLock;
399     pBt->pLock = pLock;
400   }
401 
402   /* Set the BtLock.eLock variable to the maximum of the current lock
403   ** and the requested lock. This means if a write-lock was already held
404   ** and a read-lock requested, we don't incorrectly downgrade the lock.
405   */
406   assert( WRITE_LOCK>READ_LOCK );
407   if( eLock>pLock->eLock ){
408     pLock->eLock = eLock;
409   }
410 
411   return SQLITE_OK;
412 }
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
414 
415 #ifndef SQLITE_OMIT_SHARED_CACHE
416 /*
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
419 **
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
423 */
424 static void clearAllSharedCacheTableLocks(Btree *p){
425   BtShared *pBt = p->pBt;
426   BtLock **ppIter = &pBt->pLock;
427 
428   assert( sqlite3BtreeHoldsMutex(p) );
429   assert( p->sharable || 0==*ppIter );
430   assert( p->inTrans>0 );
431 
432   while( *ppIter ){
433     BtLock *pLock = *ppIter;
434     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435     assert( pLock->pBtree->inTrans>=pLock->eLock );
436     if( pLock->pBtree==p ){
437       *ppIter = pLock->pNext;
438       assert( pLock->iTable!=1 || pLock==&p->lock );
439       if( pLock->iTable!=1 ){
440         sqlite3_free(pLock);
441       }
442     }else{
443       ppIter = &pLock->pNext;
444     }
445   }
446 
447   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448   if( pBt->pWriter==p ){
449     pBt->pWriter = 0;
450     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451   }else if( pBt->nTransaction==2 ){
452     /* This function is called when Btree p is concluding its
453     ** transaction. If there currently exists a writer, and p is not
454     ** that writer, then the number of locks held by connections other
455     ** than the writer must be about to drop to zero. In this case
456     ** set the BTS_PENDING flag to 0.
457     **
458     ** If there is not currently a writer, then BTS_PENDING must
459     ** be zero already. So this next line is harmless in that case.
460     */
461     pBt->btsFlags &= ~BTS_PENDING;
462   }
463 }
464 
465 /*
466 ** This function changes all write-locks held by Btree p into read-locks.
467 */
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469   BtShared *pBt = p->pBt;
470   if( pBt->pWriter==p ){
471     BtLock *pLock;
472     pBt->pWriter = 0;
473     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476       pLock->eLock = READ_LOCK;
477     }
478   }
479 }
480 
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
482 
483 static void releasePage(MemPage *pPage);         /* Forward reference */
484 static void releasePageOne(MemPage *pPage);      /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
486 
487 /*
488 ***** This routine is used inside of assert() only ****
489 **
490 ** Verify that the cursor holds the mutex on its BtShared
491 */
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494   return sqlite3_mutex_held(p->pBt->mutex);
495 }
496 
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed.  This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
504 */
505 static int cursorOwnsBtShared(BtCursor *p){
506   assert( cursorHoldsMutex(p) );
507   return (p->pBtree->db==p->pBt->db);
508 }
509 #endif
510 
511 /*
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
514 */
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
516 
517 /*
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
520 */
521 static void invalidateAllOverflowCache(BtShared *pBt){
522   BtCursor *p;
523   assert( sqlite3_mutex_held(pBt->mutex) );
524   for(p=pBt->pCursor; p; p=p->pNext){
525     invalidateOverflowCache(p);
526   }
527 }
528 
529 #ifndef SQLITE_OMIT_INCRBLOB
530 /*
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
534 **
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
538 **
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
542 */
543 static void invalidateIncrblobCursors(
544   Btree *pBtree,          /* The database file to check */
545   Pgno pgnoRoot,          /* The table that might be changing */
546   i64 iRow,               /* The rowid that might be changing */
547   int isClearTable        /* True if all rows are being deleted */
548 ){
549   BtCursor *p;
550   if( pBtree->hasIncrblobCur==0 ) return;
551   assert( sqlite3BtreeHoldsMutex(pBtree) );
552   pBtree->hasIncrblobCur = 0;
553   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
554     if( (p->curFlags & BTCF_Incrblob)!=0 ){
555       pBtree->hasIncrblobCur = 1;
556       if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
557         p->eState = CURSOR_INVALID;
558       }
559     }
560   }
561 }
562 
563 #else
564   /* Stub function when INCRBLOB is omitted */
565   #define invalidateIncrblobCursors(w,x,y,z)
566 #endif /* SQLITE_OMIT_INCRBLOB */
567 
568 /*
569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
570 ** when a page that previously contained data becomes a free-list leaf
571 ** page.
572 **
573 ** The BtShared.pHasContent bitvec exists to work around an obscure
574 ** bug caused by the interaction of two useful IO optimizations surrounding
575 ** free-list leaf pages:
576 **
577 **   1) When all data is deleted from a page and the page becomes
578 **      a free-list leaf page, the page is not written to the database
579 **      (as free-list leaf pages contain no meaningful data). Sometimes
580 **      such a page is not even journalled (as it will not be modified,
581 **      why bother journalling it?).
582 **
583 **   2) When a free-list leaf page is reused, its content is not read
584 **      from the database or written to the journal file (why should it
585 **      be, if it is not at all meaningful?).
586 **
587 ** By themselves, these optimizations work fine and provide a handy
588 ** performance boost to bulk delete or insert operations. However, if
589 ** a page is moved to the free-list and then reused within the same
590 ** transaction, a problem comes up. If the page is not journalled when
591 ** it is moved to the free-list and it is also not journalled when it
592 ** is extracted from the free-list and reused, then the original data
593 ** may be lost. In the event of a rollback, it may not be possible
594 ** to restore the database to its original configuration.
595 **
596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
597 ** moved to become a free-list leaf page, the corresponding bit is
598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
599 ** optimization 2 above is omitted if the corresponding bit is already
600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
601 ** at the end of every transaction.
602 */
603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
604   int rc = SQLITE_OK;
605   if( !pBt->pHasContent ){
606     assert( pgno<=pBt->nPage );
607     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
608     if( !pBt->pHasContent ){
609       rc = SQLITE_NOMEM_BKPT;
610     }
611   }
612   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
613     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
614   }
615   return rc;
616 }
617 
618 /*
619 ** Query the BtShared.pHasContent vector.
620 **
621 ** This function is called when a free-list leaf page is removed from the
622 ** free-list for reuse. It returns false if it is safe to retrieve the
623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
624 */
625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
626   Bitvec *p = pBt->pHasContent;
627   return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
628 }
629 
630 /*
631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
632 ** invoked at the conclusion of each write-transaction.
633 */
634 static void btreeClearHasContent(BtShared *pBt){
635   sqlite3BitvecDestroy(pBt->pHasContent);
636   pBt->pHasContent = 0;
637 }
638 
639 /*
640 ** Release all of the apPage[] pages for a cursor.
641 */
642 static void btreeReleaseAllCursorPages(BtCursor *pCur){
643   int i;
644   if( pCur->iPage>=0 ){
645     for(i=0; i<pCur->iPage; i++){
646       releasePageNotNull(pCur->apPage[i]);
647     }
648     releasePageNotNull(pCur->pPage);
649     pCur->iPage = -1;
650   }
651 }
652 
653 /*
654 ** The cursor passed as the only argument must point to a valid entry
655 ** when this function is called (i.e. have eState==CURSOR_VALID). This
656 ** function saves the current cursor key in variables pCur->nKey and
657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
658 ** code otherwise.
659 **
660 ** If the cursor is open on an intkey table, then the integer key
661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
663 ** set to point to a malloced buffer pCur->nKey bytes in size containing
664 ** the key.
665 */
666 static int saveCursorKey(BtCursor *pCur){
667   int rc = SQLITE_OK;
668   assert( CURSOR_VALID==pCur->eState );
669   assert( 0==pCur->pKey );
670   assert( cursorHoldsMutex(pCur) );
671 
672   if( pCur->curIntKey ){
673     /* Only the rowid is required for a table btree */
674     pCur->nKey = sqlite3BtreeIntegerKey(pCur);
675   }else{
676     /* For an index btree, save the complete key content. It is possible
677     ** that the current key is corrupt. In that case, it is possible that
678     ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
679     ** up to the size of 1 varint plus 1 8-byte value when the cursor
680     ** position is restored. Hence the 17 bytes of padding allocated
681     ** below. */
682     void *pKey;
683     pCur->nKey = sqlite3BtreePayloadSize(pCur);
684     pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
685     if( pKey ){
686       rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
687       if( rc==SQLITE_OK ){
688         memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
689         pCur->pKey = pKey;
690       }else{
691         sqlite3_free(pKey);
692       }
693     }else{
694       rc = SQLITE_NOMEM_BKPT;
695     }
696   }
697   assert( !pCur->curIntKey || !pCur->pKey );
698   return rc;
699 }
700 
701 /*
702 ** Save the current cursor position in the variables BtCursor.nKey
703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
704 **
705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
706 ** prior to calling this routine.
707 */
708 static int saveCursorPosition(BtCursor *pCur){
709   int rc;
710 
711   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
712   assert( 0==pCur->pKey );
713   assert( cursorHoldsMutex(pCur) );
714 
715   if( pCur->curFlags & BTCF_Pinned ){
716     return SQLITE_CONSTRAINT_PINNED;
717   }
718   if( pCur->eState==CURSOR_SKIPNEXT ){
719     pCur->eState = CURSOR_VALID;
720   }else{
721     pCur->skipNext = 0;
722   }
723 
724   rc = saveCursorKey(pCur);
725   if( rc==SQLITE_OK ){
726     btreeReleaseAllCursorPages(pCur);
727     pCur->eState = CURSOR_REQUIRESEEK;
728   }
729 
730   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
731   return rc;
732 }
733 
734 /* Forward reference */
735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
736 
737 /*
738 ** Save the positions of all cursors (except pExcept) that are open on
739 ** the table with root-page iRoot.  "Saving the cursor position" means that
740 ** the location in the btree is remembered in such a way that it can be
741 ** moved back to the same spot after the btree has been modified.  This
742 ** routine is called just before cursor pExcept is used to modify the
743 ** table, for example in BtreeDelete() or BtreeInsert().
744 **
745 ** If there are two or more cursors on the same btree, then all such
746 ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
747 ** routine enforces that rule.  This routine only needs to be called in
748 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
749 **
750 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
752 ** pointless call to this routine.
753 **
754 ** Implementation note:  This routine merely checks to see if any cursors
755 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
756 ** event that cursors are in need to being saved.
757 */
758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
759   BtCursor *p;
760   assert( sqlite3_mutex_held(pBt->mutex) );
761   assert( pExcept==0 || pExcept->pBt==pBt );
762   for(p=pBt->pCursor; p; p=p->pNext){
763     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
764   }
765   if( p ) return saveCursorsOnList(p, iRoot, pExcept);
766   if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
767   return SQLITE_OK;
768 }
769 
770 /* This helper routine to saveAllCursors does the actual work of saving
771 ** the cursors if and when a cursor is found that actually requires saving.
772 ** The common case is that no cursors need to be saved, so this routine is
773 ** broken out from its caller to avoid unnecessary stack pointer movement.
774 */
775 static int SQLITE_NOINLINE saveCursorsOnList(
776   BtCursor *p,         /* The first cursor that needs saving */
777   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
778   BtCursor *pExcept    /* Do not save this cursor */
779 ){
780   do{
781     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
782       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
783         int rc = saveCursorPosition(p);
784         if( SQLITE_OK!=rc ){
785           return rc;
786         }
787       }else{
788         testcase( p->iPage>=0 );
789         btreeReleaseAllCursorPages(p);
790       }
791     }
792     p = p->pNext;
793   }while( p );
794   return SQLITE_OK;
795 }
796 
797 /*
798 ** Clear the current cursor position.
799 */
800 void sqlite3BtreeClearCursor(BtCursor *pCur){
801   assert( cursorHoldsMutex(pCur) );
802   sqlite3_free(pCur->pKey);
803   pCur->pKey = 0;
804   pCur->eState = CURSOR_INVALID;
805 }
806 
807 /*
808 ** In this version of BtreeMoveto, pKey is a packed index record
809 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
810 ** record and then call BtreeMovetoUnpacked() to do the work.
811 */
812 static int btreeMoveto(
813   BtCursor *pCur,     /* Cursor open on the btree to be searched */
814   const void *pKey,   /* Packed key if the btree is an index */
815   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
816   int bias,           /* Bias search to the high end */
817   int *pRes           /* Write search results here */
818 ){
819   int rc;                    /* Status code */
820   UnpackedRecord *pIdxKey;   /* Unpacked index key */
821 
822   if( pKey ){
823     KeyInfo *pKeyInfo = pCur->pKeyInfo;
824     assert( nKey==(i64)(int)nKey );
825     pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826     if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827     sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828     if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829       rc = SQLITE_CORRUPT_BKPT;
830       goto moveto_done;
831     }
832   }else{
833     pIdxKey = 0;
834   }
835   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
836 moveto_done:
837   if( pIdxKey ){
838     sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
839   }
840   return rc;
841 }
842 
843 /*
844 ** Restore the cursor to the position it was in (or as close to as possible)
845 ** when saveCursorPosition() was called. Note that this call deletes the
846 ** saved position info stored by saveCursorPosition(), so there can be
847 ** at most one effective restoreCursorPosition() call after each
848 ** saveCursorPosition().
849 */
850 static int btreeRestoreCursorPosition(BtCursor *pCur){
851   int rc;
852   int skipNext = 0;
853   assert( cursorOwnsBtShared(pCur) );
854   assert( pCur->eState>=CURSOR_REQUIRESEEK );
855   if( pCur->eState==CURSOR_FAULT ){
856     return pCur->skipNext;
857   }
858   pCur->eState = CURSOR_INVALID;
859   if( sqlite3FaultSim(410) ){
860     rc = SQLITE_IOERR;
861   }else{
862     rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
863   }
864   if( rc==SQLITE_OK ){
865     sqlite3_free(pCur->pKey);
866     pCur->pKey = 0;
867     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
868     if( skipNext ) pCur->skipNext = skipNext;
869     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
870       pCur->eState = CURSOR_SKIPNEXT;
871     }
872   }
873   return rc;
874 }
875 
876 #define restoreCursorPosition(p) \
877   (p->eState>=CURSOR_REQUIRESEEK ? \
878          btreeRestoreCursorPosition(p) : \
879          SQLITE_OK)
880 
881 /*
882 ** Determine whether or not a cursor has moved from the position where
883 ** it was last placed, or has been invalidated for any other reason.
884 ** Cursors can move when the row they are pointing at is deleted out
885 ** from under them, for example.  Cursor might also move if a btree
886 ** is rebalanced.
887 **
888 ** Calling this routine with a NULL cursor pointer returns false.
889 **
890 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
891 ** back to where it ought to be if this routine returns true.
892 */
893 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
894   assert( EIGHT_BYTE_ALIGNMENT(pCur)
895        || pCur==sqlite3BtreeFakeValidCursor() );
896   assert( offsetof(BtCursor, eState)==0 );
897   assert( sizeof(pCur->eState)==1 );
898   return CURSOR_VALID != *(u8*)pCur;
899 }
900 
901 /*
902 ** Return a pointer to a fake BtCursor object that will always answer
903 ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
904 ** cursor returned must not be used with any other Btree interface.
905 */
906 BtCursor *sqlite3BtreeFakeValidCursor(void){
907   static u8 fakeCursor = CURSOR_VALID;
908   assert( offsetof(BtCursor, eState)==0 );
909   return (BtCursor*)&fakeCursor;
910 }
911 
912 /*
913 ** This routine restores a cursor back to its original position after it
914 ** has been moved by some outside activity (such as a btree rebalance or
915 ** a row having been deleted out from under the cursor).
916 **
917 ** On success, the *pDifferentRow parameter is false if the cursor is left
918 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
919 ** was pointing to has been deleted, forcing the cursor to point to some
920 ** nearby row.
921 **
922 ** This routine should only be called for a cursor that just returned
923 ** TRUE from sqlite3BtreeCursorHasMoved().
924 */
925 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
926   int rc;
927 
928   assert( pCur!=0 );
929   assert( pCur->eState!=CURSOR_VALID );
930   rc = restoreCursorPosition(pCur);
931   if( rc ){
932     *pDifferentRow = 1;
933     return rc;
934   }
935   if( pCur->eState!=CURSOR_VALID ){
936     *pDifferentRow = 1;
937   }else{
938     *pDifferentRow = 0;
939   }
940   return SQLITE_OK;
941 }
942 
943 #ifdef SQLITE_ENABLE_CURSOR_HINTS
944 /*
945 ** Provide hints to the cursor.  The particular hint given (and the type
946 ** and number of the varargs parameters) is determined by the eHintType
947 ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
948 */
949 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
950   /* Used only by system that substitute their own storage engine */
951 }
952 #endif
953 
954 /*
955 ** Provide flag hints to the cursor.
956 */
957 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
958   assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
959   pCur->hints = x;
960 }
961 
962 
963 #ifndef SQLITE_OMIT_AUTOVACUUM
964 /*
965 ** Given a page number of a regular database page, return the page
966 ** number for the pointer-map page that contains the entry for the
967 ** input page number.
968 **
969 ** Return 0 (not a valid page) for pgno==1 since there is
970 ** no pointer map associated with page 1.  The integrity_check logic
971 ** requires that ptrmapPageno(*,1)!=1.
972 */
973 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
974   int nPagesPerMapPage;
975   Pgno iPtrMap, ret;
976   assert( sqlite3_mutex_held(pBt->mutex) );
977   if( pgno<2 ) return 0;
978   nPagesPerMapPage = (pBt->usableSize/5)+1;
979   iPtrMap = (pgno-2)/nPagesPerMapPage;
980   ret = (iPtrMap*nPagesPerMapPage) + 2;
981   if( ret==PENDING_BYTE_PAGE(pBt) ){
982     ret++;
983   }
984   return ret;
985 }
986 
987 /*
988 ** Write an entry into the pointer map.
989 **
990 ** This routine updates the pointer map entry for page number 'key'
991 ** so that it maps to type 'eType' and parent page number 'pgno'.
992 **
993 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
994 ** a no-op.  If an error occurs, the appropriate error code is written
995 ** into *pRC.
996 */
997 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
998   DbPage *pDbPage;  /* The pointer map page */
999   u8 *pPtrmap;      /* The pointer map data */
1000   Pgno iPtrmap;     /* The pointer map page number */
1001   int offset;       /* Offset in pointer map page */
1002   int rc;           /* Return code from subfunctions */
1003 
1004   if( *pRC ) return;
1005 
1006   assert( sqlite3_mutex_held(pBt->mutex) );
1007   /* The super-journal page number must never be used as a pointer map page */
1008   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1009 
1010   assert( pBt->autoVacuum );
1011   if( key==0 ){
1012     *pRC = SQLITE_CORRUPT_BKPT;
1013     return;
1014   }
1015   iPtrmap = PTRMAP_PAGENO(pBt, key);
1016   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1017   if( rc!=SQLITE_OK ){
1018     *pRC = rc;
1019     return;
1020   }
1021   if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1022     /* The first byte of the extra data is the MemPage.isInit byte.
1023     ** If that byte is set, it means this page is also being used
1024     ** as a btree page. */
1025     *pRC = SQLITE_CORRUPT_BKPT;
1026     goto ptrmap_exit;
1027   }
1028   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1029   if( offset<0 ){
1030     *pRC = SQLITE_CORRUPT_BKPT;
1031     goto ptrmap_exit;
1032   }
1033   assert( offset <= (int)pBt->usableSize-5 );
1034   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1035 
1036   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1037     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1038     *pRC= rc = sqlite3PagerWrite(pDbPage);
1039     if( rc==SQLITE_OK ){
1040       pPtrmap[offset] = eType;
1041       put4byte(&pPtrmap[offset+1], parent);
1042     }
1043   }
1044 
1045 ptrmap_exit:
1046   sqlite3PagerUnref(pDbPage);
1047 }
1048 
1049 /*
1050 ** Read an entry from the pointer map.
1051 **
1052 ** This routine retrieves the pointer map entry for page 'key', writing
1053 ** the type and parent page number to *pEType and *pPgno respectively.
1054 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1055 */
1056 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1057   DbPage *pDbPage;   /* The pointer map page */
1058   int iPtrmap;       /* Pointer map page index */
1059   u8 *pPtrmap;       /* Pointer map page data */
1060   int offset;        /* Offset of entry in pointer map */
1061   int rc;
1062 
1063   assert( sqlite3_mutex_held(pBt->mutex) );
1064 
1065   iPtrmap = PTRMAP_PAGENO(pBt, key);
1066   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1067   if( rc!=0 ){
1068     return rc;
1069   }
1070   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1071 
1072   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1073   if( offset<0 ){
1074     sqlite3PagerUnref(pDbPage);
1075     return SQLITE_CORRUPT_BKPT;
1076   }
1077   assert( offset <= (int)pBt->usableSize-5 );
1078   assert( pEType!=0 );
1079   *pEType = pPtrmap[offset];
1080   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1081 
1082   sqlite3PagerUnref(pDbPage);
1083   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1084   return SQLITE_OK;
1085 }
1086 
1087 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1088   #define ptrmapPut(w,x,y,z,rc)
1089   #define ptrmapGet(w,x,y,z) SQLITE_OK
1090   #define ptrmapPutOvflPtr(x, y, z, rc)
1091 #endif
1092 
1093 /*
1094 ** Given a btree page and a cell index (0 means the first cell on
1095 ** the page, 1 means the second cell, and so forth) return a pointer
1096 ** to the cell content.
1097 **
1098 ** findCellPastPtr() does the same except it skips past the initial
1099 ** 4-byte child pointer found on interior pages, if there is one.
1100 **
1101 ** This routine works only for pages that do not contain overflow cells.
1102 */
1103 #define findCell(P,I) \
1104   ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1105 #define findCellPastPtr(P,I) \
1106   ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1107 
1108 
1109 /*
1110 ** This is common tail processing for btreeParseCellPtr() and
1111 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1112 ** on a single B-tree page.  Make necessary adjustments to the CellInfo
1113 ** structure.
1114 */
1115 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1116   MemPage *pPage,         /* Page containing the cell */
1117   u8 *pCell,              /* Pointer to the cell text. */
1118   CellInfo *pInfo         /* Fill in this structure */
1119 ){
1120   /* If the payload will not fit completely on the local page, we have
1121   ** to decide how much to store locally and how much to spill onto
1122   ** overflow pages.  The strategy is to minimize the amount of unused
1123   ** space on overflow pages while keeping the amount of local storage
1124   ** in between minLocal and maxLocal.
1125   **
1126   ** Warning:  changing the way overflow payload is distributed in any
1127   ** way will result in an incompatible file format.
1128   */
1129   int minLocal;  /* Minimum amount of payload held locally */
1130   int maxLocal;  /* Maximum amount of payload held locally */
1131   int surplus;   /* Overflow payload available for local storage */
1132 
1133   minLocal = pPage->minLocal;
1134   maxLocal = pPage->maxLocal;
1135   surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1136   testcase( surplus==maxLocal );
1137   testcase( surplus==maxLocal+1 );
1138   if( surplus <= maxLocal ){
1139     pInfo->nLocal = (u16)surplus;
1140   }else{
1141     pInfo->nLocal = (u16)minLocal;
1142   }
1143   pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1144 }
1145 
1146 /*
1147 ** Given a record with nPayload bytes of payload stored within btree
1148 ** page pPage, return the number of bytes of payload stored locally.
1149 */
1150 static int btreePayloadToLocal(MemPage *pPage, int nPayload){
1151   int maxLocal;  /* Maximum amount of payload held locally */
1152   maxLocal = pPage->maxLocal;
1153   if( nPayload<=maxLocal ){
1154     return nPayload;
1155   }else{
1156     int minLocal;  /* Minimum amount of payload held locally */
1157     int surplus;   /* Overflow payload available for local storage */
1158     minLocal = pPage->minLocal;
1159     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1160     return ( surplus <= maxLocal ) ? surplus : minLocal;
1161   }
1162 }
1163 
1164 /*
1165 ** The following routines are implementations of the MemPage.xParseCell()
1166 ** method.
1167 **
1168 ** Parse a cell content block and fill in the CellInfo structure.
1169 **
1170 ** btreeParseCellPtr()        =>   table btree leaf nodes
1171 ** btreeParseCellNoPayload()  =>   table btree internal nodes
1172 ** btreeParseCellPtrIndex()   =>   index btree nodes
1173 **
1174 ** There is also a wrapper function btreeParseCell() that works for
1175 ** all MemPage types and that references the cell by index rather than
1176 ** by pointer.
1177 */
1178 static void btreeParseCellPtrNoPayload(
1179   MemPage *pPage,         /* Page containing the cell */
1180   u8 *pCell,              /* Pointer to the cell text. */
1181   CellInfo *pInfo         /* Fill in this structure */
1182 ){
1183   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1184   assert( pPage->leaf==0 );
1185   assert( pPage->childPtrSize==4 );
1186 #ifndef SQLITE_DEBUG
1187   UNUSED_PARAMETER(pPage);
1188 #endif
1189   pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1190   pInfo->nPayload = 0;
1191   pInfo->nLocal = 0;
1192   pInfo->pPayload = 0;
1193   return;
1194 }
1195 static void btreeParseCellPtr(
1196   MemPage *pPage,         /* Page containing the cell */
1197   u8 *pCell,              /* Pointer to the cell text. */
1198   CellInfo *pInfo         /* Fill in this structure */
1199 ){
1200   u8 *pIter;              /* For scanning through pCell */
1201   u32 nPayload;           /* Number of bytes of cell payload */
1202   u64 iKey;               /* Extracted Key value */
1203 
1204   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1205   assert( pPage->leaf==0 || pPage->leaf==1 );
1206   assert( pPage->intKeyLeaf );
1207   assert( pPage->childPtrSize==0 );
1208   pIter = pCell;
1209 
1210   /* The next block of code is equivalent to:
1211   **
1212   **     pIter += getVarint32(pIter, nPayload);
1213   **
1214   ** The code is inlined to avoid a function call.
1215   */
1216   nPayload = *pIter;
1217   if( nPayload>=0x80 ){
1218     u8 *pEnd = &pIter[8];
1219     nPayload &= 0x7f;
1220     do{
1221       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1222     }while( (*pIter)>=0x80 && pIter<pEnd );
1223   }
1224   pIter++;
1225 
1226   /* The next block of code is equivalent to:
1227   **
1228   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1229   **
1230   ** The code is inlined to avoid a function call.
1231   */
1232   iKey = *pIter;
1233   if( iKey>=0x80 ){
1234     u8 *pEnd = &pIter[7];
1235     iKey &= 0x7f;
1236     while(1){
1237       iKey = (iKey<<7) | (*++pIter & 0x7f);
1238       if( (*pIter)<0x80 ) break;
1239       if( pIter>=pEnd ){
1240         iKey = (iKey<<8) | *++pIter;
1241         break;
1242       }
1243     }
1244   }
1245   pIter++;
1246 
1247   pInfo->nKey = *(i64*)&iKey;
1248   pInfo->nPayload = nPayload;
1249   pInfo->pPayload = pIter;
1250   testcase( nPayload==pPage->maxLocal );
1251   testcase( nPayload==pPage->maxLocal+1 );
1252   if( nPayload<=pPage->maxLocal ){
1253     /* This is the (easy) common case where the entire payload fits
1254     ** on the local page.  No overflow is required.
1255     */
1256     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1257     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1258     pInfo->nLocal = (u16)nPayload;
1259   }else{
1260     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1261   }
1262 }
1263 static void btreeParseCellPtrIndex(
1264   MemPage *pPage,         /* Page containing the cell */
1265   u8 *pCell,              /* Pointer to the cell text. */
1266   CellInfo *pInfo         /* Fill in this structure */
1267 ){
1268   u8 *pIter;              /* For scanning through pCell */
1269   u32 nPayload;           /* Number of bytes of cell payload */
1270 
1271   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1272   assert( pPage->leaf==0 || pPage->leaf==1 );
1273   assert( pPage->intKeyLeaf==0 );
1274   pIter = pCell + pPage->childPtrSize;
1275   nPayload = *pIter;
1276   if( nPayload>=0x80 ){
1277     u8 *pEnd = &pIter[8];
1278     nPayload &= 0x7f;
1279     do{
1280       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1281     }while( *(pIter)>=0x80 && pIter<pEnd );
1282   }
1283   pIter++;
1284   pInfo->nKey = nPayload;
1285   pInfo->nPayload = nPayload;
1286   pInfo->pPayload = pIter;
1287   testcase( nPayload==pPage->maxLocal );
1288   testcase( nPayload==pPage->maxLocal+1 );
1289   if( nPayload<=pPage->maxLocal ){
1290     /* This is the (easy) common case where the entire payload fits
1291     ** on the local page.  No overflow is required.
1292     */
1293     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1294     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1295     pInfo->nLocal = (u16)nPayload;
1296   }else{
1297     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1298   }
1299 }
1300 static void btreeParseCell(
1301   MemPage *pPage,         /* Page containing the cell */
1302   int iCell,              /* The cell index.  First cell is 0 */
1303   CellInfo *pInfo         /* Fill in this structure */
1304 ){
1305   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1306 }
1307 
1308 /*
1309 ** The following routines are implementations of the MemPage.xCellSize
1310 ** method.
1311 **
1312 ** Compute the total number of bytes that a Cell needs in the cell
1313 ** data area of the btree-page.  The return number includes the cell
1314 ** data header and the local payload, but not any overflow page or
1315 ** the space used by the cell pointer.
1316 **
1317 ** cellSizePtrNoPayload()    =>   table internal nodes
1318 ** cellSizePtr()             =>   all index nodes & table leaf nodes
1319 */
1320 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1321   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1322   u8 *pEnd;                                /* End mark for a varint */
1323   u32 nSize;                               /* Size value to return */
1324 
1325 #ifdef SQLITE_DEBUG
1326   /* The value returned by this function should always be the same as
1327   ** the (CellInfo.nSize) value found by doing a full parse of the
1328   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1329   ** this function verifies that this invariant is not violated. */
1330   CellInfo debuginfo;
1331   pPage->xParseCell(pPage, pCell, &debuginfo);
1332 #endif
1333 
1334   nSize = *pIter;
1335   if( nSize>=0x80 ){
1336     pEnd = &pIter[8];
1337     nSize &= 0x7f;
1338     do{
1339       nSize = (nSize<<7) | (*++pIter & 0x7f);
1340     }while( *(pIter)>=0x80 && pIter<pEnd );
1341   }
1342   pIter++;
1343   if( pPage->intKey ){
1344     /* pIter now points at the 64-bit integer key value, a variable length
1345     ** integer. The following block moves pIter to point at the first byte
1346     ** past the end of the key value. */
1347     pEnd = &pIter[9];
1348     while( (*pIter++)&0x80 && pIter<pEnd );
1349   }
1350   testcase( nSize==pPage->maxLocal );
1351   testcase( nSize==pPage->maxLocal+1 );
1352   if( nSize<=pPage->maxLocal ){
1353     nSize += (u32)(pIter - pCell);
1354     if( nSize<4 ) nSize = 4;
1355   }else{
1356     int minLocal = pPage->minLocal;
1357     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1358     testcase( nSize==pPage->maxLocal );
1359     testcase( nSize==pPage->maxLocal+1 );
1360     if( nSize>pPage->maxLocal ){
1361       nSize = minLocal;
1362     }
1363     nSize += 4 + (u16)(pIter - pCell);
1364   }
1365   assert( nSize==debuginfo.nSize || CORRUPT_DB );
1366   return (u16)nSize;
1367 }
1368 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1369   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1370   u8 *pEnd;              /* End mark for a varint */
1371 
1372 #ifdef SQLITE_DEBUG
1373   /* The value returned by this function should always be the same as
1374   ** the (CellInfo.nSize) value found by doing a full parse of the
1375   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1376   ** this function verifies that this invariant is not violated. */
1377   CellInfo debuginfo;
1378   pPage->xParseCell(pPage, pCell, &debuginfo);
1379 #else
1380   UNUSED_PARAMETER(pPage);
1381 #endif
1382 
1383   assert( pPage->childPtrSize==4 );
1384   pEnd = pIter + 9;
1385   while( (*pIter++)&0x80 && pIter<pEnd );
1386   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1387   return (u16)(pIter - pCell);
1388 }
1389 
1390 
1391 #ifdef SQLITE_DEBUG
1392 /* This variation on cellSizePtr() is used inside of assert() statements
1393 ** only. */
1394 static u16 cellSize(MemPage *pPage, int iCell){
1395   return pPage->xCellSize(pPage, findCell(pPage, iCell));
1396 }
1397 #endif
1398 
1399 #ifndef SQLITE_OMIT_AUTOVACUUM
1400 /*
1401 ** The cell pCell is currently part of page pSrc but will ultimately be part
1402 ** of pPage.  (pSrc and pPager are often the same.)  If pCell contains a
1403 ** pointer to an overflow page, insert an entry into the pointer-map for
1404 ** the overflow page that will be valid after pCell has been moved to pPage.
1405 */
1406 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1407   CellInfo info;
1408   if( *pRC ) return;
1409   assert( pCell!=0 );
1410   pPage->xParseCell(pPage, pCell, &info);
1411   if( info.nLocal<info.nPayload ){
1412     Pgno ovfl;
1413     if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1414       testcase( pSrc!=pPage );
1415       *pRC = SQLITE_CORRUPT_BKPT;
1416       return;
1417     }
1418     ovfl = get4byte(&pCell[info.nSize-4]);
1419     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1420   }
1421 }
1422 #endif
1423 
1424 
1425 /*
1426 ** Defragment the page given. This routine reorganizes cells within the
1427 ** page so that there are no free-blocks on the free-block list.
1428 **
1429 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1430 ** present in the page after this routine returns.
1431 **
1432 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1433 ** b-tree page so that there are no freeblocks or fragment bytes, all
1434 ** unused bytes are contained in the unallocated space region, and all
1435 ** cells are packed tightly at the end of the page.
1436 */
1437 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1438   int i;                     /* Loop counter */
1439   int pc;                    /* Address of the i-th cell */
1440   int hdr;                   /* Offset to the page header */
1441   int size;                  /* Size of a cell */
1442   int usableSize;            /* Number of usable bytes on a page */
1443   int cellOffset;            /* Offset to the cell pointer array */
1444   int cbrk;                  /* Offset to the cell content area */
1445   int nCell;                 /* Number of cells on the page */
1446   unsigned char *data;       /* The page data */
1447   unsigned char *temp;       /* Temp area for cell content */
1448   unsigned char *src;        /* Source of content */
1449   int iCellFirst;            /* First allowable cell index */
1450   int iCellLast;             /* Last possible cell index */
1451 
1452   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1453   assert( pPage->pBt!=0 );
1454   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1455   assert( pPage->nOverflow==0 );
1456   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1457   temp = 0;
1458   src = data = pPage->aData;
1459   hdr = pPage->hdrOffset;
1460   cellOffset = pPage->cellOffset;
1461   nCell = pPage->nCell;
1462   assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1463   iCellFirst = cellOffset + 2*nCell;
1464   usableSize = pPage->pBt->usableSize;
1465 
1466   /* This block handles pages with two or fewer free blocks and nMaxFrag
1467   ** or fewer fragmented bytes. In this case it is faster to move the
1468   ** two (or one) blocks of cells using memmove() and add the required
1469   ** offsets to each pointer in the cell-pointer array than it is to
1470   ** reconstruct the entire page.  */
1471   if( (int)data[hdr+7]<=nMaxFrag ){
1472     int iFree = get2byte(&data[hdr+1]);
1473     if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1474     if( iFree ){
1475       int iFree2 = get2byte(&data[iFree]);
1476       if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1477       if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1478         u8 *pEnd = &data[cellOffset + nCell*2];
1479         u8 *pAddr;
1480         int sz2 = 0;
1481         int sz = get2byte(&data[iFree+2]);
1482         int top = get2byte(&data[hdr+5]);
1483         if( top>=iFree ){
1484           return SQLITE_CORRUPT_PAGE(pPage);
1485         }
1486         if( iFree2 ){
1487           if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1488           sz2 = get2byte(&data[iFree2+2]);
1489           if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1490           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1491           sz += sz2;
1492         }else if( NEVER(iFree+sz>usableSize) ){
1493           return SQLITE_CORRUPT_PAGE(pPage);
1494         }
1495 
1496         cbrk = top+sz;
1497         assert( cbrk+(iFree-top) <= usableSize );
1498         memmove(&data[cbrk], &data[top], iFree-top);
1499         for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1500           pc = get2byte(pAddr);
1501           if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1502           else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1503         }
1504         goto defragment_out;
1505       }
1506     }
1507   }
1508 
1509   cbrk = usableSize;
1510   iCellLast = usableSize - 4;
1511   for(i=0; i<nCell; i++){
1512     u8 *pAddr;     /* The i-th cell pointer */
1513     pAddr = &data[cellOffset + i*2];
1514     pc = get2byte(pAddr);
1515     testcase( pc==iCellFirst );
1516     testcase( pc==iCellLast );
1517     /* These conditions have already been verified in btreeInitPage()
1518     ** if PRAGMA cell_size_check=ON.
1519     */
1520     if( pc<iCellFirst || pc>iCellLast ){
1521       return SQLITE_CORRUPT_PAGE(pPage);
1522     }
1523     assert( pc>=iCellFirst && pc<=iCellLast );
1524     size = pPage->xCellSize(pPage, &src[pc]);
1525     cbrk -= size;
1526     if( cbrk<iCellFirst || pc+size>usableSize ){
1527       return SQLITE_CORRUPT_PAGE(pPage);
1528     }
1529     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
1530     testcase( cbrk+size==usableSize );
1531     testcase( pc+size==usableSize );
1532     put2byte(pAddr, cbrk);
1533     if( temp==0 ){
1534       int x;
1535       if( cbrk==pc ) continue;
1536       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1537       x = get2byte(&data[hdr+5]);
1538       memcpy(&temp[x], &data[x], (cbrk+size) - x);
1539       src = temp;
1540     }
1541     memcpy(&data[cbrk], &src[pc], size);
1542   }
1543   data[hdr+7] = 0;
1544 
1545  defragment_out:
1546   assert( pPage->nFree>=0 );
1547   if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1548     return SQLITE_CORRUPT_PAGE(pPage);
1549   }
1550   assert( cbrk>=iCellFirst );
1551   put2byte(&data[hdr+5], cbrk);
1552   data[hdr+1] = 0;
1553   data[hdr+2] = 0;
1554   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1555   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1556   return SQLITE_OK;
1557 }
1558 
1559 /*
1560 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1561 ** size. If one can be found, return a pointer to the space and remove it
1562 ** from the free-list.
1563 **
1564 ** If no suitable space can be found on the free-list, return NULL.
1565 **
1566 ** This function may detect corruption within pPg.  If corruption is
1567 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1568 **
1569 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1570 ** will be ignored if adding the extra space to the fragmentation count
1571 ** causes the fragmentation count to exceed 60.
1572 */
1573 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1574   const int hdr = pPg->hdrOffset;            /* Offset to page header */
1575   u8 * const aData = pPg->aData;             /* Page data */
1576   int iAddr = hdr + 1;                       /* Address of ptr to pc */
1577   int pc = get2byte(&aData[iAddr]);          /* Address of a free slot */
1578   int x;                                     /* Excess size of the slot */
1579   int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */
1580   int size;                                  /* Size of the free slot */
1581 
1582   assert( pc>0 );
1583   while( pc<=maxPC ){
1584     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1585     ** freeblock form a big-endian integer which is the size of the freeblock
1586     ** in bytes, including the 4-byte header. */
1587     size = get2byte(&aData[pc+2]);
1588     if( (x = size - nByte)>=0 ){
1589       testcase( x==4 );
1590       testcase( x==3 );
1591       if( x<4 ){
1592         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1593         ** number of bytes in fragments may not exceed 60. */
1594         if( aData[hdr+7]>57 ) return 0;
1595 
1596         /* Remove the slot from the free-list. Update the number of
1597         ** fragmented bytes within the page. */
1598         memcpy(&aData[iAddr], &aData[pc], 2);
1599         aData[hdr+7] += (u8)x;
1600       }else if( x+pc > maxPC ){
1601         /* This slot extends off the end of the usable part of the page */
1602         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1603         return 0;
1604       }else{
1605         /* The slot remains on the free-list. Reduce its size to account
1606         ** for the portion used by the new allocation. */
1607         put2byte(&aData[pc+2], x);
1608       }
1609       return &aData[pc + x];
1610     }
1611     iAddr = pc;
1612     pc = get2byte(&aData[pc]);
1613     if( pc<=iAddr+size ){
1614       if( pc ){
1615         /* The next slot in the chain is not past the end of the current slot */
1616         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1617       }
1618       return 0;
1619     }
1620   }
1621   if( pc>maxPC+nByte-4 ){
1622     /* The free slot chain extends off the end of the page */
1623     *pRc = SQLITE_CORRUPT_PAGE(pPg);
1624   }
1625   return 0;
1626 }
1627 
1628 /*
1629 ** Allocate nByte bytes of space from within the B-Tree page passed
1630 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1631 ** of the first byte of allocated space. Return either SQLITE_OK or
1632 ** an error code (usually SQLITE_CORRUPT).
1633 **
1634 ** The caller guarantees that there is sufficient space to make the
1635 ** allocation.  This routine might need to defragment in order to bring
1636 ** all the space together, however.  This routine will avoid using
1637 ** the first two bytes past the cell pointer area since presumably this
1638 ** allocation is being made in order to insert a new cell, so we will
1639 ** also end up needing a new cell pointer.
1640 */
1641 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1642   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
1643   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
1644   int top;                             /* First byte of cell content area */
1645   int rc = SQLITE_OK;                  /* Integer return code */
1646   int gap;        /* First byte of gap between cell pointers and cell content */
1647 
1648   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1649   assert( pPage->pBt );
1650   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1651   assert( nByte>=0 );  /* Minimum cell size is 4 */
1652   assert( pPage->nFree>=nByte );
1653   assert( pPage->nOverflow==0 );
1654   assert( nByte < (int)(pPage->pBt->usableSize-8) );
1655 
1656   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1657   gap = pPage->cellOffset + 2*pPage->nCell;
1658   assert( gap<=65536 );
1659   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1660   ** and the reserved space is zero (the usual value for reserved space)
1661   ** then the cell content offset of an empty page wants to be 65536.
1662   ** However, that integer is too large to be stored in a 2-byte unsigned
1663   ** integer, so a value of 0 is used in its place. */
1664   top = get2byte(&data[hdr+5]);
1665   assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1666   if( gap>top ){
1667     if( top==0 && pPage->pBt->usableSize==65536 ){
1668       top = 65536;
1669     }else{
1670       return SQLITE_CORRUPT_PAGE(pPage);
1671     }
1672   }
1673 
1674   /* If there is enough space between gap and top for one more cell pointer,
1675   ** and if the freelist is not empty, then search the
1676   ** freelist looking for a slot big enough to satisfy the request.
1677   */
1678   testcase( gap+2==top );
1679   testcase( gap+1==top );
1680   testcase( gap==top );
1681   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1682     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1683     if( pSpace ){
1684       int g2;
1685       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1686       *pIdx = g2 = (int)(pSpace-data);
1687       if( NEVER(g2<=gap) ){
1688         return SQLITE_CORRUPT_PAGE(pPage);
1689       }else{
1690         return SQLITE_OK;
1691       }
1692     }else if( rc ){
1693       return rc;
1694     }
1695   }
1696 
1697   /* The request could not be fulfilled using a freelist slot.  Check
1698   ** to see if defragmentation is necessary.
1699   */
1700   testcase( gap+2+nByte==top );
1701   if( gap+2+nByte>top ){
1702     assert( pPage->nCell>0 || CORRUPT_DB );
1703     assert( pPage->nFree>=0 );
1704     rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1705     if( rc ) return rc;
1706     top = get2byteNotZero(&data[hdr+5]);
1707     assert( gap+2+nByte<=top );
1708   }
1709 
1710 
1711   /* Allocate memory from the gap in between the cell pointer array
1712   ** and the cell content area.  The btreeComputeFreeSpace() call has already
1713   ** validated the freelist.  Given that the freelist is valid, there
1714   ** is no way that the allocation can extend off the end of the page.
1715   ** The assert() below verifies the previous sentence.
1716   */
1717   top -= nByte;
1718   put2byte(&data[hdr+5], top);
1719   assert( top+nByte <= (int)pPage->pBt->usableSize );
1720   *pIdx = top;
1721   return SQLITE_OK;
1722 }
1723 
1724 /*
1725 ** Return a section of the pPage->aData to the freelist.
1726 ** The first byte of the new free block is pPage->aData[iStart]
1727 ** and the size of the block is iSize bytes.
1728 **
1729 ** Adjacent freeblocks are coalesced.
1730 **
1731 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1732 ** that routine will not detect overlap between cells or freeblocks.  Nor
1733 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1734 ** at the end of the page.  So do additional corruption checks inside this
1735 ** routine and return SQLITE_CORRUPT if any problems are found.
1736 */
1737 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1738   u16 iPtr;                             /* Address of ptr to next freeblock */
1739   u16 iFreeBlk;                         /* Address of the next freeblock */
1740   u8 hdr;                               /* Page header size.  0 or 100 */
1741   u8 nFrag = 0;                         /* Reduction in fragmentation */
1742   u16 iOrigSize = iSize;                /* Original value of iSize */
1743   u16 x;                                /* Offset to cell content area */
1744   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
1745   unsigned char *data = pPage->aData;   /* Page content */
1746 
1747   assert( pPage->pBt!=0 );
1748   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1749   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1750   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1751   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1752   assert( iSize>=4 );   /* Minimum cell size is 4 */
1753   assert( iStart<=pPage->pBt->usableSize-4 );
1754 
1755   /* The list of freeblocks must be in ascending order.  Find the
1756   ** spot on the list where iStart should be inserted.
1757   */
1758   hdr = pPage->hdrOffset;
1759   iPtr = hdr + 1;
1760   if( data[iPtr+1]==0 && data[iPtr]==0 ){
1761     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
1762   }else{
1763     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1764       if( iFreeBlk<iPtr+4 ){
1765         if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1766         return SQLITE_CORRUPT_PAGE(pPage);
1767       }
1768       iPtr = iFreeBlk;
1769     }
1770     if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1771       return SQLITE_CORRUPT_PAGE(pPage);
1772     }
1773     assert( iFreeBlk>iPtr || iFreeBlk==0 );
1774 
1775     /* At this point:
1776     **    iFreeBlk:   First freeblock after iStart, or zero if none
1777     **    iPtr:       The address of a pointer to iFreeBlk
1778     **
1779     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1780     */
1781     if( iFreeBlk && iEnd+3>=iFreeBlk ){
1782       nFrag = iFreeBlk - iEnd;
1783       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1784       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1785       if( iEnd > pPage->pBt->usableSize ){
1786         return SQLITE_CORRUPT_PAGE(pPage);
1787       }
1788       iSize = iEnd - iStart;
1789       iFreeBlk = get2byte(&data[iFreeBlk]);
1790     }
1791 
1792     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1793     ** pointer in the page header) then check to see if iStart should be
1794     ** coalesced onto the end of iPtr.
1795     */
1796     if( iPtr>hdr+1 ){
1797       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1798       if( iPtrEnd+3>=iStart ){
1799         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1800         nFrag += iStart - iPtrEnd;
1801         iSize = iEnd - iPtr;
1802         iStart = iPtr;
1803       }
1804     }
1805     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1806     data[hdr+7] -= nFrag;
1807   }
1808   x = get2byte(&data[hdr+5]);
1809   if( iStart<=x ){
1810     /* The new freeblock is at the beginning of the cell content area,
1811     ** so just extend the cell content area rather than create another
1812     ** freelist entry */
1813     if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1814     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1815     put2byte(&data[hdr+1], iFreeBlk);
1816     put2byte(&data[hdr+5], iEnd);
1817   }else{
1818     /* Insert the new freeblock into the freelist */
1819     put2byte(&data[iPtr], iStart);
1820   }
1821   if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1822     /* Overwrite deleted information with zeros when the secure_delete
1823     ** option is enabled */
1824     memset(&data[iStart], 0, iSize);
1825   }
1826   put2byte(&data[iStart], iFreeBlk);
1827   put2byte(&data[iStart+2], iSize);
1828   pPage->nFree += iOrigSize;
1829   return SQLITE_OK;
1830 }
1831 
1832 /*
1833 ** Decode the flags byte (the first byte of the header) for a page
1834 ** and initialize fields of the MemPage structure accordingly.
1835 **
1836 ** Only the following combinations are supported.  Anything different
1837 ** indicates a corrupt database files:
1838 **
1839 **         PTF_ZERODATA
1840 **         PTF_ZERODATA | PTF_LEAF
1841 **         PTF_LEAFDATA | PTF_INTKEY
1842 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1843 */
1844 static int decodeFlags(MemPage *pPage, int flagByte){
1845   BtShared *pBt;     /* A copy of pPage->pBt */
1846 
1847   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1848   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1849   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
1850   flagByte &= ~PTF_LEAF;
1851   pPage->childPtrSize = 4-4*pPage->leaf;
1852   pPage->xCellSize = cellSizePtr;
1853   pBt = pPage->pBt;
1854   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1855     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1856     ** interior table b-tree page. */
1857     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1858     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1859     ** leaf table b-tree page. */
1860     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1861     pPage->intKey = 1;
1862     if( pPage->leaf ){
1863       pPage->intKeyLeaf = 1;
1864       pPage->xParseCell = btreeParseCellPtr;
1865     }else{
1866       pPage->intKeyLeaf = 0;
1867       pPage->xCellSize = cellSizePtrNoPayload;
1868       pPage->xParseCell = btreeParseCellPtrNoPayload;
1869     }
1870     pPage->maxLocal = pBt->maxLeaf;
1871     pPage->minLocal = pBt->minLeaf;
1872   }else if( flagByte==PTF_ZERODATA ){
1873     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1874     ** interior index b-tree page. */
1875     assert( (PTF_ZERODATA)==2 );
1876     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1877     ** leaf index b-tree page. */
1878     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1879     pPage->intKey = 0;
1880     pPage->intKeyLeaf = 0;
1881     pPage->xParseCell = btreeParseCellPtrIndex;
1882     pPage->maxLocal = pBt->maxLocal;
1883     pPage->minLocal = pBt->minLocal;
1884   }else{
1885     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1886     ** an error. */
1887     return SQLITE_CORRUPT_PAGE(pPage);
1888   }
1889   pPage->max1bytePayload = pBt->max1bytePayload;
1890   return SQLITE_OK;
1891 }
1892 
1893 /*
1894 ** Compute the amount of freespace on the page.  In other words, fill
1895 ** in the pPage->nFree field.
1896 */
1897 static int btreeComputeFreeSpace(MemPage *pPage){
1898   int pc;            /* Address of a freeblock within pPage->aData[] */
1899   u8 hdr;            /* Offset to beginning of page header */
1900   u8 *data;          /* Equal to pPage->aData */
1901   int usableSize;    /* Amount of usable space on each page */
1902   int nFree;         /* Number of unused bytes on the page */
1903   int top;           /* First byte of the cell content area */
1904   int iCellFirst;    /* First allowable cell or freeblock offset */
1905   int iCellLast;     /* Last possible cell or freeblock offset */
1906 
1907   assert( pPage->pBt!=0 );
1908   assert( pPage->pBt->db!=0 );
1909   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1910   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1911   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1912   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1913   assert( pPage->isInit==1 );
1914   assert( pPage->nFree<0 );
1915 
1916   usableSize = pPage->pBt->usableSize;
1917   hdr = pPage->hdrOffset;
1918   data = pPage->aData;
1919   /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1920   ** the start of the cell content area. A zero value for this integer is
1921   ** interpreted as 65536. */
1922   top = get2byteNotZero(&data[hdr+5]);
1923   iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1924   iCellLast = usableSize - 4;
1925 
1926   /* Compute the total free space on the page
1927   ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1928   ** start of the first freeblock on the page, or is zero if there are no
1929   ** freeblocks. */
1930   pc = get2byte(&data[hdr+1]);
1931   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
1932   if( pc>0 ){
1933     u32 next, size;
1934     if( pc<top ){
1935       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1936       ** always be at least one cell before the first freeblock.
1937       */
1938       return SQLITE_CORRUPT_PAGE(pPage);
1939     }
1940     while( 1 ){
1941       if( pc>iCellLast ){
1942         /* Freeblock off the end of the page */
1943         return SQLITE_CORRUPT_PAGE(pPage);
1944       }
1945       next = get2byte(&data[pc]);
1946       size = get2byte(&data[pc+2]);
1947       nFree = nFree + size;
1948       if( next<=pc+size+3 ) break;
1949       pc = next;
1950     }
1951     if( next>0 ){
1952       /* Freeblock not in ascending order */
1953       return SQLITE_CORRUPT_PAGE(pPage);
1954     }
1955     if( pc+size>(unsigned int)usableSize ){
1956       /* Last freeblock extends past page end */
1957       return SQLITE_CORRUPT_PAGE(pPage);
1958     }
1959   }
1960 
1961   /* At this point, nFree contains the sum of the offset to the start
1962   ** of the cell-content area plus the number of free bytes within
1963   ** the cell-content area. If this is greater than the usable-size
1964   ** of the page, then the page must be corrupted. This check also
1965   ** serves to verify that the offset to the start of the cell-content
1966   ** area, according to the page header, lies within the page.
1967   */
1968   if( nFree>usableSize || nFree<iCellFirst ){
1969     return SQLITE_CORRUPT_PAGE(pPage);
1970   }
1971   pPage->nFree = (u16)(nFree - iCellFirst);
1972   return SQLITE_OK;
1973 }
1974 
1975 /*
1976 ** Do additional sanity check after btreeInitPage() if
1977 ** PRAGMA cell_size_check=ON
1978 */
1979 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1980   int iCellFirst;    /* First allowable cell or freeblock offset */
1981   int iCellLast;     /* Last possible cell or freeblock offset */
1982   int i;             /* Index into the cell pointer array */
1983   int sz;            /* Size of a cell */
1984   int pc;            /* Address of a freeblock within pPage->aData[] */
1985   u8 *data;          /* Equal to pPage->aData */
1986   int usableSize;    /* Maximum usable space on the page */
1987   int cellOffset;    /* Start of cell content area */
1988 
1989   iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1990   usableSize = pPage->pBt->usableSize;
1991   iCellLast = usableSize - 4;
1992   data = pPage->aData;
1993   cellOffset = pPage->cellOffset;
1994   if( !pPage->leaf ) iCellLast--;
1995   for(i=0; i<pPage->nCell; i++){
1996     pc = get2byteAligned(&data[cellOffset+i*2]);
1997     testcase( pc==iCellFirst );
1998     testcase( pc==iCellLast );
1999     if( pc<iCellFirst || pc>iCellLast ){
2000       return SQLITE_CORRUPT_PAGE(pPage);
2001     }
2002     sz = pPage->xCellSize(pPage, &data[pc]);
2003     testcase( pc+sz==usableSize );
2004     if( pc+sz>usableSize ){
2005       return SQLITE_CORRUPT_PAGE(pPage);
2006     }
2007   }
2008   return SQLITE_OK;
2009 }
2010 
2011 /*
2012 ** Initialize the auxiliary information for a disk block.
2013 **
2014 ** Return SQLITE_OK on success.  If we see that the page does
2015 ** not contain a well-formed database page, then return
2016 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
2017 ** guarantee that the page is well-formed.  It only shows that
2018 ** we failed to detect any corruption.
2019 */
2020 static int btreeInitPage(MemPage *pPage){
2021   u8 *data;          /* Equal to pPage->aData */
2022   BtShared *pBt;        /* The main btree structure */
2023 
2024   assert( pPage->pBt!=0 );
2025   assert( pPage->pBt->db!=0 );
2026   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2027   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2028   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2029   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2030   assert( pPage->isInit==0 );
2031 
2032   pBt = pPage->pBt;
2033   data = pPage->aData + pPage->hdrOffset;
2034   /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2035   ** the b-tree page type. */
2036   if( decodeFlags(pPage, data[0]) ){
2037     return SQLITE_CORRUPT_PAGE(pPage);
2038   }
2039   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2040   pPage->maskPage = (u16)(pBt->pageSize - 1);
2041   pPage->nOverflow = 0;
2042   pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2043   pPage->aCellIdx = data + pPage->childPtrSize + 8;
2044   pPage->aDataEnd = pPage->aData + pBt->usableSize;
2045   pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2046   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2047   ** number of cells on the page. */
2048   pPage->nCell = get2byte(&data[3]);
2049   if( pPage->nCell>MX_CELL(pBt) ){
2050     /* To many cells for a single page.  The page must be corrupt */
2051     return SQLITE_CORRUPT_PAGE(pPage);
2052   }
2053   testcase( pPage->nCell==MX_CELL(pBt) );
2054   /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2055   ** possible for a root page of a table that contains no rows) then the
2056   ** offset to the cell content area will equal the page size minus the
2057   ** bytes of reserved space. */
2058   assert( pPage->nCell>0
2059        || get2byteNotZero(&data[5])==(int)pBt->usableSize
2060        || CORRUPT_DB );
2061   pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */
2062   pPage->isInit = 1;
2063   if( pBt->db->flags & SQLITE_CellSizeCk ){
2064     return btreeCellSizeCheck(pPage);
2065   }
2066   return SQLITE_OK;
2067 }
2068 
2069 /*
2070 ** Set up a raw page so that it looks like a database page holding
2071 ** no entries.
2072 */
2073 static void zeroPage(MemPage *pPage, int flags){
2074   unsigned char *data = pPage->aData;
2075   BtShared *pBt = pPage->pBt;
2076   u8 hdr = pPage->hdrOffset;
2077   u16 first;
2078 
2079   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2080   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2081   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2082   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2083   assert( sqlite3_mutex_held(pBt->mutex) );
2084   if( pBt->btsFlags & BTS_FAST_SECURE ){
2085     memset(&data[hdr], 0, pBt->usableSize - hdr);
2086   }
2087   data[hdr] = (char)flags;
2088   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2089   memset(&data[hdr+1], 0, 4);
2090   data[hdr+7] = 0;
2091   put2byte(&data[hdr+5], pBt->usableSize);
2092   pPage->nFree = (u16)(pBt->usableSize - first);
2093   decodeFlags(pPage, flags);
2094   pPage->cellOffset = first;
2095   pPage->aDataEnd = &data[pBt->usableSize];
2096   pPage->aCellIdx = &data[first];
2097   pPage->aDataOfst = &data[pPage->childPtrSize];
2098   pPage->nOverflow = 0;
2099   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2100   pPage->maskPage = (u16)(pBt->pageSize - 1);
2101   pPage->nCell = 0;
2102   pPage->isInit = 1;
2103 }
2104 
2105 
2106 /*
2107 ** Convert a DbPage obtained from the pager into a MemPage used by
2108 ** the btree layer.
2109 */
2110 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2111   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2112   if( pgno!=pPage->pgno ){
2113     pPage->aData = sqlite3PagerGetData(pDbPage);
2114     pPage->pDbPage = pDbPage;
2115     pPage->pBt = pBt;
2116     pPage->pgno = pgno;
2117     pPage->hdrOffset = pgno==1 ? 100 : 0;
2118   }
2119   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2120   return pPage;
2121 }
2122 
2123 /*
2124 ** Get a page from the pager.  Initialize the MemPage.pBt and
2125 ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
2126 **
2127 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2128 ** about the content of the page at this time.  So do not go to the disk
2129 ** to fetch the content.  Just fill in the content with zeros for now.
2130 ** If in the future we call sqlite3PagerWrite() on this page, that
2131 ** means we have started to be concerned about content and the disk
2132 ** read should occur at that point.
2133 */
2134 static int btreeGetPage(
2135   BtShared *pBt,       /* The btree */
2136   Pgno pgno,           /* Number of the page to fetch */
2137   MemPage **ppPage,    /* Return the page in this parameter */
2138   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2139 ){
2140   int rc;
2141   DbPage *pDbPage;
2142 
2143   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2144   assert( sqlite3_mutex_held(pBt->mutex) );
2145   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2146   if( rc ) return rc;
2147   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2148   return SQLITE_OK;
2149 }
2150 
2151 /*
2152 ** Retrieve a page from the pager cache. If the requested page is not
2153 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2154 ** MemPage.aData elements if needed.
2155 */
2156 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2157   DbPage *pDbPage;
2158   assert( sqlite3_mutex_held(pBt->mutex) );
2159   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2160   if( pDbPage ){
2161     return btreePageFromDbPage(pDbPage, pgno, pBt);
2162   }
2163   return 0;
2164 }
2165 
2166 /*
2167 ** Return the size of the database file in pages. If there is any kind of
2168 ** error, return ((unsigned int)-1).
2169 */
2170 static Pgno btreePagecount(BtShared *pBt){
2171   return pBt->nPage;
2172 }
2173 Pgno sqlite3BtreeLastPage(Btree *p){
2174   assert( sqlite3BtreeHoldsMutex(p) );
2175   return btreePagecount(p->pBt);
2176 }
2177 
2178 /*
2179 ** Get a page from the pager and initialize it.
2180 **
2181 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2182 ** call.  Do additional sanity checking on the page in this case.
2183 ** And if the fetch fails, this routine must decrement pCur->iPage.
2184 **
2185 ** The page is fetched as read-write unless pCur is not NULL and is
2186 ** a read-only cursor.
2187 **
2188 ** If an error occurs, then *ppPage is undefined. It
2189 ** may remain unchanged, or it may be set to an invalid value.
2190 */
2191 static int getAndInitPage(
2192   BtShared *pBt,                  /* The database file */
2193   Pgno pgno,                      /* Number of the page to get */
2194   MemPage **ppPage,               /* Write the page pointer here */
2195   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
2196   int bReadOnly                   /* True for a read-only page */
2197 ){
2198   int rc;
2199   DbPage *pDbPage;
2200   assert( sqlite3_mutex_held(pBt->mutex) );
2201   assert( pCur==0 || ppPage==&pCur->pPage );
2202   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2203   assert( pCur==0 || pCur->iPage>0 );
2204 
2205   if( pgno>btreePagecount(pBt) ){
2206     rc = SQLITE_CORRUPT_BKPT;
2207     goto getAndInitPage_error1;
2208   }
2209   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2210   if( rc ){
2211     goto getAndInitPage_error1;
2212   }
2213   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2214   if( (*ppPage)->isInit==0 ){
2215     btreePageFromDbPage(pDbPage, pgno, pBt);
2216     rc = btreeInitPage(*ppPage);
2217     if( rc!=SQLITE_OK ){
2218       goto getAndInitPage_error2;
2219     }
2220   }
2221   assert( (*ppPage)->pgno==pgno );
2222   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2223 
2224   /* If obtaining a child page for a cursor, we must verify that the page is
2225   ** compatible with the root page. */
2226   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2227     rc = SQLITE_CORRUPT_PGNO(pgno);
2228     goto getAndInitPage_error2;
2229   }
2230   return SQLITE_OK;
2231 
2232 getAndInitPage_error2:
2233   releasePage(*ppPage);
2234 getAndInitPage_error1:
2235   if( pCur ){
2236     pCur->iPage--;
2237     pCur->pPage = pCur->apPage[pCur->iPage];
2238   }
2239   testcase( pgno==0 );
2240   assert( pgno!=0 || rc==SQLITE_CORRUPT );
2241   return rc;
2242 }
2243 
2244 /*
2245 ** Release a MemPage.  This should be called once for each prior
2246 ** call to btreeGetPage.
2247 **
2248 ** Page1 is a special case and must be released using releasePageOne().
2249 */
2250 static void releasePageNotNull(MemPage *pPage){
2251   assert( pPage->aData );
2252   assert( pPage->pBt );
2253   assert( pPage->pDbPage!=0 );
2254   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2255   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2256   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2257   sqlite3PagerUnrefNotNull(pPage->pDbPage);
2258 }
2259 static void releasePage(MemPage *pPage){
2260   if( pPage ) releasePageNotNull(pPage);
2261 }
2262 static void releasePageOne(MemPage *pPage){
2263   assert( pPage!=0 );
2264   assert( pPage->aData );
2265   assert( pPage->pBt );
2266   assert( pPage->pDbPage!=0 );
2267   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2268   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2269   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2270   sqlite3PagerUnrefPageOne(pPage->pDbPage);
2271 }
2272 
2273 /*
2274 ** Get an unused page.
2275 **
2276 ** This works just like btreeGetPage() with the addition:
2277 **
2278 **   *  If the page is already in use for some other purpose, immediately
2279 **      release it and return an SQLITE_CURRUPT error.
2280 **   *  Make sure the isInit flag is clear
2281 */
2282 static int btreeGetUnusedPage(
2283   BtShared *pBt,       /* The btree */
2284   Pgno pgno,           /* Number of the page to fetch */
2285   MemPage **ppPage,    /* Return the page in this parameter */
2286   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2287 ){
2288   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2289   if( rc==SQLITE_OK ){
2290     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2291       releasePage(*ppPage);
2292       *ppPage = 0;
2293       return SQLITE_CORRUPT_BKPT;
2294     }
2295     (*ppPage)->isInit = 0;
2296   }else{
2297     *ppPage = 0;
2298   }
2299   return rc;
2300 }
2301 
2302 
2303 /*
2304 ** During a rollback, when the pager reloads information into the cache
2305 ** so that the cache is restored to its original state at the start of
2306 ** the transaction, for each page restored this routine is called.
2307 **
2308 ** This routine needs to reset the extra data section at the end of the
2309 ** page to agree with the restored data.
2310 */
2311 static void pageReinit(DbPage *pData){
2312   MemPage *pPage;
2313   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2314   assert( sqlite3PagerPageRefcount(pData)>0 );
2315   if( pPage->isInit ){
2316     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2317     pPage->isInit = 0;
2318     if( sqlite3PagerPageRefcount(pData)>1 ){
2319       /* pPage might not be a btree page;  it might be an overflow page
2320       ** or ptrmap page or a free page.  In those cases, the following
2321       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2322       ** But no harm is done by this.  And it is very important that
2323       ** btreeInitPage() be called on every btree page so we make
2324       ** the call for every page that comes in for re-initing. */
2325       btreeInitPage(pPage);
2326     }
2327   }
2328 }
2329 
2330 /*
2331 ** Invoke the busy handler for a btree.
2332 */
2333 static int btreeInvokeBusyHandler(void *pArg){
2334   BtShared *pBt = (BtShared*)pArg;
2335   assert( pBt->db );
2336   assert( sqlite3_mutex_held(pBt->db->mutex) );
2337   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2338 }
2339 
2340 /*
2341 ** Open a database file.
2342 **
2343 ** zFilename is the name of the database file.  If zFilename is NULL
2344 ** then an ephemeral database is created.  The ephemeral database might
2345 ** be exclusively in memory, or it might use a disk-based memory cache.
2346 ** Either way, the ephemeral database will be automatically deleted
2347 ** when sqlite3BtreeClose() is called.
2348 **
2349 ** If zFilename is ":memory:" then an in-memory database is created
2350 ** that is automatically destroyed when it is closed.
2351 **
2352 ** The "flags" parameter is a bitmask that might contain bits like
2353 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2354 **
2355 ** If the database is already opened in the same database connection
2356 ** and we are in shared cache mode, then the open will fail with an
2357 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
2358 ** objects in the same database connection since doing so will lead
2359 ** to problems with locking.
2360 */
2361 int sqlite3BtreeOpen(
2362   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
2363   const char *zFilename,  /* Name of the file containing the BTree database */
2364   sqlite3 *db,            /* Associated database handle */
2365   Btree **ppBtree,        /* Pointer to new Btree object written here */
2366   int flags,              /* Options */
2367   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
2368 ){
2369   BtShared *pBt = 0;             /* Shared part of btree structure */
2370   Btree *p;                      /* Handle to return */
2371   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
2372   int rc = SQLITE_OK;            /* Result code from this function */
2373   u8 nReserve;                   /* Byte of unused space on each page */
2374   unsigned char zDbHeader[100];  /* Database header content */
2375 
2376   /* True if opening an ephemeral, temporary database */
2377   const int isTempDb = zFilename==0 || zFilename[0]==0;
2378 
2379   /* Set the variable isMemdb to true for an in-memory database, or
2380   ** false for a file-based database.
2381   */
2382 #ifdef SQLITE_OMIT_MEMORYDB
2383   const int isMemdb = 0;
2384 #else
2385   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2386                        || (isTempDb && sqlite3TempInMemory(db))
2387                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2388 #endif
2389 
2390   assert( db!=0 );
2391   assert( pVfs!=0 );
2392   assert( sqlite3_mutex_held(db->mutex) );
2393   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
2394 
2395   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2396   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2397 
2398   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2399   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2400 
2401   if( isMemdb ){
2402     flags |= BTREE_MEMORY;
2403   }
2404   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2405     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2406   }
2407   p = sqlite3MallocZero(sizeof(Btree));
2408   if( !p ){
2409     return SQLITE_NOMEM_BKPT;
2410   }
2411   p->inTrans = TRANS_NONE;
2412   p->db = db;
2413 #ifndef SQLITE_OMIT_SHARED_CACHE
2414   p->lock.pBtree = p;
2415   p->lock.iTable = 1;
2416 #endif
2417 
2418 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2419   /*
2420   ** If this Btree is a candidate for shared cache, try to find an
2421   ** existing BtShared object that we can share with
2422   */
2423   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2424     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2425       int nFilename = sqlite3Strlen30(zFilename)+1;
2426       int nFullPathname = pVfs->mxPathname+1;
2427       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2428       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2429 
2430       p->sharable = 1;
2431       if( !zFullPathname ){
2432         sqlite3_free(p);
2433         return SQLITE_NOMEM_BKPT;
2434       }
2435       if( isMemdb ){
2436         memcpy(zFullPathname, zFilename, nFilename);
2437       }else{
2438         rc = sqlite3OsFullPathname(pVfs, zFilename,
2439                                    nFullPathname, zFullPathname);
2440         if( rc ){
2441           if( rc==SQLITE_OK_SYMLINK ){
2442             rc = SQLITE_OK;
2443           }else{
2444             sqlite3_free(zFullPathname);
2445             sqlite3_free(p);
2446             return rc;
2447           }
2448         }
2449       }
2450 #if SQLITE_THREADSAFE
2451       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2452       sqlite3_mutex_enter(mutexOpen);
2453       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2454       sqlite3_mutex_enter(mutexShared);
2455 #endif
2456       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2457         assert( pBt->nRef>0 );
2458         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2459                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2460           int iDb;
2461           for(iDb=db->nDb-1; iDb>=0; iDb--){
2462             Btree *pExisting = db->aDb[iDb].pBt;
2463             if( pExisting && pExisting->pBt==pBt ){
2464               sqlite3_mutex_leave(mutexShared);
2465               sqlite3_mutex_leave(mutexOpen);
2466               sqlite3_free(zFullPathname);
2467               sqlite3_free(p);
2468               return SQLITE_CONSTRAINT;
2469             }
2470           }
2471           p->pBt = pBt;
2472           pBt->nRef++;
2473           break;
2474         }
2475       }
2476       sqlite3_mutex_leave(mutexShared);
2477       sqlite3_free(zFullPathname);
2478     }
2479 #ifdef SQLITE_DEBUG
2480     else{
2481       /* In debug mode, we mark all persistent databases as sharable
2482       ** even when they are not.  This exercises the locking code and
2483       ** gives more opportunity for asserts(sqlite3_mutex_held())
2484       ** statements to find locking problems.
2485       */
2486       p->sharable = 1;
2487     }
2488 #endif
2489   }
2490 #endif
2491   if( pBt==0 ){
2492     /*
2493     ** The following asserts make sure that structures used by the btree are
2494     ** the right size.  This is to guard against size changes that result
2495     ** when compiling on a different architecture.
2496     */
2497     assert( sizeof(i64)==8 );
2498     assert( sizeof(u64)==8 );
2499     assert( sizeof(u32)==4 );
2500     assert( sizeof(u16)==2 );
2501     assert( sizeof(Pgno)==4 );
2502 
2503     pBt = sqlite3MallocZero( sizeof(*pBt) );
2504     if( pBt==0 ){
2505       rc = SQLITE_NOMEM_BKPT;
2506       goto btree_open_out;
2507     }
2508     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2509                           sizeof(MemPage), flags, vfsFlags, pageReinit);
2510     if( rc==SQLITE_OK ){
2511       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2512       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2513     }
2514     if( rc!=SQLITE_OK ){
2515       goto btree_open_out;
2516     }
2517     pBt->openFlags = (u8)flags;
2518     pBt->db = db;
2519     sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2520     p->pBt = pBt;
2521 
2522     pBt->pCursor = 0;
2523     pBt->pPage1 = 0;
2524     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2525 #if defined(SQLITE_SECURE_DELETE)
2526     pBt->btsFlags |= BTS_SECURE_DELETE;
2527 #elif defined(SQLITE_FAST_SECURE_DELETE)
2528     pBt->btsFlags |= BTS_OVERWRITE;
2529 #endif
2530     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2531     ** determined by the 2-byte integer located at an offset of 16 bytes from
2532     ** the beginning of the database file. */
2533     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2534     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2535          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2536       pBt->pageSize = 0;
2537 #ifndef SQLITE_OMIT_AUTOVACUUM
2538       /* If the magic name ":memory:" will create an in-memory database, then
2539       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2540       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2541       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2542       ** regular file-name. In this case the auto-vacuum applies as per normal.
2543       */
2544       if( zFilename && !isMemdb ){
2545         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2546         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2547       }
2548 #endif
2549       nReserve = 0;
2550     }else{
2551       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2552       ** determined by the one-byte unsigned integer found at an offset of 20
2553       ** into the database file header. */
2554       nReserve = zDbHeader[20];
2555       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2556 #ifndef SQLITE_OMIT_AUTOVACUUM
2557       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2558       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2559 #endif
2560     }
2561     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2562     if( rc ) goto btree_open_out;
2563     pBt->usableSize = pBt->pageSize - nReserve;
2564     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
2565 
2566 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2567     /* Add the new BtShared object to the linked list sharable BtShareds.
2568     */
2569     pBt->nRef = 1;
2570     if( p->sharable ){
2571       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2572       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2573       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2574         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2575         if( pBt->mutex==0 ){
2576           rc = SQLITE_NOMEM_BKPT;
2577           goto btree_open_out;
2578         }
2579       }
2580       sqlite3_mutex_enter(mutexShared);
2581       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2582       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2583       sqlite3_mutex_leave(mutexShared);
2584     }
2585 #endif
2586   }
2587 
2588 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2589   /* If the new Btree uses a sharable pBtShared, then link the new
2590   ** Btree into the list of all sharable Btrees for the same connection.
2591   ** The list is kept in ascending order by pBt address.
2592   */
2593   if( p->sharable ){
2594     int i;
2595     Btree *pSib;
2596     for(i=0; i<db->nDb; i++){
2597       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2598         while( pSib->pPrev ){ pSib = pSib->pPrev; }
2599         if( (uptr)p->pBt<(uptr)pSib->pBt ){
2600           p->pNext = pSib;
2601           p->pPrev = 0;
2602           pSib->pPrev = p;
2603         }else{
2604           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2605             pSib = pSib->pNext;
2606           }
2607           p->pNext = pSib->pNext;
2608           p->pPrev = pSib;
2609           if( p->pNext ){
2610             p->pNext->pPrev = p;
2611           }
2612           pSib->pNext = p;
2613         }
2614         break;
2615       }
2616     }
2617   }
2618 #endif
2619   *ppBtree = p;
2620 
2621 btree_open_out:
2622   if( rc!=SQLITE_OK ){
2623     if( pBt && pBt->pPager ){
2624       sqlite3PagerClose(pBt->pPager, 0);
2625     }
2626     sqlite3_free(pBt);
2627     sqlite3_free(p);
2628     *ppBtree = 0;
2629   }else{
2630     sqlite3_file *pFile;
2631 
2632     /* If the B-Tree was successfully opened, set the pager-cache size to the
2633     ** default value. Except, when opening on an existing shared pager-cache,
2634     ** do not change the pager-cache size.
2635     */
2636     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2637       sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2638     }
2639 
2640     pFile = sqlite3PagerFile(pBt->pPager);
2641     if( pFile->pMethods ){
2642       sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2643     }
2644   }
2645   if( mutexOpen ){
2646     assert( sqlite3_mutex_held(mutexOpen) );
2647     sqlite3_mutex_leave(mutexOpen);
2648   }
2649   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2650   return rc;
2651 }
2652 
2653 /*
2654 ** Decrement the BtShared.nRef counter.  When it reaches zero,
2655 ** remove the BtShared structure from the sharing list.  Return
2656 ** true if the BtShared.nRef counter reaches zero and return
2657 ** false if it is still positive.
2658 */
2659 static int removeFromSharingList(BtShared *pBt){
2660 #ifndef SQLITE_OMIT_SHARED_CACHE
2661   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2662   BtShared *pList;
2663   int removed = 0;
2664 
2665   assert( sqlite3_mutex_notheld(pBt->mutex) );
2666   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2667   sqlite3_mutex_enter(pMainMtx);
2668   pBt->nRef--;
2669   if( pBt->nRef<=0 ){
2670     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2671       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2672     }else{
2673       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2674       while( ALWAYS(pList) && pList->pNext!=pBt ){
2675         pList=pList->pNext;
2676       }
2677       if( ALWAYS(pList) ){
2678         pList->pNext = pBt->pNext;
2679       }
2680     }
2681     if( SQLITE_THREADSAFE ){
2682       sqlite3_mutex_free(pBt->mutex);
2683     }
2684     removed = 1;
2685   }
2686   sqlite3_mutex_leave(pMainMtx);
2687   return removed;
2688 #else
2689   return 1;
2690 #endif
2691 }
2692 
2693 /*
2694 ** Make sure pBt->pTmpSpace points to an allocation of
2695 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2696 ** pointer.
2697 */
2698 static void allocateTempSpace(BtShared *pBt){
2699   if( !pBt->pTmpSpace ){
2700     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2701 
2702     /* One of the uses of pBt->pTmpSpace is to format cells before
2703     ** inserting them into a leaf page (function fillInCell()). If
2704     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2705     ** by the various routines that manipulate binary cells. Which
2706     ** can mean that fillInCell() only initializes the first 2 or 3
2707     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2708     ** it into a database page. This is not actually a problem, but it
2709     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2710     ** data is passed to system call write(). So to avoid this error,
2711     ** zero the first 4 bytes of temp space here.
2712     **
2713     ** Also:  Provide four bytes of initialized space before the
2714     ** beginning of pTmpSpace as an area available to prepend the
2715     ** left-child pointer to the beginning of a cell.
2716     */
2717     if( pBt->pTmpSpace ){
2718       memset(pBt->pTmpSpace, 0, 8);
2719       pBt->pTmpSpace += 4;
2720     }
2721   }
2722 }
2723 
2724 /*
2725 ** Free the pBt->pTmpSpace allocation
2726 */
2727 static void freeTempSpace(BtShared *pBt){
2728   if( pBt->pTmpSpace ){
2729     pBt->pTmpSpace -= 4;
2730     sqlite3PageFree(pBt->pTmpSpace);
2731     pBt->pTmpSpace = 0;
2732   }
2733 }
2734 
2735 /*
2736 ** Close an open database and invalidate all cursors.
2737 */
2738 int sqlite3BtreeClose(Btree *p){
2739   BtShared *pBt = p->pBt;
2740   BtCursor *pCur;
2741 
2742   /* Close all cursors opened via this handle.  */
2743   assert( sqlite3_mutex_held(p->db->mutex) );
2744   sqlite3BtreeEnter(p);
2745   pCur = pBt->pCursor;
2746   while( pCur ){
2747     BtCursor *pTmp = pCur;
2748     pCur = pCur->pNext;
2749     if( pTmp->pBtree==p ){
2750       sqlite3BtreeCloseCursor(pTmp);
2751     }
2752   }
2753 
2754   /* Rollback any active transaction and free the handle structure.
2755   ** The call to sqlite3BtreeRollback() drops any table-locks held by
2756   ** this handle.
2757   */
2758   sqlite3BtreeRollback(p, SQLITE_OK, 0);
2759   sqlite3BtreeLeave(p);
2760 
2761   /* If there are still other outstanding references to the shared-btree
2762   ** structure, return now. The remainder of this procedure cleans
2763   ** up the shared-btree.
2764   */
2765   assert( p->wantToLock==0 && p->locked==0 );
2766   if( !p->sharable || removeFromSharingList(pBt) ){
2767     /* The pBt is no longer on the sharing list, so we can access
2768     ** it without having to hold the mutex.
2769     **
2770     ** Clean out and delete the BtShared object.
2771     */
2772     assert( !pBt->pCursor );
2773     sqlite3PagerClose(pBt->pPager, p->db);
2774     if( pBt->xFreeSchema && pBt->pSchema ){
2775       pBt->xFreeSchema(pBt->pSchema);
2776     }
2777     sqlite3DbFree(0, pBt->pSchema);
2778     freeTempSpace(pBt);
2779     sqlite3_free(pBt);
2780   }
2781 
2782 #ifndef SQLITE_OMIT_SHARED_CACHE
2783   assert( p->wantToLock==0 );
2784   assert( p->locked==0 );
2785   if( p->pPrev ) p->pPrev->pNext = p->pNext;
2786   if( p->pNext ) p->pNext->pPrev = p->pPrev;
2787 #endif
2788 
2789   sqlite3_free(p);
2790   return SQLITE_OK;
2791 }
2792 
2793 /*
2794 ** Change the "soft" limit on the number of pages in the cache.
2795 ** Unused and unmodified pages will be recycled when the number of
2796 ** pages in the cache exceeds this soft limit.  But the size of the
2797 ** cache is allowed to grow larger than this limit if it contains
2798 ** dirty pages or pages still in active use.
2799 */
2800 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2801   BtShared *pBt = p->pBt;
2802   assert( sqlite3_mutex_held(p->db->mutex) );
2803   sqlite3BtreeEnter(p);
2804   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2805   sqlite3BtreeLeave(p);
2806   return SQLITE_OK;
2807 }
2808 
2809 /*
2810 ** Change the "spill" limit on the number of pages in the cache.
2811 ** If the number of pages exceeds this limit during a write transaction,
2812 ** the pager might attempt to "spill" pages to the journal early in
2813 ** order to free up memory.
2814 **
2815 ** The value returned is the current spill size.  If zero is passed
2816 ** as an argument, no changes are made to the spill size setting, so
2817 ** using mxPage of 0 is a way to query the current spill size.
2818 */
2819 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2820   BtShared *pBt = p->pBt;
2821   int res;
2822   assert( sqlite3_mutex_held(p->db->mutex) );
2823   sqlite3BtreeEnter(p);
2824   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2825   sqlite3BtreeLeave(p);
2826   return res;
2827 }
2828 
2829 #if SQLITE_MAX_MMAP_SIZE>0
2830 /*
2831 ** Change the limit on the amount of the database file that may be
2832 ** memory mapped.
2833 */
2834 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2835   BtShared *pBt = p->pBt;
2836   assert( sqlite3_mutex_held(p->db->mutex) );
2837   sqlite3BtreeEnter(p);
2838   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2839   sqlite3BtreeLeave(p);
2840   return SQLITE_OK;
2841 }
2842 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2843 
2844 /*
2845 ** Change the way data is synced to disk in order to increase or decrease
2846 ** how well the database resists damage due to OS crashes and power
2847 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
2848 ** there is a high probability of damage)  Level 2 is the default.  There
2849 ** is a very low but non-zero probability of damage.  Level 3 reduces the
2850 ** probability of damage to near zero but with a write performance reduction.
2851 */
2852 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2853 int sqlite3BtreeSetPagerFlags(
2854   Btree *p,              /* The btree to set the safety level on */
2855   unsigned pgFlags       /* Various PAGER_* flags */
2856 ){
2857   BtShared *pBt = p->pBt;
2858   assert( sqlite3_mutex_held(p->db->mutex) );
2859   sqlite3BtreeEnter(p);
2860   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2861   sqlite3BtreeLeave(p);
2862   return SQLITE_OK;
2863 }
2864 #endif
2865 
2866 /*
2867 ** Change the default pages size and the number of reserved bytes per page.
2868 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2869 ** without changing anything.
2870 **
2871 ** The page size must be a power of 2 between 512 and 65536.  If the page
2872 ** size supplied does not meet this constraint then the page size is not
2873 ** changed.
2874 **
2875 ** Page sizes are constrained to be a power of two so that the region
2876 ** of the database file used for locking (beginning at PENDING_BYTE,
2877 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2878 ** at the beginning of a page.
2879 **
2880 ** If parameter nReserve is less than zero, then the number of reserved
2881 ** bytes per page is left unchanged.
2882 **
2883 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2884 ** and autovacuum mode can no longer be changed.
2885 */
2886 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2887   int rc = SQLITE_OK;
2888   int x;
2889   BtShared *pBt = p->pBt;
2890   assert( nReserve>=0 && nReserve<=255 );
2891   sqlite3BtreeEnter(p);
2892   pBt->nReserveWanted = nReserve;
2893   x = pBt->pageSize - pBt->usableSize;
2894   if( nReserve<x ) nReserve = x;
2895   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2896     sqlite3BtreeLeave(p);
2897     return SQLITE_READONLY;
2898   }
2899   assert( nReserve>=0 && nReserve<=255 );
2900   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2901         ((pageSize-1)&pageSize)==0 ){
2902     assert( (pageSize & 7)==0 );
2903     assert( !pBt->pCursor );
2904     pBt->pageSize = (u32)pageSize;
2905     freeTempSpace(pBt);
2906   }
2907   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2908   pBt->usableSize = pBt->pageSize - (u16)nReserve;
2909   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2910   sqlite3BtreeLeave(p);
2911   return rc;
2912 }
2913 
2914 /*
2915 ** Return the currently defined page size
2916 */
2917 int sqlite3BtreeGetPageSize(Btree *p){
2918   return p->pBt->pageSize;
2919 }
2920 
2921 /*
2922 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2923 ** may only be called if it is guaranteed that the b-tree mutex is already
2924 ** held.
2925 **
2926 ** This is useful in one special case in the backup API code where it is
2927 ** known that the shared b-tree mutex is held, but the mutex on the
2928 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2929 ** were to be called, it might collide with some other operation on the
2930 ** database handle that owns *p, causing undefined behavior.
2931 */
2932 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2933   int n;
2934   assert( sqlite3_mutex_held(p->pBt->mutex) );
2935   n = p->pBt->pageSize - p->pBt->usableSize;
2936   return n;
2937 }
2938 
2939 /*
2940 ** Return the number of bytes of space at the end of every page that
2941 ** are intentually left unused.  This is the "reserved" space that is
2942 ** sometimes used by extensions.
2943 **
2944 ** The value returned is the larger of the current reserve size and
2945 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2946 ** The amount of reserve can only grow - never shrink.
2947 */
2948 int sqlite3BtreeGetRequestedReserve(Btree *p){
2949   int n1, n2;
2950   sqlite3BtreeEnter(p);
2951   n1 = (int)p->pBt->nReserveWanted;
2952   n2 = sqlite3BtreeGetReserveNoMutex(p);
2953   sqlite3BtreeLeave(p);
2954   return n1>n2 ? n1 : n2;
2955 }
2956 
2957 
2958 /*
2959 ** Set the maximum page count for a database if mxPage is positive.
2960 ** No changes are made if mxPage is 0 or negative.
2961 ** Regardless of the value of mxPage, return the maximum page count.
2962 */
2963 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2964   Pgno n;
2965   sqlite3BtreeEnter(p);
2966   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2967   sqlite3BtreeLeave(p);
2968   return n;
2969 }
2970 
2971 /*
2972 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2973 **
2974 **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2975 **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2976 **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2977 **    newFlag==(-1)    No changes
2978 **
2979 ** This routine acts as a query if newFlag is less than zero
2980 **
2981 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2982 ** freelist leaf pages are not written back to the database.  Thus in-page
2983 ** deleted content is cleared, but freelist deleted content is not.
2984 **
2985 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2986 ** that freelist leaf pages are written back into the database, increasing
2987 ** the amount of disk I/O.
2988 */
2989 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2990   int b;
2991   if( p==0 ) return 0;
2992   sqlite3BtreeEnter(p);
2993   assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2994   assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
2995   if( newFlag>=0 ){
2996     p->pBt->btsFlags &= ~BTS_FAST_SECURE;
2997     p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
2998   }
2999   b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3000   sqlite3BtreeLeave(p);
3001   return b;
3002 }
3003 
3004 /*
3005 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3006 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3007 ** is disabled. The default value for the auto-vacuum property is
3008 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3009 */
3010 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3011 #ifdef SQLITE_OMIT_AUTOVACUUM
3012   return SQLITE_READONLY;
3013 #else
3014   BtShared *pBt = p->pBt;
3015   int rc = SQLITE_OK;
3016   u8 av = (u8)autoVacuum;
3017 
3018   sqlite3BtreeEnter(p);
3019   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3020     rc = SQLITE_READONLY;
3021   }else{
3022     pBt->autoVacuum = av ?1:0;
3023     pBt->incrVacuum = av==2 ?1:0;
3024   }
3025   sqlite3BtreeLeave(p);
3026   return rc;
3027 #endif
3028 }
3029 
3030 /*
3031 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3032 ** enabled 1 is returned. Otherwise 0.
3033 */
3034 int sqlite3BtreeGetAutoVacuum(Btree *p){
3035 #ifdef SQLITE_OMIT_AUTOVACUUM
3036   return BTREE_AUTOVACUUM_NONE;
3037 #else
3038   int rc;
3039   sqlite3BtreeEnter(p);
3040   rc = (
3041     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3042     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3043     BTREE_AUTOVACUUM_INCR
3044   );
3045   sqlite3BtreeLeave(p);
3046   return rc;
3047 #endif
3048 }
3049 
3050 /*
3051 ** If the user has not set the safety-level for this database connection
3052 ** using "PRAGMA synchronous", and if the safety-level is not already
3053 ** set to the value passed to this function as the second parameter,
3054 ** set it so.
3055 */
3056 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3057     && !defined(SQLITE_OMIT_WAL)
3058 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3059   sqlite3 *db;
3060   Db *pDb;
3061   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3062     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3063     if( pDb->bSyncSet==0
3064      && pDb->safety_level!=safety_level
3065      && pDb!=&db->aDb[1]
3066     ){
3067       pDb->safety_level = safety_level;
3068       sqlite3PagerSetFlags(pBt->pPager,
3069           pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3070     }
3071   }
3072 }
3073 #else
3074 # define setDefaultSyncFlag(pBt,safety_level)
3075 #endif
3076 
3077 /* Forward declaration */
3078 static int newDatabase(BtShared*);
3079 
3080 
3081 /*
3082 ** Get a reference to pPage1 of the database file.  This will
3083 ** also acquire a readlock on that file.
3084 **
3085 ** SQLITE_OK is returned on success.  If the file is not a
3086 ** well-formed database file, then SQLITE_CORRUPT is returned.
3087 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
3088 ** is returned if we run out of memory.
3089 */
3090 static int lockBtree(BtShared *pBt){
3091   int rc;              /* Result code from subfunctions */
3092   MemPage *pPage1;     /* Page 1 of the database file */
3093   u32 nPage;           /* Number of pages in the database */
3094   u32 nPageFile = 0;   /* Number of pages in the database file */
3095   u32 nPageHeader;     /* Number of pages in the database according to hdr */
3096 
3097   assert( sqlite3_mutex_held(pBt->mutex) );
3098   assert( pBt->pPage1==0 );
3099   rc = sqlite3PagerSharedLock(pBt->pPager);
3100   if( rc!=SQLITE_OK ) return rc;
3101   rc = btreeGetPage(pBt, 1, &pPage1, 0);
3102   if( rc!=SQLITE_OK ) return rc;
3103 
3104   /* Do some checking to help insure the file we opened really is
3105   ** a valid database file.
3106   */
3107   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
3108   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3109   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3110     nPage = nPageFile;
3111   }
3112   if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3113     nPage = 0;
3114   }
3115   if( nPage>0 ){
3116     u32 pageSize;
3117     u32 usableSize;
3118     u8 *page1 = pPage1->aData;
3119     rc = SQLITE_NOTADB;
3120     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3121     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3122     ** 61 74 20 33 00. */
3123     if( memcmp(page1, zMagicHeader, 16)!=0 ){
3124       goto page1_init_failed;
3125     }
3126 
3127 #ifdef SQLITE_OMIT_WAL
3128     if( page1[18]>1 ){
3129       pBt->btsFlags |= BTS_READ_ONLY;
3130     }
3131     if( page1[19]>1 ){
3132       goto page1_init_failed;
3133     }
3134 #else
3135     if( page1[18]>2 ){
3136       pBt->btsFlags |= BTS_READ_ONLY;
3137     }
3138     if( page1[19]>2 ){
3139       goto page1_init_failed;
3140     }
3141 
3142     /* If the write version is set to 2, this database should be accessed
3143     ** in WAL mode. If the log is not already open, open it now. Then
3144     ** return SQLITE_OK and return without populating BtShared.pPage1.
3145     ** The caller detects this and calls this function again. This is
3146     ** required as the version of page 1 currently in the page1 buffer
3147     ** may not be the latest version - there may be a newer one in the log
3148     ** file.
3149     */
3150     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3151       int isOpen = 0;
3152       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3153       if( rc!=SQLITE_OK ){
3154         goto page1_init_failed;
3155       }else{
3156         setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3157         if( isOpen==0 ){
3158           releasePageOne(pPage1);
3159           return SQLITE_OK;
3160         }
3161       }
3162       rc = SQLITE_NOTADB;
3163     }else{
3164       setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3165     }
3166 #endif
3167 
3168     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3169     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3170     **
3171     ** The original design allowed these amounts to vary, but as of
3172     ** version 3.6.0, we require them to be fixed.
3173     */
3174     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3175       goto page1_init_failed;
3176     }
3177     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3178     ** determined by the 2-byte integer located at an offset of 16 bytes from
3179     ** the beginning of the database file. */
3180     pageSize = (page1[16]<<8) | (page1[17]<<16);
3181     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3182     ** between 512 and 65536 inclusive. */
3183     if( ((pageSize-1)&pageSize)!=0
3184      || pageSize>SQLITE_MAX_PAGE_SIZE
3185      || pageSize<=256
3186     ){
3187       goto page1_init_failed;
3188     }
3189     pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3190     assert( (pageSize & 7)==0 );
3191     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3192     ** integer at offset 20 is the number of bytes of space at the end of
3193     ** each page to reserve for extensions.
3194     **
3195     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3196     ** determined by the one-byte unsigned integer found at an offset of 20
3197     ** into the database file header. */
3198     usableSize = pageSize - page1[20];
3199     if( (u32)pageSize!=pBt->pageSize ){
3200       /* After reading the first page of the database assuming a page size
3201       ** of BtShared.pageSize, we have discovered that the page-size is
3202       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3203       ** zero and return SQLITE_OK. The caller will call this function
3204       ** again with the correct page-size.
3205       */
3206       releasePageOne(pPage1);
3207       pBt->usableSize = usableSize;
3208       pBt->pageSize = pageSize;
3209       freeTempSpace(pBt);
3210       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3211                                    pageSize-usableSize);
3212       return rc;
3213     }
3214     if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3215       rc = SQLITE_CORRUPT_BKPT;
3216       goto page1_init_failed;
3217     }
3218     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3219     ** be less than 480. In other words, if the page size is 512, then the
3220     ** reserved space size cannot exceed 32. */
3221     if( usableSize<480 ){
3222       goto page1_init_failed;
3223     }
3224     pBt->pageSize = pageSize;
3225     pBt->usableSize = usableSize;
3226 #ifndef SQLITE_OMIT_AUTOVACUUM
3227     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3228     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3229 #endif
3230   }
3231 
3232   /* maxLocal is the maximum amount of payload to store locally for
3233   ** a cell.  Make sure it is small enough so that at least minFanout
3234   ** cells can will fit on one page.  We assume a 10-byte page header.
3235   ** Besides the payload, the cell must store:
3236   **     2-byte pointer to the cell
3237   **     4-byte child pointer
3238   **     9-byte nKey value
3239   **     4-byte nData value
3240   **     4-byte overflow page pointer
3241   ** So a cell consists of a 2-byte pointer, a header which is as much as
3242   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3243   ** page pointer.
3244   */
3245   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3246   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3247   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3248   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3249   if( pBt->maxLocal>127 ){
3250     pBt->max1bytePayload = 127;
3251   }else{
3252     pBt->max1bytePayload = (u8)pBt->maxLocal;
3253   }
3254   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3255   pBt->pPage1 = pPage1;
3256   pBt->nPage = nPage;
3257   return SQLITE_OK;
3258 
3259 page1_init_failed:
3260   releasePageOne(pPage1);
3261   pBt->pPage1 = 0;
3262   return rc;
3263 }
3264 
3265 #ifndef NDEBUG
3266 /*
3267 ** Return the number of cursors open on pBt. This is for use
3268 ** in assert() expressions, so it is only compiled if NDEBUG is not
3269 ** defined.
3270 **
3271 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
3272 ** false then all cursors are counted.
3273 **
3274 ** For the purposes of this routine, a cursor is any cursor that
3275 ** is capable of reading or writing to the database.  Cursors that
3276 ** have been tripped into the CURSOR_FAULT state are not counted.
3277 */
3278 static int countValidCursors(BtShared *pBt, int wrOnly){
3279   BtCursor *pCur;
3280   int r = 0;
3281   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3282     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3283      && pCur->eState!=CURSOR_FAULT ) r++;
3284   }
3285   return r;
3286 }
3287 #endif
3288 
3289 /*
3290 ** If there are no outstanding cursors and we are not in the middle
3291 ** of a transaction but there is a read lock on the database, then
3292 ** this routine unrefs the first page of the database file which
3293 ** has the effect of releasing the read lock.
3294 **
3295 ** If there is a transaction in progress, this routine is a no-op.
3296 */
3297 static void unlockBtreeIfUnused(BtShared *pBt){
3298   assert( sqlite3_mutex_held(pBt->mutex) );
3299   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3300   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3301     MemPage *pPage1 = pBt->pPage1;
3302     assert( pPage1->aData );
3303     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3304     pBt->pPage1 = 0;
3305     releasePageOne(pPage1);
3306   }
3307 }
3308 
3309 /*
3310 ** If pBt points to an empty file then convert that empty file
3311 ** into a new empty database by initializing the first page of
3312 ** the database.
3313 */
3314 static int newDatabase(BtShared *pBt){
3315   MemPage *pP1;
3316   unsigned char *data;
3317   int rc;
3318 
3319   assert( sqlite3_mutex_held(pBt->mutex) );
3320   if( pBt->nPage>0 ){
3321     return SQLITE_OK;
3322   }
3323   pP1 = pBt->pPage1;
3324   assert( pP1!=0 );
3325   data = pP1->aData;
3326   rc = sqlite3PagerWrite(pP1->pDbPage);
3327   if( rc ) return rc;
3328   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3329   assert( sizeof(zMagicHeader)==16 );
3330   data[16] = (u8)((pBt->pageSize>>8)&0xff);
3331   data[17] = (u8)((pBt->pageSize>>16)&0xff);
3332   data[18] = 1;
3333   data[19] = 1;
3334   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3335   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3336   data[21] = 64;
3337   data[22] = 32;
3338   data[23] = 32;
3339   memset(&data[24], 0, 100-24);
3340   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3341   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3342 #ifndef SQLITE_OMIT_AUTOVACUUM
3343   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3344   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3345   put4byte(&data[36 + 4*4], pBt->autoVacuum);
3346   put4byte(&data[36 + 7*4], pBt->incrVacuum);
3347 #endif
3348   pBt->nPage = 1;
3349   data[31] = 1;
3350   return SQLITE_OK;
3351 }
3352 
3353 /*
3354 ** Initialize the first page of the database file (creating a database
3355 ** consisting of a single page and no schema objects). Return SQLITE_OK
3356 ** if successful, or an SQLite error code otherwise.
3357 */
3358 int sqlite3BtreeNewDb(Btree *p){
3359   int rc;
3360   sqlite3BtreeEnter(p);
3361   p->pBt->nPage = 0;
3362   rc = newDatabase(p->pBt);
3363   sqlite3BtreeLeave(p);
3364   return rc;
3365 }
3366 
3367 /*
3368 ** Attempt to start a new transaction. A write-transaction
3369 ** is started if the second argument is nonzero, otherwise a read-
3370 ** transaction.  If the second argument is 2 or more and exclusive
3371 ** transaction is started, meaning that no other process is allowed
3372 ** to access the database.  A preexisting transaction may not be
3373 ** upgraded to exclusive by calling this routine a second time - the
3374 ** exclusivity flag only works for a new transaction.
3375 **
3376 ** A write-transaction must be started before attempting any
3377 ** changes to the database.  None of the following routines
3378 ** will work unless a transaction is started first:
3379 **
3380 **      sqlite3BtreeCreateTable()
3381 **      sqlite3BtreeCreateIndex()
3382 **      sqlite3BtreeClearTable()
3383 **      sqlite3BtreeDropTable()
3384 **      sqlite3BtreeInsert()
3385 **      sqlite3BtreeDelete()
3386 **      sqlite3BtreeUpdateMeta()
3387 **
3388 ** If an initial attempt to acquire the lock fails because of lock contention
3389 ** and the database was previously unlocked, then invoke the busy handler
3390 ** if there is one.  But if there was previously a read-lock, do not
3391 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
3392 ** returned when there is already a read-lock in order to avoid a deadlock.
3393 **
3394 ** Suppose there are two processes A and B.  A has a read lock and B has
3395 ** a reserved lock.  B tries to promote to exclusive but is blocked because
3396 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
3397 ** One or the other of the two processes must give way or there can be
3398 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
3399 ** when A already has a read lock, we encourage A to give up and let B
3400 ** proceed.
3401 */
3402 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3403   BtShared *pBt = p->pBt;
3404   Pager *pPager = pBt->pPager;
3405   int rc = SQLITE_OK;
3406 
3407   sqlite3BtreeEnter(p);
3408   btreeIntegrity(p);
3409 
3410   /* If the btree is already in a write-transaction, or it
3411   ** is already in a read-transaction and a read-transaction
3412   ** is requested, this is a no-op.
3413   */
3414   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3415     goto trans_begun;
3416   }
3417   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3418 
3419   if( (p->db->flags & SQLITE_ResetDatabase)
3420    && sqlite3PagerIsreadonly(pPager)==0
3421   ){
3422     pBt->btsFlags &= ~BTS_READ_ONLY;
3423   }
3424 
3425   /* Write transactions are not possible on a read-only database */
3426   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3427     rc = SQLITE_READONLY;
3428     goto trans_begun;
3429   }
3430 
3431 #ifndef SQLITE_OMIT_SHARED_CACHE
3432   {
3433     sqlite3 *pBlock = 0;
3434     /* If another database handle has already opened a write transaction
3435     ** on this shared-btree structure and a second write transaction is
3436     ** requested, return SQLITE_LOCKED.
3437     */
3438     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3439      || (pBt->btsFlags & BTS_PENDING)!=0
3440     ){
3441       pBlock = pBt->pWriter->db;
3442     }else if( wrflag>1 ){
3443       BtLock *pIter;
3444       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3445         if( pIter->pBtree!=p ){
3446           pBlock = pIter->pBtree->db;
3447           break;
3448         }
3449       }
3450     }
3451     if( pBlock ){
3452       sqlite3ConnectionBlocked(p->db, pBlock);
3453       rc = SQLITE_LOCKED_SHAREDCACHE;
3454       goto trans_begun;
3455     }
3456   }
3457 #endif
3458 
3459   /* Any read-only or read-write transaction implies a read-lock on
3460   ** page 1. So if some other shared-cache client already has a write-lock
3461   ** on page 1, the transaction cannot be opened. */
3462   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3463   if( SQLITE_OK!=rc ) goto trans_begun;
3464 
3465   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3466   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3467   do {
3468     sqlite3PagerWalDb(pPager, p->db);
3469 
3470 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3471     /* If transitioning from no transaction directly to a write transaction,
3472     ** block for the WRITER lock first if possible. */
3473     if( pBt->pPage1==0 && wrflag ){
3474       assert( pBt->inTransaction==TRANS_NONE );
3475       rc = sqlite3PagerWalWriteLock(pPager, 1);
3476       if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3477     }
3478 #endif
3479 
3480     /* Call lockBtree() until either pBt->pPage1 is populated or
3481     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3482     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3483     ** reading page 1 it discovers that the page-size of the database
3484     ** file is not pBt->pageSize. In this case lockBtree() will update
3485     ** pBt->pageSize to the page-size of the file on disk.
3486     */
3487     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3488 
3489     if( rc==SQLITE_OK && wrflag ){
3490       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3491         rc = SQLITE_READONLY;
3492       }else{
3493         rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3494         if( rc==SQLITE_OK ){
3495           rc = newDatabase(pBt);
3496         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3497           /* if there was no transaction opened when this function was
3498           ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3499           ** code to SQLITE_BUSY. */
3500           rc = SQLITE_BUSY;
3501         }
3502       }
3503     }
3504 
3505     if( rc!=SQLITE_OK ){
3506       (void)sqlite3PagerWalWriteLock(pPager, 0);
3507       unlockBtreeIfUnused(pBt);
3508     }
3509   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3510           btreeInvokeBusyHandler(pBt) );
3511   sqlite3PagerWalDb(pPager, 0);
3512 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3513   if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3514 #endif
3515 
3516   if( rc==SQLITE_OK ){
3517     if( p->inTrans==TRANS_NONE ){
3518       pBt->nTransaction++;
3519 #ifndef SQLITE_OMIT_SHARED_CACHE
3520       if( p->sharable ){
3521         assert( p->lock.pBtree==p && p->lock.iTable==1 );
3522         p->lock.eLock = READ_LOCK;
3523         p->lock.pNext = pBt->pLock;
3524         pBt->pLock = &p->lock;
3525       }
3526 #endif
3527     }
3528     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3529     if( p->inTrans>pBt->inTransaction ){
3530       pBt->inTransaction = p->inTrans;
3531     }
3532     if( wrflag ){
3533       MemPage *pPage1 = pBt->pPage1;
3534 #ifndef SQLITE_OMIT_SHARED_CACHE
3535       assert( !pBt->pWriter );
3536       pBt->pWriter = p;
3537       pBt->btsFlags &= ~BTS_EXCLUSIVE;
3538       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3539 #endif
3540 
3541       /* If the db-size header field is incorrect (as it may be if an old
3542       ** client has been writing the database file), update it now. Doing
3543       ** this sooner rather than later means the database size can safely
3544       ** re-read the database size from page 1 if a savepoint or transaction
3545       ** rollback occurs within the transaction.
3546       */
3547       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3548         rc = sqlite3PagerWrite(pPage1->pDbPage);
3549         if( rc==SQLITE_OK ){
3550           put4byte(&pPage1->aData[28], pBt->nPage);
3551         }
3552       }
3553     }
3554   }
3555 
3556 trans_begun:
3557   if( rc==SQLITE_OK ){
3558     if( pSchemaVersion ){
3559       *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3560     }
3561     if( wrflag ){
3562       /* This call makes sure that the pager has the correct number of
3563       ** open savepoints. If the second parameter is greater than 0 and
3564       ** the sub-journal is not already open, then it will be opened here.
3565       */
3566       rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3567     }
3568   }
3569 
3570   btreeIntegrity(p);
3571   sqlite3BtreeLeave(p);
3572   return rc;
3573 }
3574 
3575 #ifndef SQLITE_OMIT_AUTOVACUUM
3576 
3577 /*
3578 ** Set the pointer-map entries for all children of page pPage. Also, if
3579 ** pPage contains cells that point to overflow pages, set the pointer
3580 ** map entries for the overflow pages as well.
3581 */
3582 static int setChildPtrmaps(MemPage *pPage){
3583   int i;                             /* Counter variable */
3584   int nCell;                         /* Number of cells in page pPage */
3585   int rc;                            /* Return code */
3586   BtShared *pBt = pPage->pBt;
3587   Pgno pgno = pPage->pgno;
3588 
3589   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3590   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3591   if( rc!=SQLITE_OK ) return rc;
3592   nCell = pPage->nCell;
3593 
3594   for(i=0; i<nCell; i++){
3595     u8 *pCell = findCell(pPage, i);
3596 
3597     ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3598 
3599     if( !pPage->leaf ){
3600       Pgno childPgno = get4byte(pCell);
3601       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3602     }
3603   }
3604 
3605   if( !pPage->leaf ){
3606     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3607     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3608   }
3609 
3610   return rc;
3611 }
3612 
3613 /*
3614 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
3615 ** that it points to iTo. Parameter eType describes the type of pointer to
3616 ** be modified, as  follows:
3617 **
3618 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
3619 **                   page of pPage.
3620 **
3621 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3622 **                   page pointed to by one of the cells on pPage.
3623 **
3624 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3625 **                   overflow page in the list.
3626 */
3627 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3628   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3629   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3630   if( eType==PTRMAP_OVERFLOW2 ){
3631     /* The pointer is always the first 4 bytes of the page in this case.  */
3632     if( get4byte(pPage->aData)!=iFrom ){
3633       return SQLITE_CORRUPT_PAGE(pPage);
3634     }
3635     put4byte(pPage->aData, iTo);
3636   }else{
3637     int i;
3638     int nCell;
3639     int rc;
3640 
3641     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3642     if( rc ) return rc;
3643     nCell = pPage->nCell;
3644 
3645     for(i=0; i<nCell; i++){
3646       u8 *pCell = findCell(pPage, i);
3647       if( eType==PTRMAP_OVERFLOW1 ){
3648         CellInfo info;
3649         pPage->xParseCell(pPage, pCell, &info);
3650         if( info.nLocal<info.nPayload ){
3651           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3652             return SQLITE_CORRUPT_PAGE(pPage);
3653           }
3654           if( iFrom==get4byte(pCell+info.nSize-4) ){
3655             put4byte(pCell+info.nSize-4, iTo);
3656             break;
3657           }
3658         }
3659       }else{
3660         if( get4byte(pCell)==iFrom ){
3661           put4byte(pCell, iTo);
3662           break;
3663         }
3664       }
3665     }
3666 
3667     if( i==nCell ){
3668       if( eType!=PTRMAP_BTREE ||
3669           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3670         return SQLITE_CORRUPT_PAGE(pPage);
3671       }
3672       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3673     }
3674   }
3675   return SQLITE_OK;
3676 }
3677 
3678 
3679 /*
3680 ** Move the open database page pDbPage to location iFreePage in the
3681 ** database. The pDbPage reference remains valid.
3682 **
3683 ** The isCommit flag indicates that there is no need to remember that
3684 ** the journal needs to be sync()ed before database page pDbPage->pgno
3685 ** can be written to. The caller has already promised not to write to that
3686 ** page.
3687 */
3688 static int relocatePage(
3689   BtShared *pBt,           /* Btree */
3690   MemPage *pDbPage,        /* Open page to move */
3691   u8 eType,                /* Pointer map 'type' entry for pDbPage */
3692   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
3693   Pgno iFreePage,          /* The location to move pDbPage to */
3694   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
3695 ){
3696   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
3697   Pgno iDbPage = pDbPage->pgno;
3698   Pager *pPager = pBt->pPager;
3699   int rc;
3700 
3701   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3702       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3703   assert( sqlite3_mutex_held(pBt->mutex) );
3704   assert( pDbPage->pBt==pBt );
3705   if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3706 
3707   /* Move page iDbPage from its current location to page number iFreePage */
3708   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3709       iDbPage, iFreePage, iPtrPage, eType));
3710   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3711   if( rc!=SQLITE_OK ){
3712     return rc;
3713   }
3714   pDbPage->pgno = iFreePage;
3715 
3716   /* If pDbPage was a btree-page, then it may have child pages and/or cells
3717   ** that point to overflow pages. The pointer map entries for all these
3718   ** pages need to be changed.
3719   **
3720   ** If pDbPage is an overflow page, then the first 4 bytes may store a
3721   ** pointer to a subsequent overflow page. If this is the case, then
3722   ** the pointer map needs to be updated for the subsequent overflow page.
3723   */
3724   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3725     rc = setChildPtrmaps(pDbPage);
3726     if( rc!=SQLITE_OK ){
3727       return rc;
3728     }
3729   }else{
3730     Pgno nextOvfl = get4byte(pDbPage->aData);
3731     if( nextOvfl!=0 ){
3732       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3733       if( rc!=SQLITE_OK ){
3734         return rc;
3735       }
3736     }
3737   }
3738 
3739   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3740   ** that it points at iFreePage. Also fix the pointer map entry for
3741   ** iPtrPage.
3742   */
3743   if( eType!=PTRMAP_ROOTPAGE ){
3744     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3745     if( rc!=SQLITE_OK ){
3746       return rc;
3747     }
3748     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3749     if( rc!=SQLITE_OK ){
3750       releasePage(pPtrPage);
3751       return rc;
3752     }
3753     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3754     releasePage(pPtrPage);
3755     if( rc==SQLITE_OK ){
3756       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3757     }
3758   }
3759   return rc;
3760 }
3761 
3762 /* Forward declaration required by incrVacuumStep(). */
3763 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3764 
3765 /*
3766 ** Perform a single step of an incremental-vacuum. If successful, return
3767 ** SQLITE_OK. If there is no work to do (and therefore no point in
3768 ** calling this function again), return SQLITE_DONE. Or, if an error
3769 ** occurs, return some other error code.
3770 **
3771 ** More specifically, this function attempts to re-organize the database so
3772 ** that the last page of the file currently in use is no longer in use.
3773 **
3774 ** Parameter nFin is the number of pages that this database would contain
3775 ** were this function called until it returns SQLITE_DONE.
3776 **
3777 ** If the bCommit parameter is non-zero, this function assumes that the
3778 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3779 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3780 ** operation, or false for an incremental vacuum.
3781 */
3782 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3783   Pgno nFreeList;           /* Number of pages still on the free-list */
3784   int rc;
3785 
3786   assert( sqlite3_mutex_held(pBt->mutex) );
3787   assert( iLastPg>nFin );
3788 
3789   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3790     u8 eType;
3791     Pgno iPtrPage;
3792 
3793     nFreeList = get4byte(&pBt->pPage1->aData[36]);
3794     if( nFreeList==0 ){
3795       return SQLITE_DONE;
3796     }
3797 
3798     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3799     if( rc!=SQLITE_OK ){
3800       return rc;
3801     }
3802     if( eType==PTRMAP_ROOTPAGE ){
3803       return SQLITE_CORRUPT_BKPT;
3804     }
3805 
3806     if( eType==PTRMAP_FREEPAGE ){
3807       if( bCommit==0 ){
3808         /* Remove the page from the files free-list. This is not required
3809         ** if bCommit is non-zero. In that case, the free-list will be
3810         ** truncated to zero after this function returns, so it doesn't
3811         ** matter if it still contains some garbage entries.
3812         */
3813         Pgno iFreePg;
3814         MemPage *pFreePg;
3815         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3816         if( rc!=SQLITE_OK ){
3817           return rc;
3818         }
3819         assert( iFreePg==iLastPg );
3820         releasePage(pFreePg);
3821       }
3822     } else {
3823       Pgno iFreePg;             /* Index of free page to move pLastPg to */
3824       MemPage *pLastPg;
3825       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
3826       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
3827 
3828       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3829       if( rc!=SQLITE_OK ){
3830         return rc;
3831       }
3832 
3833       /* If bCommit is zero, this loop runs exactly once and page pLastPg
3834       ** is swapped with the first free page pulled off the free list.
3835       **
3836       ** On the other hand, if bCommit is greater than zero, then keep
3837       ** looping until a free-page located within the first nFin pages
3838       ** of the file is found.
3839       */
3840       if( bCommit==0 ){
3841         eMode = BTALLOC_LE;
3842         iNear = nFin;
3843       }
3844       do {
3845         MemPage *pFreePg;
3846         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3847         if( rc!=SQLITE_OK ){
3848           releasePage(pLastPg);
3849           return rc;
3850         }
3851         releasePage(pFreePg);
3852       }while( bCommit && iFreePg>nFin );
3853       assert( iFreePg<iLastPg );
3854 
3855       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3856       releasePage(pLastPg);
3857       if( rc!=SQLITE_OK ){
3858         return rc;
3859       }
3860     }
3861   }
3862 
3863   if( bCommit==0 ){
3864     do {
3865       iLastPg--;
3866     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3867     pBt->bDoTruncate = 1;
3868     pBt->nPage = iLastPg;
3869   }
3870   return SQLITE_OK;
3871 }
3872 
3873 /*
3874 ** The database opened by the first argument is an auto-vacuum database
3875 ** nOrig pages in size containing nFree free pages. Return the expected
3876 ** size of the database in pages following an auto-vacuum operation.
3877 */
3878 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3879   int nEntry;                     /* Number of entries on one ptrmap page */
3880   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
3881   Pgno nFin;                      /* Return value */
3882 
3883   nEntry = pBt->usableSize/5;
3884   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3885   nFin = nOrig - nFree - nPtrmap;
3886   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3887     nFin--;
3888   }
3889   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3890     nFin--;
3891   }
3892 
3893   return nFin;
3894 }
3895 
3896 /*
3897 ** A write-transaction must be opened before calling this function.
3898 ** It performs a single unit of work towards an incremental vacuum.
3899 **
3900 ** If the incremental vacuum is finished after this function has run,
3901 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3902 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3903 */
3904 int sqlite3BtreeIncrVacuum(Btree *p){
3905   int rc;
3906   BtShared *pBt = p->pBt;
3907 
3908   sqlite3BtreeEnter(p);
3909   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3910   if( !pBt->autoVacuum ){
3911     rc = SQLITE_DONE;
3912   }else{
3913     Pgno nOrig = btreePagecount(pBt);
3914     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3915     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3916 
3917     if( nOrig<nFin || nFree>=nOrig ){
3918       rc = SQLITE_CORRUPT_BKPT;
3919     }else if( nFree>0 ){
3920       rc = saveAllCursors(pBt, 0, 0);
3921       if( rc==SQLITE_OK ){
3922         invalidateAllOverflowCache(pBt);
3923         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3924       }
3925       if( rc==SQLITE_OK ){
3926         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3927         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3928       }
3929     }else{
3930       rc = SQLITE_DONE;
3931     }
3932   }
3933   sqlite3BtreeLeave(p);
3934   return rc;
3935 }
3936 
3937 /*
3938 ** This routine is called prior to sqlite3PagerCommit when a transaction
3939 ** is committed for an auto-vacuum database.
3940 **
3941 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3942 ** the database file should be truncated to during the commit process.
3943 ** i.e. the database has been reorganized so that only the first *pnTrunc
3944 ** pages are in use.
3945 */
3946 static int autoVacuumCommit(BtShared *pBt){
3947   int rc = SQLITE_OK;
3948   Pager *pPager = pBt->pPager;
3949   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3950 
3951   assert( sqlite3_mutex_held(pBt->mutex) );
3952   invalidateAllOverflowCache(pBt);
3953   assert(pBt->autoVacuum);
3954   if( !pBt->incrVacuum ){
3955     Pgno nFin;         /* Number of pages in database after autovacuuming */
3956     Pgno nFree;        /* Number of pages on the freelist initially */
3957     Pgno iFree;        /* The next page to be freed */
3958     Pgno nOrig;        /* Database size before freeing */
3959 
3960     nOrig = btreePagecount(pBt);
3961     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3962       /* It is not possible to create a database for which the final page
3963       ** is either a pointer-map page or the pending-byte page. If one
3964       ** is encountered, this indicates corruption.
3965       */
3966       return SQLITE_CORRUPT_BKPT;
3967     }
3968 
3969     nFree = get4byte(&pBt->pPage1->aData[36]);
3970     nFin = finalDbSize(pBt, nOrig, nFree);
3971     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3972     if( nFin<nOrig ){
3973       rc = saveAllCursors(pBt, 0, 0);
3974     }
3975     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3976       rc = incrVacuumStep(pBt, nFin, iFree, 1);
3977     }
3978     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3979       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3980       put4byte(&pBt->pPage1->aData[32], 0);
3981       put4byte(&pBt->pPage1->aData[36], 0);
3982       put4byte(&pBt->pPage1->aData[28], nFin);
3983       pBt->bDoTruncate = 1;
3984       pBt->nPage = nFin;
3985     }
3986     if( rc!=SQLITE_OK ){
3987       sqlite3PagerRollback(pPager);
3988     }
3989   }
3990 
3991   assert( nRef>=sqlite3PagerRefcount(pPager) );
3992   return rc;
3993 }
3994 
3995 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3996 # define setChildPtrmaps(x) SQLITE_OK
3997 #endif
3998 
3999 /*
4000 ** This routine does the first phase of a two-phase commit.  This routine
4001 ** causes a rollback journal to be created (if it does not already exist)
4002 ** and populated with enough information so that if a power loss occurs
4003 ** the database can be restored to its original state by playing back
4004 ** the journal.  Then the contents of the journal are flushed out to
4005 ** the disk.  After the journal is safely on oxide, the changes to the
4006 ** database are written into the database file and flushed to oxide.
4007 ** At the end of this call, the rollback journal still exists on the
4008 ** disk and we are still holding all locks, so the transaction has not
4009 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4010 ** commit process.
4011 **
4012 ** This call is a no-op if no write-transaction is currently active on pBt.
4013 **
4014 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4015 ** the name of a super-journal file that should be written into the
4016 ** individual journal file, or is NULL, indicating no super-journal file
4017 ** (single database transaction).
4018 **
4019 ** When this is called, the super-journal should already have been
4020 ** created, populated with this journal pointer and synced to disk.
4021 **
4022 ** Once this is routine has returned, the only thing required to commit
4023 ** the write-transaction for this database file is to delete the journal.
4024 */
4025 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4026   int rc = SQLITE_OK;
4027   if( p->inTrans==TRANS_WRITE ){
4028     BtShared *pBt = p->pBt;
4029     sqlite3BtreeEnter(p);
4030 #ifndef SQLITE_OMIT_AUTOVACUUM
4031     if( pBt->autoVacuum ){
4032       rc = autoVacuumCommit(pBt);
4033       if( rc!=SQLITE_OK ){
4034         sqlite3BtreeLeave(p);
4035         return rc;
4036       }
4037     }
4038     if( pBt->bDoTruncate ){
4039       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4040     }
4041 #endif
4042     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4043     sqlite3BtreeLeave(p);
4044   }
4045   return rc;
4046 }
4047 
4048 /*
4049 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4050 ** at the conclusion of a transaction.
4051 */
4052 static void btreeEndTransaction(Btree *p){
4053   BtShared *pBt = p->pBt;
4054   sqlite3 *db = p->db;
4055   assert( sqlite3BtreeHoldsMutex(p) );
4056 
4057 #ifndef SQLITE_OMIT_AUTOVACUUM
4058   pBt->bDoTruncate = 0;
4059 #endif
4060   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4061     /* If there are other active statements that belong to this database
4062     ** handle, downgrade to a read-only transaction. The other statements
4063     ** may still be reading from the database.  */
4064     downgradeAllSharedCacheTableLocks(p);
4065     p->inTrans = TRANS_READ;
4066   }else{
4067     /* If the handle had any kind of transaction open, decrement the
4068     ** transaction count of the shared btree. If the transaction count
4069     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4070     ** call below will unlock the pager.  */
4071     if( p->inTrans!=TRANS_NONE ){
4072       clearAllSharedCacheTableLocks(p);
4073       pBt->nTransaction--;
4074       if( 0==pBt->nTransaction ){
4075         pBt->inTransaction = TRANS_NONE;
4076       }
4077     }
4078 
4079     /* Set the current transaction state to TRANS_NONE and unlock the
4080     ** pager if this call closed the only read or write transaction.  */
4081     p->inTrans = TRANS_NONE;
4082     unlockBtreeIfUnused(pBt);
4083   }
4084 
4085   btreeIntegrity(p);
4086 }
4087 
4088 /*
4089 ** Commit the transaction currently in progress.
4090 **
4091 ** This routine implements the second phase of a 2-phase commit.  The
4092 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4093 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
4094 ** routine did all the work of writing information out to disk and flushing the
4095 ** contents so that they are written onto the disk platter.  All this
4096 ** routine has to do is delete or truncate or zero the header in the
4097 ** the rollback journal (which causes the transaction to commit) and
4098 ** drop locks.
4099 **
4100 ** Normally, if an error occurs while the pager layer is attempting to
4101 ** finalize the underlying journal file, this function returns an error and
4102 ** the upper layer will attempt a rollback. However, if the second argument
4103 ** is non-zero then this b-tree transaction is part of a multi-file
4104 ** transaction. In this case, the transaction has already been committed
4105 ** (by deleting a super-journal file) and the caller will ignore this
4106 ** functions return code. So, even if an error occurs in the pager layer,
4107 ** reset the b-tree objects internal state to indicate that the write
4108 ** transaction has been closed. This is quite safe, as the pager will have
4109 ** transitioned to the error state.
4110 **
4111 ** This will release the write lock on the database file.  If there
4112 ** are no active cursors, it also releases the read lock.
4113 */
4114 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4115 
4116   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4117   sqlite3BtreeEnter(p);
4118   btreeIntegrity(p);
4119 
4120   /* If the handle has a write-transaction open, commit the shared-btrees
4121   ** transaction and set the shared state to TRANS_READ.
4122   */
4123   if( p->inTrans==TRANS_WRITE ){
4124     int rc;
4125     BtShared *pBt = p->pBt;
4126     assert( pBt->inTransaction==TRANS_WRITE );
4127     assert( pBt->nTransaction>0 );
4128     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4129     if( rc!=SQLITE_OK && bCleanup==0 ){
4130       sqlite3BtreeLeave(p);
4131       return rc;
4132     }
4133     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
4134     pBt->inTransaction = TRANS_READ;
4135     btreeClearHasContent(pBt);
4136   }
4137 
4138   btreeEndTransaction(p);
4139   sqlite3BtreeLeave(p);
4140   return SQLITE_OK;
4141 }
4142 
4143 /*
4144 ** Do both phases of a commit.
4145 */
4146 int sqlite3BtreeCommit(Btree *p){
4147   int rc;
4148   sqlite3BtreeEnter(p);
4149   rc = sqlite3BtreeCommitPhaseOne(p, 0);
4150   if( rc==SQLITE_OK ){
4151     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4152   }
4153   sqlite3BtreeLeave(p);
4154   return rc;
4155 }
4156 
4157 /*
4158 ** This routine sets the state to CURSOR_FAULT and the error
4159 ** code to errCode for every cursor on any BtShared that pBtree
4160 ** references.  Or if the writeOnly flag is set to 1, then only
4161 ** trip write cursors and leave read cursors unchanged.
4162 **
4163 ** Every cursor is a candidate to be tripped, including cursors
4164 ** that belong to other database connections that happen to be
4165 ** sharing the cache with pBtree.
4166 **
4167 ** This routine gets called when a rollback occurs. If the writeOnly
4168 ** flag is true, then only write-cursors need be tripped - read-only
4169 ** cursors save their current positions so that they may continue
4170 ** following the rollback. Or, if writeOnly is false, all cursors are
4171 ** tripped. In general, writeOnly is false if the transaction being
4172 ** rolled back modified the database schema. In this case b-tree root
4173 ** pages may be moved or deleted from the database altogether, making
4174 ** it unsafe for read cursors to continue.
4175 **
4176 ** If the writeOnly flag is true and an error is encountered while
4177 ** saving the current position of a read-only cursor, all cursors,
4178 ** including all read-cursors are tripped.
4179 **
4180 ** SQLITE_OK is returned if successful, or if an error occurs while
4181 ** saving a cursor position, an SQLite error code.
4182 */
4183 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4184   BtCursor *p;
4185   int rc = SQLITE_OK;
4186 
4187   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4188   if( pBtree ){
4189     sqlite3BtreeEnter(pBtree);
4190     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4191       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4192         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4193           rc = saveCursorPosition(p);
4194           if( rc!=SQLITE_OK ){
4195             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4196             break;
4197           }
4198         }
4199       }else{
4200         sqlite3BtreeClearCursor(p);
4201         p->eState = CURSOR_FAULT;
4202         p->skipNext = errCode;
4203       }
4204       btreeReleaseAllCursorPages(p);
4205     }
4206     sqlite3BtreeLeave(pBtree);
4207   }
4208   return rc;
4209 }
4210 
4211 /*
4212 ** Set the pBt->nPage field correctly, according to the current
4213 ** state of the database.  Assume pBt->pPage1 is valid.
4214 */
4215 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4216   int nPage = get4byte(&pPage1->aData[28]);
4217   testcase( nPage==0 );
4218   if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4219   testcase( pBt->nPage!=nPage );
4220   pBt->nPage = nPage;
4221 }
4222 
4223 /*
4224 ** Rollback the transaction in progress.
4225 **
4226 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4227 ** Only write cursors are tripped if writeOnly is true but all cursors are
4228 ** tripped if writeOnly is false.  Any attempt to use
4229 ** a tripped cursor will result in an error.
4230 **
4231 ** This will release the write lock on the database file.  If there
4232 ** are no active cursors, it also releases the read lock.
4233 */
4234 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4235   int rc;
4236   BtShared *pBt = p->pBt;
4237   MemPage *pPage1;
4238 
4239   assert( writeOnly==1 || writeOnly==0 );
4240   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4241   sqlite3BtreeEnter(p);
4242   if( tripCode==SQLITE_OK ){
4243     rc = tripCode = saveAllCursors(pBt, 0, 0);
4244     if( rc ) writeOnly = 0;
4245   }else{
4246     rc = SQLITE_OK;
4247   }
4248   if( tripCode ){
4249     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4250     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4251     if( rc2!=SQLITE_OK ) rc = rc2;
4252   }
4253   btreeIntegrity(p);
4254 
4255   if( p->inTrans==TRANS_WRITE ){
4256     int rc2;
4257 
4258     assert( TRANS_WRITE==pBt->inTransaction );
4259     rc2 = sqlite3PagerRollback(pBt->pPager);
4260     if( rc2!=SQLITE_OK ){
4261       rc = rc2;
4262     }
4263 
4264     /* The rollback may have destroyed the pPage1->aData value.  So
4265     ** call btreeGetPage() on page 1 again to make
4266     ** sure pPage1->aData is set correctly. */
4267     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4268       btreeSetNPage(pBt, pPage1);
4269       releasePageOne(pPage1);
4270     }
4271     assert( countValidCursors(pBt, 1)==0 );
4272     pBt->inTransaction = TRANS_READ;
4273     btreeClearHasContent(pBt);
4274   }
4275 
4276   btreeEndTransaction(p);
4277   sqlite3BtreeLeave(p);
4278   return rc;
4279 }
4280 
4281 /*
4282 ** Start a statement subtransaction. The subtransaction can be rolled
4283 ** back independently of the main transaction. You must start a transaction
4284 ** before starting a subtransaction. The subtransaction is ended automatically
4285 ** if the main transaction commits or rolls back.
4286 **
4287 ** Statement subtransactions are used around individual SQL statements
4288 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4289 ** error occurs within the statement, the effect of that one statement
4290 ** can be rolled back without having to rollback the entire transaction.
4291 **
4292 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4293 ** value passed as the second parameter is the total number of savepoints,
4294 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4295 ** are no active savepoints and no other statement-transactions open,
4296 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4297 ** using the sqlite3BtreeSavepoint() function.
4298 */
4299 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4300   int rc;
4301   BtShared *pBt = p->pBt;
4302   sqlite3BtreeEnter(p);
4303   assert( p->inTrans==TRANS_WRITE );
4304   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4305   assert( iStatement>0 );
4306   assert( iStatement>p->db->nSavepoint );
4307   assert( pBt->inTransaction==TRANS_WRITE );
4308   /* At the pager level, a statement transaction is a savepoint with
4309   ** an index greater than all savepoints created explicitly using
4310   ** SQL statements. It is illegal to open, release or rollback any
4311   ** such savepoints while the statement transaction savepoint is active.
4312   */
4313   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4314   sqlite3BtreeLeave(p);
4315   return rc;
4316 }
4317 
4318 /*
4319 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4320 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4321 ** savepoint identified by parameter iSavepoint, depending on the value
4322 ** of op.
4323 **
4324 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4325 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4326 ** contents of the entire transaction are rolled back. This is different
4327 ** from a normal transaction rollback, as no locks are released and the
4328 ** transaction remains open.
4329 */
4330 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4331   int rc = SQLITE_OK;
4332   if( p && p->inTrans==TRANS_WRITE ){
4333     BtShared *pBt = p->pBt;
4334     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4335     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4336     sqlite3BtreeEnter(p);
4337     if( op==SAVEPOINT_ROLLBACK ){
4338       rc = saveAllCursors(pBt, 0, 0);
4339     }
4340     if( rc==SQLITE_OK ){
4341       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4342     }
4343     if( rc==SQLITE_OK ){
4344       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4345         pBt->nPage = 0;
4346       }
4347       rc = newDatabase(pBt);
4348       btreeSetNPage(pBt, pBt->pPage1);
4349 
4350       /* pBt->nPage might be zero if the database was corrupt when
4351       ** the transaction was started. Otherwise, it must be at least 1.  */
4352       assert( CORRUPT_DB || pBt->nPage>0 );
4353     }
4354     sqlite3BtreeLeave(p);
4355   }
4356   return rc;
4357 }
4358 
4359 /*
4360 ** Create a new cursor for the BTree whose root is on the page
4361 ** iTable. If a read-only cursor is requested, it is assumed that
4362 ** the caller already has at least a read-only transaction open
4363 ** on the database already. If a write-cursor is requested, then
4364 ** the caller is assumed to have an open write transaction.
4365 **
4366 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4367 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4368 ** can be used for reading or for writing if other conditions for writing
4369 ** are also met.  These are the conditions that must be met in order
4370 ** for writing to be allowed:
4371 **
4372 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4373 **
4374 ** 2:  Other database connections that share the same pager cache
4375 **     but which are not in the READ_UNCOMMITTED state may not have
4376 **     cursors open with wrFlag==0 on the same table.  Otherwise
4377 **     the changes made by this write cursor would be visible to
4378 **     the read cursors in the other database connection.
4379 **
4380 ** 3:  The database must be writable (not on read-only media)
4381 **
4382 ** 4:  There must be an active transaction.
4383 **
4384 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4385 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4386 ** this cursor will only be used to seek to and delete entries of an index
4387 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4388 ** this implementation.  But in a hypothetical alternative storage engine
4389 ** in which index entries are automatically deleted when corresponding table
4390 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4391 ** operations on this cursor can be no-ops and all READ operations can
4392 ** return a null row (2-bytes: 0x01 0x00).
4393 **
4394 ** No checking is done to make sure that page iTable really is the
4395 ** root page of a b-tree.  If it is not, then the cursor acquired
4396 ** will not work correctly.
4397 **
4398 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4399 ** on pCur to initialize the memory space prior to invoking this routine.
4400 */
4401 static int btreeCursor(
4402   Btree *p,                              /* The btree */
4403   Pgno iTable,                           /* Root page of table to open */
4404   int wrFlag,                            /* 1 to write. 0 read-only */
4405   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4406   BtCursor *pCur                         /* Space for new cursor */
4407 ){
4408   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4409   BtCursor *pX;                          /* Looping over other all cursors */
4410 
4411   assert( sqlite3BtreeHoldsMutex(p) );
4412   assert( wrFlag==0
4413        || wrFlag==BTREE_WRCSR
4414        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4415   );
4416 
4417   /* The following assert statements verify that if this is a sharable
4418   ** b-tree database, the connection is holding the required table locks,
4419   ** and that no other connection has any open cursor that conflicts with
4420   ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
4421   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4422           || iTable<1 );
4423   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4424 
4425   /* Assert that the caller has opened the required transaction. */
4426   assert( p->inTrans>TRANS_NONE );
4427   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4428   assert( pBt->pPage1 && pBt->pPage1->aData );
4429   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4430 
4431   if( wrFlag ){
4432     allocateTempSpace(pBt);
4433     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4434   }
4435   if( iTable<=1 ){
4436     if( iTable<1 ){
4437       return SQLITE_CORRUPT_BKPT;
4438     }else if( btreePagecount(pBt)==0 ){
4439       assert( wrFlag==0 );
4440       iTable = 0;
4441     }
4442   }
4443 
4444   /* Now that no other errors can occur, finish filling in the BtCursor
4445   ** variables and link the cursor into the BtShared list.  */
4446   pCur->pgnoRoot = iTable;
4447   pCur->iPage = -1;
4448   pCur->pKeyInfo = pKeyInfo;
4449   pCur->pBtree = p;
4450   pCur->pBt = pBt;
4451   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4452   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4453   /* If there are two or more cursors on the same btree, then all such
4454   ** cursors *must* have the BTCF_Multiple flag set. */
4455   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4456     if( pX->pgnoRoot==iTable ){
4457       pX->curFlags |= BTCF_Multiple;
4458       pCur->curFlags |= BTCF_Multiple;
4459     }
4460   }
4461   pCur->pNext = pBt->pCursor;
4462   pBt->pCursor = pCur;
4463   pCur->eState = CURSOR_INVALID;
4464   return SQLITE_OK;
4465 }
4466 static int btreeCursorWithLock(
4467   Btree *p,                              /* The btree */
4468   Pgno iTable,                           /* Root page of table to open */
4469   int wrFlag,                            /* 1 to write. 0 read-only */
4470   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4471   BtCursor *pCur                         /* Space for new cursor */
4472 ){
4473   int rc;
4474   sqlite3BtreeEnter(p);
4475   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4476   sqlite3BtreeLeave(p);
4477   return rc;
4478 }
4479 int sqlite3BtreeCursor(
4480   Btree *p,                                   /* The btree */
4481   Pgno iTable,                                /* Root page of table to open */
4482   int wrFlag,                                 /* 1 to write. 0 read-only */
4483   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4484   BtCursor *pCur                              /* Write new cursor here */
4485 ){
4486   if( p->sharable ){
4487     return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4488   }else{
4489     return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4490   }
4491 }
4492 
4493 /*
4494 ** Return the size of a BtCursor object in bytes.
4495 **
4496 ** This interfaces is needed so that users of cursors can preallocate
4497 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4498 ** to users so they cannot do the sizeof() themselves - they must call
4499 ** this routine.
4500 */
4501 int sqlite3BtreeCursorSize(void){
4502   return ROUND8(sizeof(BtCursor));
4503 }
4504 
4505 /*
4506 ** Initialize memory that will be converted into a BtCursor object.
4507 **
4508 ** The simple approach here would be to memset() the entire object
4509 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4510 ** do not need to be zeroed and they are large, so we can save a lot
4511 ** of run-time by skipping the initialization of those elements.
4512 */
4513 void sqlite3BtreeCursorZero(BtCursor *p){
4514   memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4515 }
4516 
4517 /*
4518 ** Close a cursor.  The read lock on the database file is released
4519 ** when the last cursor is closed.
4520 */
4521 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4522   Btree *pBtree = pCur->pBtree;
4523   if( pBtree ){
4524     BtShared *pBt = pCur->pBt;
4525     sqlite3BtreeEnter(pBtree);
4526     assert( pBt->pCursor!=0 );
4527     if( pBt->pCursor==pCur ){
4528       pBt->pCursor = pCur->pNext;
4529     }else{
4530       BtCursor *pPrev = pBt->pCursor;
4531       do{
4532         if( pPrev->pNext==pCur ){
4533           pPrev->pNext = pCur->pNext;
4534           break;
4535         }
4536         pPrev = pPrev->pNext;
4537       }while( ALWAYS(pPrev) );
4538     }
4539     btreeReleaseAllCursorPages(pCur);
4540     unlockBtreeIfUnused(pBt);
4541     sqlite3_free(pCur->aOverflow);
4542     sqlite3_free(pCur->pKey);
4543     sqlite3BtreeLeave(pBtree);
4544     pCur->pBtree = 0;
4545   }
4546   return SQLITE_OK;
4547 }
4548 
4549 /*
4550 ** Make sure the BtCursor* given in the argument has a valid
4551 ** BtCursor.info structure.  If it is not already valid, call
4552 ** btreeParseCell() to fill it in.
4553 **
4554 ** BtCursor.info is a cache of the information in the current cell.
4555 ** Using this cache reduces the number of calls to btreeParseCell().
4556 */
4557 #ifndef NDEBUG
4558   static int cellInfoEqual(CellInfo *a, CellInfo *b){
4559     if( a->nKey!=b->nKey ) return 0;
4560     if( a->pPayload!=b->pPayload ) return 0;
4561     if( a->nPayload!=b->nPayload ) return 0;
4562     if( a->nLocal!=b->nLocal ) return 0;
4563     if( a->nSize!=b->nSize ) return 0;
4564     return 1;
4565   }
4566   static void assertCellInfo(BtCursor *pCur){
4567     CellInfo info;
4568     memset(&info, 0, sizeof(info));
4569     btreeParseCell(pCur->pPage, pCur->ix, &info);
4570     assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4571   }
4572 #else
4573   #define assertCellInfo(x)
4574 #endif
4575 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4576   if( pCur->info.nSize==0 ){
4577     pCur->curFlags |= BTCF_ValidNKey;
4578     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4579   }else{
4580     assertCellInfo(pCur);
4581   }
4582 }
4583 
4584 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4585 /*
4586 ** Return true if the given BtCursor is valid.  A valid cursor is one
4587 ** that is currently pointing to a row in a (non-empty) table.
4588 ** This is a verification routine is used only within assert() statements.
4589 */
4590 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4591   return pCur && pCur->eState==CURSOR_VALID;
4592 }
4593 #endif /* NDEBUG */
4594 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4595   assert( pCur!=0 );
4596   return pCur->eState==CURSOR_VALID;
4597 }
4598 
4599 /*
4600 ** Return the value of the integer key or "rowid" for a table btree.
4601 ** This routine is only valid for a cursor that is pointing into a
4602 ** ordinary table btree.  If the cursor points to an index btree or
4603 ** is invalid, the result of this routine is undefined.
4604 */
4605 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4606   assert( cursorHoldsMutex(pCur) );
4607   assert( pCur->eState==CURSOR_VALID );
4608   assert( pCur->curIntKey );
4609   getCellInfo(pCur);
4610   return pCur->info.nKey;
4611 }
4612 
4613 /*
4614 ** Pin or unpin a cursor.
4615 */
4616 void sqlite3BtreeCursorPin(BtCursor *pCur){
4617   assert( (pCur->curFlags & BTCF_Pinned)==0 );
4618   pCur->curFlags |= BTCF_Pinned;
4619 }
4620 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4621   assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4622   pCur->curFlags &= ~BTCF_Pinned;
4623 }
4624 
4625 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4626 /*
4627 ** Return the offset into the database file for the start of the
4628 ** payload to which the cursor is pointing.
4629 */
4630 i64 sqlite3BtreeOffset(BtCursor *pCur){
4631   assert( cursorHoldsMutex(pCur) );
4632   assert( pCur->eState==CURSOR_VALID );
4633   getCellInfo(pCur);
4634   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4635          (i64)(pCur->info.pPayload - pCur->pPage->aData);
4636 }
4637 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4638 
4639 /*
4640 ** Return the number of bytes of payload for the entry that pCur is
4641 ** currently pointing to.  For table btrees, this will be the amount
4642 ** of data.  For index btrees, this will be the size of the key.
4643 **
4644 ** The caller must guarantee that the cursor is pointing to a non-NULL
4645 ** valid entry.  In other words, the calling procedure must guarantee
4646 ** that the cursor has Cursor.eState==CURSOR_VALID.
4647 */
4648 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4649   assert( cursorHoldsMutex(pCur) );
4650   assert( pCur->eState==CURSOR_VALID );
4651   getCellInfo(pCur);
4652   return pCur->info.nPayload;
4653 }
4654 
4655 /*
4656 ** Return an upper bound on the size of any record for the table
4657 ** that the cursor is pointing into.
4658 **
4659 ** This is an optimization.  Everything will still work if this
4660 ** routine always returns 2147483647 (which is the largest record
4661 ** that SQLite can handle) or more.  But returning a smaller value might
4662 ** prevent large memory allocations when trying to interpret a
4663 ** corrupt datrabase.
4664 **
4665 ** The current implementation merely returns the size of the underlying
4666 ** database file.
4667 */
4668 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4669   assert( cursorHoldsMutex(pCur) );
4670   assert( pCur->eState==CURSOR_VALID );
4671   return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4672 }
4673 
4674 /*
4675 ** Given the page number of an overflow page in the database (parameter
4676 ** ovfl), this function finds the page number of the next page in the
4677 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4678 ** pointer-map data instead of reading the content of page ovfl to do so.
4679 **
4680 ** If an error occurs an SQLite error code is returned. Otherwise:
4681 **
4682 ** The page number of the next overflow page in the linked list is
4683 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4684 ** list, *pPgnoNext is set to zero.
4685 **
4686 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4687 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4688 ** reference. It is the responsibility of the caller to call releasePage()
4689 ** on *ppPage to free the reference. In no reference was obtained (because
4690 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4691 ** *ppPage is set to zero.
4692 */
4693 static int getOverflowPage(
4694   BtShared *pBt,               /* The database file */
4695   Pgno ovfl,                   /* Current overflow page number */
4696   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4697   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4698 ){
4699   Pgno next = 0;
4700   MemPage *pPage = 0;
4701   int rc = SQLITE_OK;
4702 
4703   assert( sqlite3_mutex_held(pBt->mutex) );
4704   assert(pPgnoNext);
4705 
4706 #ifndef SQLITE_OMIT_AUTOVACUUM
4707   /* Try to find the next page in the overflow list using the
4708   ** autovacuum pointer-map pages. Guess that the next page in
4709   ** the overflow list is page number (ovfl+1). If that guess turns
4710   ** out to be wrong, fall back to loading the data of page
4711   ** number ovfl to determine the next page number.
4712   */
4713   if( pBt->autoVacuum ){
4714     Pgno pgno;
4715     Pgno iGuess = ovfl+1;
4716     u8 eType;
4717 
4718     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4719       iGuess++;
4720     }
4721 
4722     if( iGuess<=btreePagecount(pBt) ){
4723       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4724       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4725         next = iGuess;
4726         rc = SQLITE_DONE;
4727       }
4728     }
4729   }
4730 #endif
4731 
4732   assert( next==0 || rc==SQLITE_DONE );
4733   if( rc==SQLITE_OK ){
4734     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4735     assert( rc==SQLITE_OK || pPage==0 );
4736     if( rc==SQLITE_OK ){
4737       next = get4byte(pPage->aData);
4738     }
4739   }
4740 
4741   *pPgnoNext = next;
4742   if( ppPage ){
4743     *ppPage = pPage;
4744   }else{
4745     releasePage(pPage);
4746   }
4747   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4748 }
4749 
4750 /*
4751 ** Copy data from a buffer to a page, or from a page to a buffer.
4752 **
4753 ** pPayload is a pointer to data stored on database page pDbPage.
4754 ** If argument eOp is false, then nByte bytes of data are copied
4755 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4756 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4757 ** of data are copied from the buffer pBuf to pPayload.
4758 **
4759 ** SQLITE_OK is returned on success, otherwise an error code.
4760 */
4761 static int copyPayload(
4762   void *pPayload,           /* Pointer to page data */
4763   void *pBuf,               /* Pointer to buffer */
4764   int nByte,                /* Number of bytes to copy */
4765   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4766   DbPage *pDbPage           /* Page containing pPayload */
4767 ){
4768   if( eOp ){
4769     /* Copy data from buffer to page (a write operation) */
4770     int rc = sqlite3PagerWrite(pDbPage);
4771     if( rc!=SQLITE_OK ){
4772       return rc;
4773     }
4774     memcpy(pPayload, pBuf, nByte);
4775   }else{
4776     /* Copy data from page to buffer (a read operation) */
4777     memcpy(pBuf, pPayload, nByte);
4778   }
4779   return SQLITE_OK;
4780 }
4781 
4782 /*
4783 ** This function is used to read or overwrite payload information
4784 ** for the entry that the pCur cursor is pointing to. The eOp
4785 ** argument is interpreted as follows:
4786 **
4787 **   0: The operation is a read. Populate the overflow cache.
4788 **   1: The operation is a write. Populate the overflow cache.
4789 **
4790 ** A total of "amt" bytes are read or written beginning at "offset".
4791 ** Data is read to or from the buffer pBuf.
4792 **
4793 ** The content being read or written might appear on the main page
4794 ** or be scattered out on multiple overflow pages.
4795 **
4796 ** If the current cursor entry uses one or more overflow pages
4797 ** this function may allocate space for and lazily populate
4798 ** the overflow page-list cache array (BtCursor.aOverflow).
4799 ** Subsequent calls use this cache to make seeking to the supplied offset
4800 ** more efficient.
4801 **
4802 ** Once an overflow page-list cache has been allocated, it must be
4803 ** invalidated if some other cursor writes to the same table, or if
4804 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4805 ** mode, the following events may invalidate an overflow page-list cache.
4806 **
4807 **   * An incremental vacuum,
4808 **   * A commit in auto_vacuum="full" mode,
4809 **   * Creating a table (may require moving an overflow page).
4810 */
4811 static int accessPayload(
4812   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4813   u32 offset,          /* Begin reading this far into payload */
4814   u32 amt,             /* Read this many bytes */
4815   unsigned char *pBuf, /* Write the bytes into this buffer */
4816   int eOp              /* zero to read. non-zero to write. */
4817 ){
4818   unsigned char *aPayload;
4819   int rc = SQLITE_OK;
4820   int iIdx = 0;
4821   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
4822   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4823 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4824   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4825 #endif
4826 
4827   assert( pPage );
4828   assert( eOp==0 || eOp==1 );
4829   assert( pCur->eState==CURSOR_VALID );
4830   assert( pCur->ix<pPage->nCell );
4831   assert( cursorHoldsMutex(pCur) );
4832 
4833   getCellInfo(pCur);
4834   aPayload = pCur->info.pPayload;
4835   assert( offset+amt <= pCur->info.nPayload );
4836 
4837   assert( aPayload > pPage->aData );
4838   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4839     /* Trying to read or write past the end of the data is an error.  The
4840     ** conditional above is really:
4841     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4842     ** but is recast into its current form to avoid integer overflow problems
4843     */
4844     return SQLITE_CORRUPT_PAGE(pPage);
4845   }
4846 
4847   /* Check if data must be read/written to/from the btree page itself. */
4848   if( offset<pCur->info.nLocal ){
4849     int a = amt;
4850     if( a+offset>pCur->info.nLocal ){
4851       a = pCur->info.nLocal - offset;
4852     }
4853     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4854     offset = 0;
4855     pBuf += a;
4856     amt -= a;
4857   }else{
4858     offset -= pCur->info.nLocal;
4859   }
4860 
4861 
4862   if( rc==SQLITE_OK && amt>0 ){
4863     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4864     Pgno nextPage;
4865 
4866     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4867 
4868     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4869     **
4870     ** The aOverflow[] array is sized at one entry for each overflow page
4871     ** in the overflow chain. The page number of the first overflow page is
4872     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4873     ** means "not yet known" (the cache is lazily populated).
4874     */
4875     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4876       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4877       if( pCur->aOverflow==0
4878        || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4879       ){
4880         Pgno *aNew = (Pgno*)sqlite3Realloc(
4881             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4882         );
4883         if( aNew==0 ){
4884           return SQLITE_NOMEM_BKPT;
4885         }else{
4886           pCur->aOverflow = aNew;
4887         }
4888       }
4889       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4890       pCur->curFlags |= BTCF_ValidOvfl;
4891     }else{
4892       /* If the overflow page-list cache has been allocated and the
4893       ** entry for the first required overflow page is valid, skip
4894       ** directly to it.
4895       */
4896       if( pCur->aOverflow[offset/ovflSize] ){
4897         iIdx = (offset/ovflSize);
4898         nextPage = pCur->aOverflow[iIdx];
4899         offset = (offset%ovflSize);
4900       }
4901     }
4902 
4903     assert( rc==SQLITE_OK && amt>0 );
4904     while( nextPage ){
4905       /* If required, populate the overflow page-list cache. */
4906       if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4907       assert( pCur->aOverflow[iIdx]==0
4908               || pCur->aOverflow[iIdx]==nextPage
4909               || CORRUPT_DB );
4910       pCur->aOverflow[iIdx] = nextPage;
4911 
4912       if( offset>=ovflSize ){
4913         /* The only reason to read this page is to obtain the page
4914         ** number for the next page in the overflow chain. The page
4915         ** data is not required. So first try to lookup the overflow
4916         ** page-list cache, if any, then fall back to the getOverflowPage()
4917         ** function.
4918         */
4919         assert( pCur->curFlags & BTCF_ValidOvfl );
4920         assert( pCur->pBtree->db==pBt->db );
4921         if( pCur->aOverflow[iIdx+1] ){
4922           nextPage = pCur->aOverflow[iIdx+1];
4923         }else{
4924           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4925         }
4926         offset -= ovflSize;
4927       }else{
4928         /* Need to read this page properly. It contains some of the
4929         ** range of data that is being read (eOp==0) or written (eOp!=0).
4930         */
4931         int a = amt;
4932         if( a + offset > ovflSize ){
4933           a = ovflSize - offset;
4934         }
4935 
4936 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4937         /* If all the following are true:
4938         **
4939         **   1) this is a read operation, and
4940         **   2) data is required from the start of this overflow page, and
4941         **   3) there are no dirty pages in the page-cache
4942         **   4) the database is file-backed, and
4943         **   5) the page is not in the WAL file
4944         **   6) at least 4 bytes have already been read into the output buffer
4945         **
4946         ** then data can be read directly from the database file into the
4947         ** output buffer, bypassing the page-cache altogether. This speeds
4948         ** up loading large records that span many overflow pages.
4949         */
4950         if( eOp==0                                             /* (1) */
4951          && offset==0                                          /* (2) */
4952          && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
4953          && &pBuf[-4]>=pBufStart                               /* (6) */
4954         ){
4955           sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4956           u8 aSave[4];
4957           u8 *aWrite = &pBuf[-4];
4958           assert( aWrite>=pBufStart );                         /* due to (6) */
4959           memcpy(aSave, aWrite, 4);
4960           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4961           if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
4962           nextPage = get4byte(aWrite);
4963           memcpy(aWrite, aSave, 4);
4964         }else
4965 #endif
4966 
4967         {
4968           DbPage *pDbPage;
4969           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4970               (eOp==0 ? PAGER_GET_READONLY : 0)
4971           );
4972           if( rc==SQLITE_OK ){
4973             aPayload = sqlite3PagerGetData(pDbPage);
4974             nextPage = get4byte(aPayload);
4975             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4976             sqlite3PagerUnref(pDbPage);
4977             offset = 0;
4978           }
4979         }
4980         amt -= a;
4981         if( amt==0 ) return rc;
4982         pBuf += a;
4983       }
4984       if( rc ) break;
4985       iIdx++;
4986     }
4987   }
4988 
4989   if( rc==SQLITE_OK && amt>0 ){
4990     /* Overflow chain ends prematurely */
4991     return SQLITE_CORRUPT_PAGE(pPage);
4992   }
4993   return rc;
4994 }
4995 
4996 /*
4997 ** Read part of the payload for the row at which that cursor pCur is currently
4998 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
4999 ** begins at "offset".
5000 **
5001 ** pCur can be pointing to either a table or an index b-tree.
5002 ** If pointing to a table btree, then the content section is read.  If
5003 ** pCur is pointing to an index b-tree then the key section is read.
5004 **
5005 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5006 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
5007 ** cursor might be invalid or might need to be restored before being read.
5008 **
5009 ** Return SQLITE_OK on success or an error code if anything goes
5010 ** wrong.  An error is returned if "offset+amt" is larger than
5011 ** the available payload.
5012 */
5013 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5014   assert( cursorHoldsMutex(pCur) );
5015   assert( pCur->eState==CURSOR_VALID );
5016   assert( pCur->iPage>=0 && pCur->pPage );
5017   assert( pCur->ix<pCur->pPage->nCell );
5018   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5019 }
5020 
5021 /*
5022 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5023 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
5024 ** interface.
5025 */
5026 #ifndef SQLITE_OMIT_INCRBLOB
5027 static SQLITE_NOINLINE int accessPayloadChecked(
5028   BtCursor *pCur,
5029   u32 offset,
5030   u32 amt,
5031   void *pBuf
5032 ){
5033   int rc;
5034   if ( pCur->eState==CURSOR_INVALID ){
5035     return SQLITE_ABORT;
5036   }
5037   assert( cursorOwnsBtShared(pCur) );
5038   rc = btreeRestoreCursorPosition(pCur);
5039   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5040 }
5041 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5042   if( pCur->eState==CURSOR_VALID ){
5043     assert( cursorOwnsBtShared(pCur) );
5044     return accessPayload(pCur, offset, amt, pBuf, 0);
5045   }else{
5046     return accessPayloadChecked(pCur, offset, amt, pBuf);
5047   }
5048 }
5049 #endif /* SQLITE_OMIT_INCRBLOB */
5050 
5051 /*
5052 ** Return a pointer to payload information from the entry that the
5053 ** pCur cursor is pointing to.  The pointer is to the beginning of
5054 ** the key if index btrees (pPage->intKey==0) and is the data for
5055 ** table btrees (pPage->intKey==1). The number of bytes of available
5056 ** key/data is written into *pAmt.  If *pAmt==0, then the value
5057 ** returned will not be a valid pointer.
5058 **
5059 ** This routine is an optimization.  It is common for the entire key
5060 ** and data to fit on the local page and for there to be no overflow
5061 ** pages.  When that is so, this routine can be used to access the
5062 ** key and data without making a copy.  If the key and/or data spills
5063 ** onto overflow pages, then accessPayload() must be used to reassemble
5064 ** the key/data and copy it into a preallocated buffer.
5065 **
5066 ** The pointer returned by this routine looks directly into the cached
5067 ** page of the database.  The data might change or move the next time
5068 ** any btree routine is called.
5069 */
5070 static const void *fetchPayload(
5071   BtCursor *pCur,      /* Cursor pointing to entry to read from */
5072   u32 *pAmt            /* Write the number of available bytes here */
5073 ){
5074   int amt;
5075   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5076   assert( pCur->eState==CURSOR_VALID );
5077   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5078   assert( cursorOwnsBtShared(pCur) );
5079   assert( pCur->ix<pCur->pPage->nCell );
5080   assert( pCur->info.nSize>0 );
5081   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5082   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5083   amt = pCur->info.nLocal;
5084   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5085     /* There is too little space on the page for the expected amount
5086     ** of local content. Database must be corrupt. */
5087     assert( CORRUPT_DB );
5088     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5089   }
5090   *pAmt = (u32)amt;
5091   return (void*)pCur->info.pPayload;
5092 }
5093 
5094 
5095 /*
5096 ** For the entry that cursor pCur is point to, return as
5097 ** many bytes of the key or data as are available on the local
5098 ** b-tree page.  Write the number of available bytes into *pAmt.
5099 **
5100 ** The pointer returned is ephemeral.  The key/data may move
5101 ** or be destroyed on the next call to any Btree routine,
5102 ** including calls from other threads against the same cache.
5103 ** Hence, a mutex on the BtShared should be held prior to calling
5104 ** this routine.
5105 **
5106 ** These routines is used to get quick access to key and data
5107 ** in the common case where no overflow pages are used.
5108 */
5109 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5110   return fetchPayload(pCur, pAmt);
5111 }
5112 
5113 
5114 /*
5115 ** Move the cursor down to a new child page.  The newPgno argument is the
5116 ** page number of the child page to move to.
5117 **
5118 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5119 ** the new child page does not match the flags field of the parent (i.e.
5120 ** if an intkey page appears to be the parent of a non-intkey page, or
5121 ** vice-versa).
5122 */
5123 static int moveToChild(BtCursor *pCur, u32 newPgno){
5124   BtShared *pBt = pCur->pBt;
5125 
5126   assert( cursorOwnsBtShared(pCur) );
5127   assert( pCur->eState==CURSOR_VALID );
5128   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5129   assert( pCur->iPage>=0 );
5130   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5131     return SQLITE_CORRUPT_BKPT;
5132   }
5133   pCur->info.nSize = 0;
5134   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5135   pCur->aiIdx[pCur->iPage] = pCur->ix;
5136   pCur->apPage[pCur->iPage] = pCur->pPage;
5137   pCur->ix = 0;
5138   pCur->iPage++;
5139   return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5140 }
5141 
5142 #ifdef SQLITE_DEBUG
5143 /*
5144 ** Page pParent is an internal (non-leaf) tree page. This function
5145 ** asserts that page number iChild is the left-child if the iIdx'th
5146 ** cell in page pParent. Or, if iIdx is equal to the total number of
5147 ** cells in pParent, that page number iChild is the right-child of
5148 ** the page.
5149 */
5150 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5151   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
5152                             ** in a corrupt database */
5153   assert( iIdx<=pParent->nCell );
5154   if( iIdx==pParent->nCell ){
5155     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5156   }else{
5157     assert( get4byte(findCell(pParent, iIdx))==iChild );
5158   }
5159 }
5160 #else
5161 #  define assertParentIndex(x,y,z)
5162 #endif
5163 
5164 /*
5165 ** Move the cursor up to the parent page.
5166 **
5167 ** pCur->idx is set to the cell index that contains the pointer
5168 ** to the page we are coming from.  If we are coming from the
5169 ** right-most child page then pCur->idx is set to one more than
5170 ** the largest cell index.
5171 */
5172 static void moveToParent(BtCursor *pCur){
5173   MemPage *pLeaf;
5174   assert( cursorOwnsBtShared(pCur) );
5175   assert( pCur->eState==CURSOR_VALID );
5176   assert( pCur->iPage>0 );
5177   assert( pCur->pPage );
5178   assertParentIndex(
5179     pCur->apPage[pCur->iPage-1],
5180     pCur->aiIdx[pCur->iPage-1],
5181     pCur->pPage->pgno
5182   );
5183   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5184   pCur->info.nSize = 0;
5185   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5186   pCur->ix = pCur->aiIdx[pCur->iPage-1];
5187   pLeaf = pCur->pPage;
5188   pCur->pPage = pCur->apPage[--pCur->iPage];
5189   releasePageNotNull(pLeaf);
5190 }
5191 
5192 /*
5193 ** Move the cursor to point to the root page of its b-tree structure.
5194 **
5195 ** If the table has a virtual root page, then the cursor is moved to point
5196 ** to the virtual root page instead of the actual root page. A table has a
5197 ** virtual root page when the actual root page contains no cells and a
5198 ** single child page. This can only happen with the table rooted at page 1.
5199 **
5200 ** If the b-tree structure is empty, the cursor state is set to
5201 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5202 ** the cursor is set to point to the first cell located on the root
5203 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5204 **
5205 ** If this function returns successfully, it may be assumed that the
5206 ** page-header flags indicate that the [virtual] root-page is the expected
5207 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5208 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5209 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5210 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5211 ** b-tree).
5212 */
5213 static int moveToRoot(BtCursor *pCur){
5214   MemPage *pRoot;
5215   int rc = SQLITE_OK;
5216 
5217   assert( cursorOwnsBtShared(pCur) );
5218   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5219   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
5220   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
5221   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5222   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5223 
5224   if( pCur->iPage>=0 ){
5225     if( pCur->iPage ){
5226       releasePageNotNull(pCur->pPage);
5227       while( --pCur->iPage ){
5228         releasePageNotNull(pCur->apPage[pCur->iPage]);
5229       }
5230       pCur->pPage = pCur->apPage[0];
5231       goto skip_init;
5232     }
5233   }else if( pCur->pgnoRoot==0 ){
5234     pCur->eState = CURSOR_INVALID;
5235     return SQLITE_EMPTY;
5236   }else{
5237     assert( pCur->iPage==(-1) );
5238     if( pCur->eState>=CURSOR_REQUIRESEEK ){
5239       if( pCur->eState==CURSOR_FAULT ){
5240         assert( pCur->skipNext!=SQLITE_OK );
5241         return pCur->skipNext;
5242       }
5243       sqlite3BtreeClearCursor(pCur);
5244     }
5245     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5246                         0, pCur->curPagerFlags);
5247     if( rc!=SQLITE_OK ){
5248       pCur->eState = CURSOR_INVALID;
5249       return rc;
5250     }
5251     pCur->iPage = 0;
5252     pCur->curIntKey = pCur->pPage->intKey;
5253   }
5254   pRoot = pCur->pPage;
5255   assert( pRoot->pgno==pCur->pgnoRoot );
5256 
5257   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5258   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5259   ** NULL, the caller expects a table b-tree. If this is not the case,
5260   ** return an SQLITE_CORRUPT error.
5261   **
5262   ** Earlier versions of SQLite assumed that this test could not fail
5263   ** if the root page was already loaded when this function was called (i.e.
5264   ** if pCur->iPage>=0). But this is not so if the database is corrupted
5265   ** in such a way that page pRoot is linked into a second b-tree table
5266   ** (or the freelist).  */
5267   assert( pRoot->intKey==1 || pRoot->intKey==0 );
5268   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5269     return SQLITE_CORRUPT_PAGE(pCur->pPage);
5270   }
5271 
5272 skip_init:
5273   pCur->ix = 0;
5274   pCur->info.nSize = 0;
5275   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5276 
5277   pRoot = pCur->pPage;
5278   if( pRoot->nCell>0 ){
5279     pCur->eState = CURSOR_VALID;
5280   }else if( !pRoot->leaf ){
5281     Pgno subpage;
5282     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5283     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5284     pCur->eState = CURSOR_VALID;
5285     rc = moveToChild(pCur, subpage);
5286   }else{
5287     pCur->eState = CURSOR_INVALID;
5288     rc = SQLITE_EMPTY;
5289   }
5290   return rc;
5291 }
5292 
5293 /*
5294 ** Move the cursor down to the left-most leaf entry beneath the
5295 ** entry to which it is currently pointing.
5296 **
5297 ** The left-most leaf is the one with the smallest key - the first
5298 ** in ascending order.
5299 */
5300 static int moveToLeftmost(BtCursor *pCur){
5301   Pgno pgno;
5302   int rc = SQLITE_OK;
5303   MemPage *pPage;
5304 
5305   assert( cursorOwnsBtShared(pCur) );
5306   assert( pCur->eState==CURSOR_VALID );
5307   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5308     assert( pCur->ix<pPage->nCell );
5309     pgno = get4byte(findCell(pPage, pCur->ix));
5310     rc = moveToChild(pCur, pgno);
5311   }
5312   return rc;
5313 }
5314 
5315 /*
5316 ** Move the cursor down to the right-most leaf entry beneath the
5317 ** page to which it is currently pointing.  Notice the difference
5318 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5319 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5320 ** finds the right-most entry beneath the *page*.
5321 **
5322 ** The right-most entry is the one with the largest key - the last
5323 ** key in ascending order.
5324 */
5325 static int moveToRightmost(BtCursor *pCur){
5326   Pgno pgno;
5327   int rc = SQLITE_OK;
5328   MemPage *pPage = 0;
5329 
5330   assert( cursorOwnsBtShared(pCur) );
5331   assert( pCur->eState==CURSOR_VALID );
5332   while( !(pPage = pCur->pPage)->leaf ){
5333     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5334     pCur->ix = pPage->nCell;
5335     rc = moveToChild(pCur, pgno);
5336     if( rc ) return rc;
5337   }
5338   pCur->ix = pPage->nCell-1;
5339   assert( pCur->info.nSize==0 );
5340   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5341   return SQLITE_OK;
5342 }
5343 
5344 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5345 ** on success.  Set *pRes to 0 if the cursor actually points to something
5346 ** or set *pRes to 1 if the table is empty.
5347 */
5348 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5349   int rc;
5350 
5351   assert( cursorOwnsBtShared(pCur) );
5352   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5353   rc = moveToRoot(pCur);
5354   if( rc==SQLITE_OK ){
5355     assert( pCur->pPage->nCell>0 );
5356     *pRes = 0;
5357     rc = moveToLeftmost(pCur);
5358   }else if( rc==SQLITE_EMPTY ){
5359     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5360     *pRes = 1;
5361     rc = SQLITE_OK;
5362   }
5363   return rc;
5364 }
5365 
5366 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5367 ** on success.  Set *pRes to 0 if the cursor actually points to something
5368 ** or set *pRes to 1 if the table is empty.
5369 */
5370 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5371   int rc;
5372 
5373   assert( cursorOwnsBtShared(pCur) );
5374   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5375 
5376   /* If the cursor already points to the last entry, this is a no-op. */
5377   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5378 #ifdef SQLITE_DEBUG
5379     /* This block serves to assert() that the cursor really does point
5380     ** to the last entry in the b-tree. */
5381     int ii;
5382     for(ii=0; ii<pCur->iPage; ii++){
5383       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5384     }
5385     assert( pCur->ix==pCur->pPage->nCell-1 );
5386     assert( pCur->pPage->leaf );
5387 #endif
5388     *pRes = 0;
5389     return SQLITE_OK;
5390   }
5391 
5392   rc = moveToRoot(pCur);
5393   if( rc==SQLITE_OK ){
5394     assert( pCur->eState==CURSOR_VALID );
5395     *pRes = 0;
5396     rc = moveToRightmost(pCur);
5397     if( rc==SQLITE_OK ){
5398       pCur->curFlags |= BTCF_AtLast;
5399     }else{
5400       pCur->curFlags &= ~BTCF_AtLast;
5401     }
5402   }else if( rc==SQLITE_EMPTY ){
5403     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5404     *pRes = 1;
5405     rc = SQLITE_OK;
5406   }
5407   return rc;
5408 }
5409 
5410 /* Move the cursor so that it points to an entry near the key
5411 ** specified by pIdxKey or intKey.   Return a success code.
5412 **
5413 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
5414 ** must be NULL.  For index tables, pIdxKey is used and intKey
5415 ** is ignored.
5416 **
5417 ** If an exact match is not found, then the cursor is always
5418 ** left pointing at a leaf page which would hold the entry if it
5419 ** were present.  The cursor might point to an entry that comes
5420 ** before or after the key.
5421 **
5422 ** An integer is written into *pRes which is the result of
5423 ** comparing the key with the entry to which the cursor is
5424 ** pointing.  The meaning of the integer written into
5425 ** *pRes is as follows:
5426 **
5427 **     *pRes<0      The cursor is left pointing at an entry that
5428 **                  is smaller than intKey/pIdxKey or if the table is empty
5429 **                  and the cursor is therefore left point to nothing.
5430 **
5431 **     *pRes==0     The cursor is left pointing at an entry that
5432 **                  exactly matches intKey/pIdxKey.
5433 **
5434 **     *pRes>0      The cursor is left pointing at an entry that
5435 **                  is larger than intKey/pIdxKey.
5436 **
5437 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5438 ** exists an entry in the table that exactly matches pIdxKey.
5439 */
5440 int sqlite3BtreeMovetoUnpacked(
5441   BtCursor *pCur,          /* The cursor to be moved */
5442   UnpackedRecord *pIdxKey, /* Unpacked index key */
5443   i64 intKey,              /* The table key */
5444   int biasRight,           /* If true, bias the search to the high end */
5445   int *pRes                /* Write search results here */
5446 ){
5447   int rc;
5448   RecordCompare xRecordCompare;
5449 
5450   assert( cursorOwnsBtShared(pCur) );
5451   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5452   assert( pRes );
5453   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5454   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5455 
5456   /* If the cursor is already positioned at the point we are trying
5457   ** to move to, then just return without doing any work */
5458   if( pIdxKey==0
5459    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5460   ){
5461     if( pCur->info.nKey==intKey ){
5462       *pRes = 0;
5463       return SQLITE_OK;
5464     }
5465     if( pCur->info.nKey<intKey ){
5466       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5467         *pRes = -1;
5468         return SQLITE_OK;
5469       }
5470       /* If the requested key is one more than the previous key, then
5471       ** try to get there using sqlite3BtreeNext() rather than a full
5472       ** binary search.  This is an optimization only.  The correct answer
5473       ** is still obtained without this case, only a little more slowely */
5474       if( pCur->info.nKey+1==intKey ){
5475         *pRes = 0;
5476         rc = sqlite3BtreeNext(pCur, 0);
5477         if( rc==SQLITE_OK ){
5478           getCellInfo(pCur);
5479           if( pCur->info.nKey==intKey ){
5480             return SQLITE_OK;
5481           }
5482         }else if( rc==SQLITE_DONE ){
5483           rc = SQLITE_OK;
5484         }else{
5485           return rc;
5486         }
5487       }
5488     }
5489   }
5490 
5491 #ifdef SQLITE_DEBUG
5492   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5493 #endif
5494 
5495   if( pIdxKey ){
5496     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5497     pIdxKey->errCode = 0;
5498     assert( pIdxKey->default_rc==1
5499          || pIdxKey->default_rc==0
5500          || pIdxKey->default_rc==-1
5501     );
5502   }else{
5503     xRecordCompare = 0; /* All keys are integers */
5504   }
5505 
5506   rc = moveToRoot(pCur);
5507   if( rc ){
5508     if( rc==SQLITE_EMPTY ){
5509       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5510       *pRes = -1;
5511       return SQLITE_OK;
5512     }
5513     return rc;
5514   }
5515   assert( pCur->pPage );
5516   assert( pCur->pPage->isInit );
5517   assert( pCur->eState==CURSOR_VALID );
5518   assert( pCur->pPage->nCell > 0 );
5519   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5520   assert( pCur->curIntKey || pIdxKey );
5521   for(;;){
5522     int lwr, upr, idx, c;
5523     Pgno chldPg;
5524     MemPage *pPage = pCur->pPage;
5525     u8 *pCell;                          /* Pointer to current cell in pPage */
5526 
5527     /* pPage->nCell must be greater than zero. If this is the root-page
5528     ** the cursor would have been INVALID above and this for(;;) loop
5529     ** not run. If this is not the root-page, then the moveToChild() routine
5530     ** would have already detected db corruption. Similarly, pPage must
5531     ** be the right kind (index or table) of b-tree page. Otherwise
5532     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5533     assert( pPage->nCell>0 );
5534     assert( pPage->intKey==(pIdxKey==0) );
5535     lwr = 0;
5536     upr = pPage->nCell-1;
5537     assert( biasRight==0 || biasRight==1 );
5538     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5539     pCur->ix = (u16)idx;
5540     if( xRecordCompare==0 ){
5541       for(;;){
5542         i64 nCellKey;
5543         pCell = findCellPastPtr(pPage, idx);
5544         if( pPage->intKeyLeaf ){
5545           while( 0x80 <= *(pCell++) ){
5546             if( pCell>=pPage->aDataEnd ){
5547               return SQLITE_CORRUPT_PAGE(pPage);
5548             }
5549           }
5550         }
5551         getVarint(pCell, (u64*)&nCellKey);
5552         if( nCellKey<intKey ){
5553           lwr = idx+1;
5554           if( lwr>upr ){ c = -1; break; }
5555         }else if( nCellKey>intKey ){
5556           upr = idx-1;
5557           if( lwr>upr ){ c = +1; break; }
5558         }else{
5559           assert( nCellKey==intKey );
5560           pCur->ix = (u16)idx;
5561           if( !pPage->leaf ){
5562             lwr = idx;
5563             goto moveto_next_layer;
5564           }else{
5565             pCur->curFlags |= BTCF_ValidNKey;
5566             pCur->info.nKey = nCellKey;
5567             pCur->info.nSize = 0;
5568             *pRes = 0;
5569             return SQLITE_OK;
5570           }
5571         }
5572         assert( lwr+upr>=0 );
5573         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5574       }
5575     }else{
5576       for(;;){
5577         int nCell;  /* Size of the pCell cell in bytes */
5578         pCell = findCellPastPtr(pPage, idx);
5579 
5580         /* The maximum supported page-size is 65536 bytes. This means that
5581         ** the maximum number of record bytes stored on an index B-Tree
5582         ** page is less than 16384 bytes and may be stored as a 2-byte
5583         ** varint. This information is used to attempt to avoid parsing
5584         ** the entire cell by checking for the cases where the record is
5585         ** stored entirely within the b-tree page by inspecting the first
5586         ** 2 bytes of the cell.
5587         */
5588         nCell = pCell[0];
5589         if( nCell<=pPage->max1bytePayload ){
5590           /* This branch runs if the record-size field of the cell is a
5591           ** single byte varint and the record fits entirely on the main
5592           ** b-tree page.  */
5593           testcase( pCell+nCell+1==pPage->aDataEnd );
5594           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5595         }else if( !(pCell[1] & 0x80)
5596           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5597         ){
5598           /* The record-size field is a 2 byte varint and the record
5599           ** fits entirely on the main b-tree page.  */
5600           testcase( pCell+nCell+2==pPage->aDataEnd );
5601           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5602         }else{
5603           /* The record flows over onto one or more overflow pages. In
5604           ** this case the whole cell needs to be parsed, a buffer allocated
5605           ** and accessPayload() used to retrieve the record into the
5606           ** buffer before VdbeRecordCompare() can be called.
5607           **
5608           ** If the record is corrupt, the xRecordCompare routine may read
5609           ** up to two varints past the end of the buffer. An extra 18
5610           ** bytes of padding is allocated at the end of the buffer in
5611           ** case this happens.  */
5612           void *pCellKey;
5613           u8 * const pCellBody = pCell - pPage->childPtrSize;
5614           const int nOverrun = 18;  /* Size of the overrun padding */
5615           pPage->xParseCell(pPage, pCellBody, &pCur->info);
5616           nCell = (int)pCur->info.nKey;
5617           testcase( nCell<0 );   /* True if key size is 2^32 or more */
5618           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5619           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5620           testcase( nCell==2 );  /* Minimum legal index key size */
5621           if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5622             rc = SQLITE_CORRUPT_PAGE(pPage);
5623             goto moveto_finish;
5624           }
5625           pCellKey = sqlite3Malloc( nCell+nOverrun );
5626           if( pCellKey==0 ){
5627             rc = SQLITE_NOMEM_BKPT;
5628             goto moveto_finish;
5629           }
5630           pCur->ix = (u16)idx;
5631           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5632           memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5633           pCur->curFlags &= ~BTCF_ValidOvfl;
5634           if( rc ){
5635             sqlite3_free(pCellKey);
5636             goto moveto_finish;
5637           }
5638           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5639           sqlite3_free(pCellKey);
5640         }
5641         assert(
5642             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5643          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5644         );
5645         if( c<0 ){
5646           lwr = idx+1;
5647         }else if( c>0 ){
5648           upr = idx-1;
5649         }else{
5650           assert( c==0 );
5651           *pRes = 0;
5652           rc = SQLITE_OK;
5653           pCur->ix = (u16)idx;
5654           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5655           goto moveto_finish;
5656         }
5657         if( lwr>upr ) break;
5658         assert( lwr+upr>=0 );
5659         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5660       }
5661     }
5662     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5663     assert( pPage->isInit );
5664     if( pPage->leaf ){
5665       assert( pCur->ix<pCur->pPage->nCell );
5666       pCur->ix = (u16)idx;
5667       *pRes = c;
5668       rc = SQLITE_OK;
5669       goto moveto_finish;
5670     }
5671 moveto_next_layer:
5672     if( lwr>=pPage->nCell ){
5673       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5674     }else{
5675       chldPg = get4byte(findCell(pPage, lwr));
5676     }
5677     pCur->ix = (u16)lwr;
5678     rc = moveToChild(pCur, chldPg);
5679     if( rc ) break;
5680   }
5681 moveto_finish:
5682   pCur->info.nSize = 0;
5683   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5684   return rc;
5685 }
5686 
5687 
5688 /*
5689 ** Return TRUE if the cursor is not pointing at an entry of the table.
5690 **
5691 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5692 ** past the last entry in the table or sqlite3BtreePrev() moves past
5693 ** the first entry.  TRUE is also returned if the table is empty.
5694 */
5695 int sqlite3BtreeEof(BtCursor *pCur){
5696   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5697   ** have been deleted? This API will need to change to return an error code
5698   ** as well as the boolean result value.
5699   */
5700   return (CURSOR_VALID!=pCur->eState);
5701 }
5702 
5703 /*
5704 ** Return an estimate for the number of rows in the table that pCur is
5705 ** pointing to.  Return a negative number if no estimate is currently
5706 ** available.
5707 */
5708 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5709   i64 n;
5710   u8 i;
5711 
5712   assert( cursorOwnsBtShared(pCur) );
5713   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5714 
5715   /* Currently this interface is only called by the OP_IfSmaller
5716   ** opcode, and it that case the cursor will always be valid and
5717   ** will always point to a leaf node. */
5718   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5719   if( NEVER(pCur->pPage->leaf==0) ) return -1;
5720 
5721   n = pCur->pPage->nCell;
5722   for(i=0; i<pCur->iPage; i++){
5723     n *= pCur->apPage[i]->nCell;
5724   }
5725   return n;
5726 }
5727 
5728 /*
5729 ** Advance the cursor to the next entry in the database.
5730 ** Return value:
5731 **
5732 **    SQLITE_OK        success
5733 **    SQLITE_DONE      cursor is already pointing at the last element
5734 **    otherwise        some kind of error occurred
5735 **
5736 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
5737 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5738 ** to the next cell on the current page.  The (slower) btreeNext() helper
5739 ** routine is called when it is necessary to move to a different page or
5740 ** to restore the cursor.
5741 **
5742 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5743 ** cursor corresponds to an SQL index and this routine could have been
5744 ** skipped if the SQL index had been a unique index.  The F argument
5745 ** is a hint to the implement.  SQLite btree implementation does not use
5746 ** this hint, but COMDB2 does.
5747 */
5748 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5749   int rc;
5750   int idx;
5751   MemPage *pPage;
5752 
5753   assert( cursorOwnsBtShared(pCur) );
5754   if( pCur->eState!=CURSOR_VALID ){
5755     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5756     rc = restoreCursorPosition(pCur);
5757     if( rc!=SQLITE_OK ){
5758       return rc;
5759     }
5760     if( CURSOR_INVALID==pCur->eState ){
5761       return SQLITE_DONE;
5762     }
5763     if( pCur->eState==CURSOR_SKIPNEXT ){
5764       pCur->eState = CURSOR_VALID;
5765       if( pCur->skipNext>0 ) return SQLITE_OK;
5766     }
5767   }
5768 
5769   pPage = pCur->pPage;
5770   idx = ++pCur->ix;
5771   if( !pPage->isInit || sqlite3FaultSim(412) ){
5772     /* The only known way for this to happen is for there to be a
5773     ** recursive SQL function that does a DELETE operation as part of a
5774     ** SELECT which deletes content out from under an active cursor
5775     ** in a corrupt database file where the table being DELETE-ed from
5776     ** has pages in common with the table being queried.  See TH3
5777     ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5778     ** example. */
5779     return SQLITE_CORRUPT_BKPT;
5780   }
5781 
5782   /* If the database file is corrupt, it is possible for the value of idx
5783   ** to be invalid here. This can only occur if a second cursor modifies
5784   ** the page while cursor pCur is holding a reference to it. Which can
5785   ** only happen if the database is corrupt in such a way as to link the
5786   ** page into more than one b-tree structure.
5787   **
5788   ** Update 2019-12-23: appears to long longer be possible after the
5789   ** addition of anotherValidCursor() condition on balance_deeper().  */
5790   harmless( idx>pPage->nCell );
5791 
5792   if( idx>=pPage->nCell ){
5793     if( !pPage->leaf ){
5794       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5795       if( rc ) return rc;
5796       return moveToLeftmost(pCur);
5797     }
5798     do{
5799       if( pCur->iPage==0 ){
5800         pCur->eState = CURSOR_INVALID;
5801         return SQLITE_DONE;
5802       }
5803       moveToParent(pCur);
5804       pPage = pCur->pPage;
5805     }while( pCur->ix>=pPage->nCell );
5806     if( pPage->intKey ){
5807       return sqlite3BtreeNext(pCur, 0);
5808     }else{
5809       return SQLITE_OK;
5810     }
5811   }
5812   if( pPage->leaf ){
5813     return SQLITE_OK;
5814   }else{
5815     return moveToLeftmost(pCur);
5816   }
5817 }
5818 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5819   MemPage *pPage;
5820   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5821   assert( cursorOwnsBtShared(pCur) );
5822   assert( flags==0 || flags==1 );
5823   pCur->info.nSize = 0;
5824   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5825   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5826   pPage = pCur->pPage;
5827   if( (++pCur->ix)>=pPage->nCell ){
5828     pCur->ix--;
5829     return btreeNext(pCur);
5830   }
5831   if( pPage->leaf ){
5832     return SQLITE_OK;
5833   }else{
5834     return moveToLeftmost(pCur);
5835   }
5836 }
5837 
5838 /*
5839 ** Step the cursor to the back to the previous entry in the database.
5840 ** Return values:
5841 **
5842 **     SQLITE_OK     success
5843 **     SQLITE_DONE   the cursor is already on the first element of the table
5844 **     otherwise     some kind of error occurred
5845 **
5846 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
5847 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5848 ** to the previous cell on the current page.  The (slower) btreePrevious()
5849 ** helper routine is called when it is necessary to move to a different page
5850 ** or to restore the cursor.
5851 **
5852 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5853 ** the cursor corresponds to an SQL index and this routine could have been
5854 ** skipped if the SQL index had been a unique index.  The F argument is a
5855 ** hint to the implement.  The native SQLite btree implementation does not
5856 ** use this hint, but COMDB2 does.
5857 */
5858 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5859   int rc;
5860   MemPage *pPage;
5861 
5862   assert( cursorOwnsBtShared(pCur) );
5863   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5864   assert( pCur->info.nSize==0 );
5865   if( pCur->eState!=CURSOR_VALID ){
5866     rc = restoreCursorPosition(pCur);
5867     if( rc!=SQLITE_OK ){
5868       return rc;
5869     }
5870     if( CURSOR_INVALID==pCur->eState ){
5871       return SQLITE_DONE;
5872     }
5873     if( CURSOR_SKIPNEXT==pCur->eState ){
5874       pCur->eState = CURSOR_VALID;
5875       if( pCur->skipNext<0 ) return SQLITE_OK;
5876     }
5877   }
5878 
5879   pPage = pCur->pPage;
5880   assert( pPage->isInit );
5881   if( !pPage->leaf ){
5882     int idx = pCur->ix;
5883     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5884     if( rc ) return rc;
5885     rc = moveToRightmost(pCur);
5886   }else{
5887     while( pCur->ix==0 ){
5888       if( pCur->iPage==0 ){
5889         pCur->eState = CURSOR_INVALID;
5890         return SQLITE_DONE;
5891       }
5892       moveToParent(pCur);
5893     }
5894     assert( pCur->info.nSize==0 );
5895     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5896 
5897     pCur->ix--;
5898     pPage = pCur->pPage;
5899     if( pPage->intKey && !pPage->leaf ){
5900       rc = sqlite3BtreePrevious(pCur, 0);
5901     }else{
5902       rc = SQLITE_OK;
5903     }
5904   }
5905   return rc;
5906 }
5907 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5908   assert( cursorOwnsBtShared(pCur) );
5909   assert( flags==0 || flags==1 );
5910   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5911   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5912   pCur->info.nSize = 0;
5913   if( pCur->eState!=CURSOR_VALID
5914    || pCur->ix==0
5915    || pCur->pPage->leaf==0
5916   ){
5917     return btreePrevious(pCur);
5918   }
5919   pCur->ix--;
5920   return SQLITE_OK;
5921 }
5922 
5923 /*
5924 ** Allocate a new page from the database file.
5925 **
5926 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
5927 ** has already been called on the new page.)  The new page has also
5928 ** been referenced and the calling routine is responsible for calling
5929 ** sqlite3PagerUnref() on the new page when it is done.
5930 **
5931 ** SQLITE_OK is returned on success.  Any other return value indicates
5932 ** an error.  *ppPage is set to NULL in the event of an error.
5933 **
5934 ** If the "nearby" parameter is not 0, then an effort is made to
5935 ** locate a page close to the page number "nearby".  This can be used in an
5936 ** attempt to keep related pages close to each other in the database file,
5937 ** which in turn can make database access faster.
5938 **
5939 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5940 ** anywhere on the free-list, then it is guaranteed to be returned.  If
5941 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5942 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
5943 ** are no restrictions on which page is returned.
5944 */
5945 static int allocateBtreePage(
5946   BtShared *pBt,         /* The btree */
5947   MemPage **ppPage,      /* Store pointer to the allocated page here */
5948   Pgno *pPgno,           /* Store the page number here */
5949   Pgno nearby,           /* Search for a page near this one */
5950   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5951 ){
5952   MemPage *pPage1;
5953   int rc;
5954   u32 n;     /* Number of pages on the freelist */
5955   u32 k;     /* Number of leaves on the trunk of the freelist */
5956   MemPage *pTrunk = 0;
5957   MemPage *pPrevTrunk = 0;
5958   Pgno mxPage;     /* Total size of the database file */
5959 
5960   assert( sqlite3_mutex_held(pBt->mutex) );
5961   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5962   pPage1 = pBt->pPage1;
5963   mxPage = btreePagecount(pBt);
5964   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5965   ** stores stores the total number of pages on the freelist. */
5966   n = get4byte(&pPage1->aData[36]);
5967   testcase( n==mxPage-1 );
5968   if( n>=mxPage ){
5969     return SQLITE_CORRUPT_BKPT;
5970   }
5971   if( n>0 ){
5972     /* There are pages on the freelist.  Reuse one of those pages. */
5973     Pgno iTrunk;
5974     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5975     u32 nSearch = 0;   /* Count of the number of search attempts */
5976 
5977     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5978     ** shows that the page 'nearby' is somewhere on the free-list, then
5979     ** the entire-list will be searched for that page.
5980     */
5981 #ifndef SQLITE_OMIT_AUTOVACUUM
5982     if( eMode==BTALLOC_EXACT ){
5983       if( nearby<=mxPage ){
5984         u8 eType;
5985         assert( nearby>0 );
5986         assert( pBt->autoVacuum );
5987         rc = ptrmapGet(pBt, nearby, &eType, 0);
5988         if( rc ) return rc;
5989         if( eType==PTRMAP_FREEPAGE ){
5990           searchList = 1;
5991         }
5992       }
5993     }else if( eMode==BTALLOC_LE ){
5994       searchList = 1;
5995     }
5996 #endif
5997 
5998     /* Decrement the free-list count by 1. Set iTrunk to the index of the
5999     ** first free-list trunk page. iPrevTrunk is initially 1.
6000     */
6001     rc = sqlite3PagerWrite(pPage1->pDbPage);
6002     if( rc ) return rc;
6003     put4byte(&pPage1->aData[36], n-1);
6004 
6005     /* The code within this loop is run only once if the 'searchList' variable
6006     ** is not true. Otherwise, it runs once for each trunk-page on the
6007     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6008     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6009     */
6010     do {
6011       pPrevTrunk = pTrunk;
6012       if( pPrevTrunk ){
6013         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6014         ** is the page number of the next freelist trunk page in the list or
6015         ** zero if this is the last freelist trunk page. */
6016         iTrunk = get4byte(&pPrevTrunk->aData[0]);
6017       }else{
6018         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6019         ** stores the page number of the first page of the freelist, or zero if
6020         ** the freelist is empty. */
6021         iTrunk = get4byte(&pPage1->aData[32]);
6022       }
6023       testcase( iTrunk==mxPage );
6024       if( iTrunk>mxPage || nSearch++ > n ){
6025         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6026       }else{
6027         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6028       }
6029       if( rc ){
6030         pTrunk = 0;
6031         goto end_allocate_page;
6032       }
6033       assert( pTrunk!=0 );
6034       assert( pTrunk->aData!=0 );
6035       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6036       ** is the number of leaf page pointers to follow. */
6037       k = get4byte(&pTrunk->aData[4]);
6038       if( k==0 && !searchList ){
6039         /* The trunk has no leaves and the list is not being searched.
6040         ** So extract the trunk page itself and use it as the newly
6041         ** allocated page */
6042         assert( pPrevTrunk==0 );
6043         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6044         if( rc ){
6045           goto end_allocate_page;
6046         }
6047         *pPgno = iTrunk;
6048         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6049         *ppPage = pTrunk;
6050         pTrunk = 0;
6051         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6052       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6053         /* Value of k is out of range.  Database corruption */
6054         rc = SQLITE_CORRUPT_PGNO(iTrunk);
6055         goto end_allocate_page;
6056 #ifndef SQLITE_OMIT_AUTOVACUUM
6057       }else if( searchList
6058             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6059       ){
6060         /* The list is being searched and this trunk page is the page
6061         ** to allocate, regardless of whether it has leaves.
6062         */
6063         *pPgno = iTrunk;
6064         *ppPage = pTrunk;
6065         searchList = 0;
6066         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6067         if( rc ){
6068           goto end_allocate_page;
6069         }
6070         if( k==0 ){
6071           if( !pPrevTrunk ){
6072             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6073           }else{
6074             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6075             if( rc!=SQLITE_OK ){
6076               goto end_allocate_page;
6077             }
6078             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6079           }
6080         }else{
6081           /* The trunk page is required by the caller but it contains
6082           ** pointers to free-list leaves. The first leaf becomes a trunk
6083           ** page in this case.
6084           */
6085           MemPage *pNewTrunk;
6086           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6087           if( iNewTrunk>mxPage ){
6088             rc = SQLITE_CORRUPT_PGNO(iTrunk);
6089             goto end_allocate_page;
6090           }
6091           testcase( iNewTrunk==mxPage );
6092           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6093           if( rc!=SQLITE_OK ){
6094             goto end_allocate_page;
6095           }
6096           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6097           if( rc!=SQLITE_OK ){
6098             releasePage(pNewTrunk);
6099             goto end_allocate_page;
6100           }
6101           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6102           put4byte(&pNewTrunk->aData[4], k-1);
6103           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6104           releasePage(pNewTrunk);
6105           if( !pPrevTrunk ){
6106             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6107             put4byte(&pPage1->aData[32], iNewTrunk);
6108           }else{
6109             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6110             if( rc ){
6111               goto end_allocate_page;
6112             }
6113             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6114           }
6115         }
6116         pTrunk = 0;
6117         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6118 #endif
6119       }else if( k>0 ){
6120         /* Extract a leaf from the trunk */
6121         u32 closest;
6122         Pgno iPage;
6123         unsigned char *aData = pTrunk->aData;
6124         if( nearby>0 ){
6125           u32 i;
6126           closest = 0;
6127           if( eMode==BTALLOC_LE ){
6128             for(i=0; i<k; i++){
6129               iPage = get4byte(&aData[8+i*4]);
6130               if( iPage<=nearby ){
6131                 closest = i;
6132                 break;
6133               }
6134             }
6135           }else{
6136             int dist;
6137             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6138             for(i=1; i<k; i++){
6139               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6140               if( d2<dist ){
6141                 closest = i;
6142                 dist = d2;
6143               }
6144             }
6145           }
6146         }else{
6147           closest = 0;
6148         }
6149 
6150         iPage = get4byte(&aData[8+closest*4]);
6151         testcase( iPage==mxPage );
6152         if( iPage>mxPage ){
6153           rc = SQLITE_CORRUPT_PGNO(iTrunk);
6154           goto end_allocate_page;
6155         }
6156         testcase( iPage==mxPage );
6157         if( !searchList
6158          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6159         ){
6160           int noContent;
6161           *pPgno = iPage;
6162           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6163                  ": %d more free pages\n",
6164                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
6165           rc = sqlite3PagerWrite(pTrunk->pDbPage);
6166           if( rc ) goto end_allocate_page;
6167           if( closest<k-1 ){
6168             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6169           }
6170           put4byte(&aData[4], k-1);
6171           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6172           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6173           if( rc==SQLITE_OK ){
6174             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6175             if( rc!=SQLITE_OK ){
6176               releasePage(*ppPage);
6177               *ppPage = 0;
6178             }
6179           }
6180           searchList = 0;
6181         }
6182       }
6183       releasePage(pPrevTrunk);
6184       pPrevTrunk = 0;
6185     }while( searchList );
6186   }else{
6187     /* There are no pages on the freelist, so append a new page to the
6188     ** database image.
6189     **
6190     ** Normally, new pages allocated by this block can be requested from the
6191     ** pager layer with the 'no-content' flag set. This prevents the pager
6192     ** from trying to read the pages content from disk. However, if the
6193     ** current transaction has already run one or more incremental-vacuum
6194     ** steps, then the page we are about to allocate may contain content
6195     ** that is required in the event of a rollback. In this case, do
6196     ** not set the no-content flag. This causes the pager to load and journal
6197     ** the current page content before overwriting it.
6198     **
6199     ** Note that the pager will not actually attempt to load or journal
6200     ** content for any page that really does lie past the end of the database
6201     ** file on disk. So the effects of disabling the no-content optimization
6202     ** here are confined to those pages that lie between the end of the
6203     ** database image and the end of the database file.
6204     */
6205     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6206 
6207     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6208     if( rc ) return rc;
6209     pBt->nPage++;
6210     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6211 
6212 #ifndef SQLITE_OMIT_AUTOVACUUM
6213     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6214       /* If *pPgno refers to a pointer-map page, allocate two new pages
6215       ** at the end of the file instead of one. The first allocated page
6216       ** becomes a new pointer-map page, the second is used by the caller.
6217       */
6218       MemPage *pPg = 0;
6219       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6220       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6221       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6222       if( rc==SQLITE_OK ){
6223         rc = sqlite3PagerWrite(pPg->pDbPage);
6224         releasePage(pPg);
6225       }
6226       if( rc ) return rc;
6227       pBt->nPage++;
6228       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6229     }
6230 #endif
6231     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6232     *pPgno = pBt->nPage;
6233 
6234     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6235     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6236     if( rc ) return rc;
6237     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6238     if( rc!=SQLITE_OK ){
6239       releasePage(*ppPage);
6240       *ppPage = 0;
6241     }
6242     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6243   }
6244 
6245   assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6246 
6247 end_allocate_page:
6248   releasePage(pTrunk);
6249   releasePage(pPrevTrunk);
6250   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6251   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6252   return rc;
6253 }
6254 
6255 /*
6256 ** This function is used to add page iPage to the database file free-list.
6257 ** It is assumed that the page is not already a part of the free-list.
6258 **
6259 ** The value passed as the second argument to this function is optional.
6260 ** If the caller happens to have a pointer to the MemPage object
6261 ** corresponding to page iPage handy, it may pass it as the second value.
6262 ** Otherwise, it may pass NULL.
6263 **
6264 ** If a pointer to a MemPage object is passed as the second argument,
6265 ** its reference count is not altered by this function.
6266 */
6267 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6268   MemPage *pTrunk = 0;                /* Free-list trunk page */
6269   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
6270   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
6271   MemPage *pPage;                     /* Page being freed. May be NULL. */
6272   int rc;                             /* Return Code */
6273   u32 nFree;                          /* Initial number of pages on free-list */
6274 
6275   assert( sqlite3_mutex_held(pBt->mutex) );
6276   assert( CORRUPT_DB || iPage>1 );
6277   assert( !pMemPage || pMemPage->pgno==iPage );
6278 
6279   if( iPage<2 || iPage>pBt->nPage ){
6280     return SQLITE_CORRUPT_BKPT;
6281   }
6282   if( pMemPage ){
6283     pPage = pMemPage;
6284     sqlite3PagerRef(pPage->pDbPage);
6285   }else{
6286     pPage = btreePageLookup(pBt, iPage);
6287   }
6288 
6289   /* Increment the free page count on pPage1 */
6290   rc = sqlite3PagerWrite(pPage1->pDbPage);
6291   if( rc ) goto freepage_out;
6292   nFree = get4byte(&pPage1->aData[36]);
6293   put4byte(&pPage1->aData[36], nFree+1);
6294 
6295   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6296     /* If the secure_delete option is enabled, then
6297     ** always fully overwrite deleted information with zeros.
6298     */
6299     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6300      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6301     ){
6302       goto freepage_out;
6303     }
6304     memset(pPage->aData, 0, pPage->pBt->pageSize);
6305   }
6306 
6307   /* If the database supports auto-vacuum, write an entry in the pointer-map
6308   ** to indicate that the page is free.
6309   */
6310   if( ISAUTOVACUUM ){
6311     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6312     if( rc ) goto freepage_out;
6313   }
6314 
6315   /* Now manipulate the actual database free-list structure. There are two
6316   ** possibilities. If the free-list is currently empty, or if the first
6317   ** trunk page in the free-list is full, then this page will become a
6318   ** new free-list trunk page. Otherwise, it will become a leaf of the
6319   ** first trunk page in the current free-list. This block tests if it
6320   ** is possible to add the page as a new free-list leaf.
6321   */
6322   if( nFree!=0 ){
6323     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6324 
6325     iTrunk = get4byte(&pPage1->aData[32]);
6326     if( iTrunk>btreePagecount(pBt) ){
6327       rc = SQLITE_CORRUPT_BKPT;
6328       goto freepage_out;
6329     }
6330     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6331     if( rc!=SQLITE_OK ){
6332       goto freepage_out;
6333     }
6334 
6335     nLeaf = get4byte(&pTrunk->aData[4]);
6336     assert( pBt->usableSize>32 );
6337     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6338       rc = SQLITE_CORRUPT_BKPT;
6339       goto freepage_out;
6340     }
6341     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6342       /* In this case there is room on the trunk page to insert the page
6343       ** being freed as a new leaf.
6344       **
6345       ** Note that the trunk page is not really full until it contains
6346       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6347       ** coded.  But due to a coding error in versions of SQLite prior to
6348       ** 3.6.0, databases with freelist trunk pages holding more than
6349       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6350       ** to maintain backwards compatibility with older versions of SQLite,
6351       ** we will continue to restrict the number of entries to usableSize/4 - 8
6352       ** for now.  At some point in the future (once everyone has upgraded
6353       ** to 3.6.0 or later) we should consider fixing the conditional above
6354       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6355       **
6356       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6357       ** avoid using the last six entries in the freelist trunk page array in
6358       ** order that database files created by newer versions of SQLite can be
6359       ** read by older versions of SQLite.
6360       */
6361       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6362       if( rc==SQLITE_OK ){
6363         put4byte(&pTrunk->aData[4], nLeaf+1);
6364         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6365         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6366           sqlite3PagerDontWrite(pPage->pDbPage);
6367         }
6368         rc = btreeSetHasContent(pBt, iPage);
6369       }
6370       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6371       goto freepage_out;
6372     }
6373   }
6374 
6375   /* If control flows to this point, then it was not possible to add the
6376   ** the page being freed as a leaf page of the first trunk in the free-list.
6377   ** Possibly because the free-list is empty, or possibly because the
6378   ** first trunk in the free-list is full. Either way, the page being freed
6379   ** will become the new first trunk page in the free-list.
6380   */
6381   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6382     goto freepage_out;
6383   }
6384   rc = sqlite3PagerWrite(pPage->pDbPage);
6385   if( rc!=SQLITE_OK ){
6386     goto freepage_out;
6387   }
6388   put4byte(pPage->aData, iTrunk);
6389   put4byte(&pPage->aData[4], 0);
6390   put4byte(&pPage1->aData[32], iPage);
6391   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6392 
6393 freepage_out:
6394   if( pPage ){
6395     pPage->isInit = 0;
6396   }
6397   releasePage(pPage);
6398   releasePage(pTrunk);
6399   return rc;
6400 }
6401 static void freePage(MemPage *pPage, int *pRC){
6402   if( (*pRC)==SQLITE_OK ){
6403     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6404   }
6405 }
6406 
6407 /*
6408 ** Free any overflow pages associated with the given Cell.  Store
6409 ** size information about the cell in pInfo.
6410 */
6411 static int clearCell(
6412   MemPage *pPage,          /* The page that contains the Cell */
6413   unsigned char *pCell,    /* First byte of the Cell */
6414   CellInfo *pInfo          /* Size information about the cell */
6415 ){
6416   BtShared *pBt;
6417   Pgno ovflPgno;
6418   int rc;
6419   int nOvfl;
6420   u32 ovflPageSize;
6421 
6422   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6423   pPage->xParseCell(pPage, pCell, pInfo);
6424   if( pInfo->nLocal==pInfo->nPayload ){
6425     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
6426   }
6427   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6428   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6429   if( pCell + pInfo->nSize > pPage->aDataEnd ){
6430     /* Cell extends past end of page */
6431     return SQLITE_CORRUPT_PAGE(pPage);
6432   }
6433   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6434   pBt = pPage->pBt;
6435   assert( pBt->usableSize > 4 );
6436   ovflPageSize = pBt->usableSize - 4;
6437   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6438   assert( nOvfl>0 ||
6439     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6440   );
6441   while( nOvfl-- ){
6442     Pgno iNext = 0;
6443     MemPage *pOvfl = 0;
6444     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6445       /* 0 is not a legal page number and page 1 cannot be an
6446       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6447       ** file the database must be corrupt. */
6448       return SQLITE_CORRUPT_BKPT;
6449     }
6450     if( nOvfl ){
6451       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6452       if( rc ) return rc;
6453     }
6454 
6455     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6456      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6457     ){
6458       /* There is no reason any cursor should have an outstanding reference
6459       ** to an overflow page belonging to a cell that is being deleted/updated.
6460       ** So if there exists more than one reference to this page, then it
6461       ** must not really be an overflow page and the database must be corrupt.
6462       ** It is helpful to detect this before calling freePage2(), as
6463       ** freePage2() may zero the page contents if secure-delete mode is
6464       ** enabled. If this 'overflow' page happens to be a page that the
6465       ** caller is iterating through or using in some other way, this
6466       ** can be problematic.
6467       */
6468       rc = SQLITE_CORRUPT_BKPT;
6469     }else{
6470       rc = freePage2(pBt, pOvfl, ovflPgno);
6471     }
6472 
6473     if( pOvfl ){
6474       sqlite3PagerUnref(pOvfl->pDbPage);
6475     }
6476     if( rc ) return rc;
6477     ovflPgno = iNext;
6478   }
6479   return SQLITE_OK;
6480 }
6481 
6482 /*
6483 ** Create the byte sequence used to represent a cell on page pPage
6484 ** and write that byte sequence into pCell[].  Overflow pages are
6485 ** allocated and filled in as necessary.  The calling procedure
6486 ** is responsible for making sure sufficient space has been allocated
6487 ** for pCell[].
6488 **
6489 ** Note that pCell does not necessary need to point to the pPage->aData
6490 ** area.  pCell might point to some temporary storage.  The cell will
6491 ** be constructed in this temporary area then copied into pPage->aData
6492 ** later.
6493 */
6494 static int fillInCell(
6495   MemPage *pPage,                /* The page that contains the cell */
6496   unsigned char *pCell,          /* Complete text of the cell */
6497   const BtreePayload *pX,        /* Payload with which to construct the cell */
6498   int *pnSize                    /* Write cell size here */
6499 ){
6500   int nPayload;
6501   const u8 *pSrc;
6502   int nSrc, n, rc, mn;
6503   int spaceLeft;
6504   MemPage *pToRelease;
6505   unsigned char *pPrior;
6506   unsigned char *pPayload;
6507   BtShared *pBt;
6508   Pgno pgnoOvfl;
6509   int nHeader;
6510 
6511   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6512 
6513   /* pPage is not necessarily writeable since pCell might be auxiliary
6514   ** buffer space that is separate from the pPage buffer area */
6515   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6516             || sqlite3PagerIswriteable(pPage->pDbPage) );
6517 
6518   /* Fill in the header. */
6519   nHeader = pPage->childPtrSize;
6520   if( pPage->intKey ){
6521     nPayload = pX->nData + pX->nZero;
6522     pSrc = pX->pData;
6523     nSrc = pX->nData;
6524     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6525     nHeader += putVarint32(&pCell[nHeader], nPayload);
6526     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6527   }else{
6528     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6529     nSrc = nPayload = (int)pX->nKey;
6530     pSrc = pX->pKey;
6531     nHeader += putVarint32(&pCell[nHeader], nPayload);
6532   }
6533 
6534   /* Fill in the payload */
6535   pPayload = &pCell[nHeader];
6536   if( nPayload<=pPage->maxLocal ){
6537     /* This is the common case where everything fits on the btree page
6538     ** and no overflow pages are required. */
6539     n = nHeader + nPayload;
6540     testcase( n==3 );
6541     testcase( n==4 );
6542     if( n<4 ) n = 4;
6543     *pnSize = n;
6544     assert( nSrc<=nPayload );
6545     testcase( nSrc<nPayload );
6546     memcpy(pPayload, pSrc, nSrc);
6547     memset(pPayload+nSrc, 0, nPayload-nSrc);
6548     return SQLITE_OK;
6549   }
6550 
6551   /* If we reach this point, it means that some of the content will need
6552   ** to spill onto overflow pages.
6553   */
6554   mn = pPage->minLocal;
6555   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6556   testcase( n==pPage->maxLocal );
6557   testcase( n==pPage->maxLocal+1 );
6558   if( n > pPage->maxLocal ) n = mn;
6559   spaceLeft = n;
6560   *pnSize = n + nHeader + 4;
6561   pPrior = &pCell[nHeader+n];
6562   pToRelease = 0;
6563   pgnoOvfl = 0;
6564   pBt = pPage->pBt;
6565 
6566   /* At this point variables should be set as follows:
6567   **
6568   **   nPayload           Total payload size in bytes
6569   **   pPayload           Begin writing payload here
6570   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6571   **                      that means content must spill into overflow pages.
6572   **   *pnSize            Size of the local cell (not counting overflow pages)
6573   **   pPrior             Where to write the pgno of the first overflow page
6574   **
6575   ** Use a call to btreeParseCellPtr() to verify that the values above
6576   ** were computed correctly.
6577   */
6578 #ifdef SQLITE_DEBUG
6579   {
6580     CellInfo info;
6581     pPage->xParseCell(pPage, pCell, &info);
6582     assert( nHeader==(int)(info.pPayload - pCell) );
6583     assert( info.nKey==pX->nKey );
6584     assert( *pnSize == info.nSize );
6585     assert( spaceLeft == info.nLocal );
6586   }
6587 #endif
6588 
6589   /* Write the payload into the local Cell and any extra into overflow pages */
6590   while( 1 ){
6591     n = nPayload;
6592     if( n>spaceLeft ) n = spaceLeft;
6593 
6594     /* If pToRelease is not zero than pPayload points into the data area
6595     ** of pToRelease.  Make sure pToRelease is still writeable. */
6596     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6597 
6598     /* If pPayload is part of the data area of pPage, then make sure pPage
6599     ** is still writeable */
6600     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6601             || sqlite3PagerIswriteable(pPage->pDbPage) );
6602 
6603     if( nSrc>=n ){
6604       memcpy(pPayload, pSrc, n);
6605     }else if( nSrc>0 ){
6606       n = nSrc;
6607       memcpy(pPayload, pSrc, n);
6608     }else{
6609       memset(pPayload, 0, n);
6610     }
6611     nPayload -= n;
6612     if( nPayload<=0 ) break;
6613     pPayload += n;
6614     pSrc += n;
6615     nSrc -= n;
6616     spaceLeft -= n;
6617     if( spaceLeft==0 ){
6618       MemPage *pOvfl = 0;
6619 #ifndef SQLITE_OMIT_AUTOVACUUM
6620       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6621       if( pBt->autoVacuum ){
6622         do{
6623           pgnoOvfl++;
6624         } while(
6625           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6626         );
6627       }
6628 #endif
6629       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6630 #ifndef SQLITE_OMIT_AUTOVACUUM
6631       /* If the database supports auto-vacuum, and the second or subsequent
6632       ** overflow page is being allocated, add an entry to the pointer-map
6633       ** for that page now.
6634       **
6635       ** If this is the first overflow page, then write a partial entry
6636       ** to the pointer-map. If we write nothing to this pointer-map slot,
6637       ** then the optimistic overflow chain processing in clearCell()
6638       ** may misinterpret the uninitialized values and delete the
6639       ** wrong pages from the database.
6640       */
6641       if( pBt->autoVacuum && rc==SQLITE_OK ){
6642         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6643         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6644         if( rc ){
6645           releasePage(pOvfl);
6646         }
6647       }
6648 #endif
6649       if( rc ){
6650         releasePage(pToRelease);
6651         return rc;
6652       }
6653 
6654       /* If pToRelease is not zero than pPrior points into the data area
6655       ** of pToRelease.  Make sure pToRelease is still writeable. */
6656       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6657 
6658       /* If pPrior is part of the data area of pPage, then make sure pPage
6659       ** is still writeable */
6660       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6661             || sqlite3PagerIswriteable(pPage->pDbPage) );
6662 
6663       put4byte(pPrior, pgnoOvfl);
6664       releasePage(pToRelease);
6665       pToRelease = pOvfl;
6666       pPrior = pOvfl->aData;
6667       put4byte(pPrior, 0);
6668       pPayload = &pOvfl->aData[4];
6669       spaceLeft = pBt->usableSize - 4;
6670     }
6671   }
6672   releasePage(pToRelease);
6673   return SQLITE_OK;
6674 }
6675 
6676 /*
6677 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6678 ** The cell content is not freed or deallocated.  It is assumed that
6679 ** the cell content has been copied someplace else.  This routine just
6680 ** removes the reference to the cell from pPage.
6681 **
6682 ** "sz" must be the number of bytes in the cell.
6683 */
6684 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6685   u32 pc;         /* Offset to cell content of cell being deleted */
6686   u8 *data;       /* pPage->aData */
6687   u8 *ptr;        /* Used to move bytes around within data[] */
6688   int rc;         /* The return code */
6689   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6690 
6691   if( *pRC ) return;
6692   assert( idx>=0 && idx<pPage->nCell );
6693   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6694   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6695   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6696   assert( pPage->nFree>=0 );
6697   data = pPage->aData;
6698   ptr = &pPage->aCellIdx[2*idx];
6699   pc = get2byte(ptr);
6700   hdr = pPage->hdrOffset;
6701   testcase( pc==get2byte(&data[hdr+5]) );
6702   testcase( pc+sz==pPage->pBt->usableSize );
6703   if( pc+sz > pPage->pBt->usableSize ){
6704     *pRC = SQLITE_CORRUPT_BKPT;
6705     return;
6706   }
6707   rc = freeSpace(pPage, pc, sz);
6708   if( rc ){
6709     *pRC = rc;
6710     return;
6711   }
6712   pPage->nCell--;
6713   if( pPage->nCell==0 ){
6714     memset(&data[hdr+1], 0, 4);
6715     data[hdr+7] = 0;
6716     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6717     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6718                        - pPage->childPtrSize - 8;
6719   }else{
6720     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6721     put2byte(&data[hdr+3], pPage->nCell);
6722     pPage->nFree += 2;
6723   }
6724 }
6725 
6726 /*
6727 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6728 ** content of the cell.
6729 **
6730 ** If the cell content will fit on the page, then put it there.  If it
6731 ** will not fit, then make a copy of the cell content into pTemp if
6732 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6733 ** in pPage->apOvfl[] and make it point to the cell content (either
6734 ** in pTemp or the original pCell) and also record its index.
6735 ** Allocating a new entry in pPage->aCell[] implies that
6736 ** pPage->nOverflow is incremented.
6737 **
6738 ** *pRC must be SQLITE_OK when this routine is called.
6739 */
6740 static void insertCell(
6741   MemPage *pPage,   /* Page into which we are copying */
6742   int i,            /* New cell becomes the i-th cell of the page */
6743   u8 *pCell,        /* Content of the new cell */
6744   int sz,           /* Bytes of content in pCell */
6745   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6746   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6747   int *pRC          /* Read and write return code from here */
6748 ){
6749   int idx = 0;      /* Where to write new cell content in data[] */
6750   int j;            /* Loop counter */
6751   u8 *data;         /* The content of the whole page */
6752   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6753 
6754   assert( *pRC==SQLITE_OK );
6755   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6756   assert( MX_CELL(pPage->pBt)<=10921 );
6757   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6758   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6759   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6760   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6761   assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6762   assert( pPage->nFree>=0 );
6763   if( pPage->nOverflow || sz+2>pPage->nFree ){
6764     if( pTemp ){
6765       memcpy(pTemp, pCell, sz);
6766       pCell = pTemp;
6767     }
6768     if( iChild ){
6769       put4byte(pCell, iChild);
6770     }
6771     j = pPage->nOverflow++;
6772     /* Comparison against ArraySize-1 since we hold back one extra slot
6773     ** as a contingency.  In other words, never need more than 3 overflow
6774     ** slots but 4 are allocated, just to be safe. */
6775     assert( j < ArraySize(pPage->apOvfl)-1 );
6776     pPage->apOvfl[j] = pCell;
6777     pPage->aiOvfl[j] = (u16)i;
6778 
6779     /* When multiple overflows occur, they are always sequential and in
6780     ** sorted order.  This invariants arise because multiple overflows can
6781     ** only occur when inserting divider cells into the parent page during
6782     ** balancing, and the dividers are adjacent and sorted.
6783     */
6784     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6785     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6786   }else{
6787     int rc = sqlite3PagerWrite(pPage->pDbPage);
6788     if( rc!=SQLITE_OK ){
6789       *pRC = rc;
6790       return;
6791     }
6792     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6793     data = pPage->aData;
6794     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6795     rc = allocateSpace(pPage, sz, &idx);
6796     if( rc ){ *pRC = rc; return; }
6797     /* The allocateSpace() routine guarantees the following properties
6798     ** if it returns successfully */
6799     assert( idx >= 0 );
6800     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6801     assert( idx+sz <= (int)pPage->pBt->usableSize );
6802     pPage->nFree -= (u16)(2 + sz);
6803     if( iChild ){
6804       /* In a corrupt database where an entry in the cell index section of
6805       ** a btree page has a value of 3 or less, the pCell value might point
6806       ** as many as 4 bytes in front of the start of the aData buffer for
6807       ** the source page.  Make sure this does not cause problems by not
6808       ** reading the first 4 bytes */
6809       memcpy(&data[idx+4], pCell+4, sz-4);
6810       put4byte(&data[idx], iChild);
6811     }else{
6812       memcpy(&data[idx], pCell, sz);
6813     }
6814     pIns = pPage->aCellIdx + i*2;
6815     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6816     put2byte(pIns, idx);
6817     pPage->nCell++;
6818     /* increment the cell count */
6819     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6820     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6821 #ifndef SQLITE_OMIT_AUTOVACUUM
6822     if( pPage->pBt->autoVacuum ){
6823       /* The cell may contain a pointer to an overflow page. If so, write
6824       ** the entry for the overflow page into the pointer map.
6825       */
6826       ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6827     }
6828 #endif
6829   }
6830 }
6831 
6832 /*
6833 ** The following parameters determine how many adjacent pages get involved
6834 ** in a balancing operation.  NN is the number of neighbors on either side
6835 ** of the page that participate in the balancing operation.  NB is the
6836 ** total number of pages that participate, including the target page and
6837 ** NN neighbors on either side.
6838 **
6839 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
6840 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6841 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6842 ** The value of NN appears to give the best results overall.
6843 **
6844 ** (Later:) The description above makes it seem as if these values are
6845 ** tunable - as if you could change them and recompile and it would all work.
6846 ** But that is unlikely.  NB has been 3 since the inception of SQLite and
6847 ** we have never tested any other value.
6848 */
6849 #define NN 1             /* Number of neighbors on either side of pPage */
6850 #define NB 3             /* (NN*2+1): Total pages involved in the balance */
6851 
6852 /*
6853 ** A CellArray object contains a cache of pointers and sizes for a
6854 ** consecutive sequence of cells that might be held on multiple pages.
6855 **
6856 ** The cells in this array are the divider cell or cells from the pParent
6857 ** page plus up to three child pages.  There are a total of nCell cells.
6858 **
6859 ** pRef is a pointer to one of the pages that contributes cells.  This is
6860 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6861 ** which should be common to all pages that contribute cells to this array.
6862 **
6863 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6864 ** cell and the size of each cell.  Some of the apCell[] pointers might refer
6865 ** to overflow cells.  In other words, some apCel[] pointers might not point
6866 ** to content area of the pages.
6867 **
6868 ** A szCell[] of zero means the size of that cell has not yet been computed.
6869 **
6870 ** The cells come from as many as four different pages:
6871 **
6872 **             -----------
6873 **             | Parent  |
6874 **             -----------
6875 **            /     |     \
6876 **           /      |      \
6877 **  ---------   ---------   ---------
6878 **  |Child-1|   |Child-2|   |Child-3|
6879 **  ---------   ---------   ---------
6880 **
6881 ** The order of cells is in the array is for an index btree is:
6882 **
6883 **       1.  All cells from Child-1 in order
6884 **       2.  The first divider cell from Parent
6885 **       3.  All cells from Child-2 in order
6886 **       4.  The second divider cell from Parent
6887 **       5.  All cells from Child-3 in order
6888 **
6889 ** For a table-btree (with rowids) the items 2 and 4 are empty because
6890 ** content exists only in leaves and there are no divider cells.
6891 **
6892 ** For an index btree, the apEnd[] array holds pointer to the end of page
6893 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
6894 ** respectively. The ixNx[] array holds the number of cells contained in
6895 ** each of these 5 stages, and all stages to the left.  Hence:
6896 **
6897 **    ixNx[0] = Number of cells in Child-1.
6898 **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
6899 **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
6900 **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
6901 **    ixNx[4] = Total number of cells.
6902 **
6903 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
6904 ** are used and they point to the leaf pages only, and the ixNx value are:
6905 **
6906 **    ixNx[0] = Number of cells in Child-1.
6907 **    ixNx[1] = Number of cells in Child-1 and Child-2.
6908 **    ixNx[2] = Total number of cells.
6909 **
6910 ** Sometimes when deleting, a child page can have zero cells.  In those
6911 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
6912 ** entries, shift down.  The end result is that each ixNx[] entry should
6913 ** be larger than the previous
6914 */
6915 typedef struct CellArray CellArray;
6916 struct CellArray {
6917   int nCell;              /* Number of cells in apCell[] */
6918   MemPage *pRef;          /* Reference page */
6919   u8 **apCell;            /* All cells begin balanced */
6920   u16 *szCell;            /* Local size of all cells in apCell[] */
6921   u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
6922   int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
6923 };
6924 
6925 /*
6926 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6927 ** computed.
6928 */
6929 static void populateCellCache(CellArray *p, int idx, int N){
6930   assert( idx>=0 && idx+N<=p->nCell );
6931   while( N>0 ){
6932     assert( p->apCell[idx]!=0 );
6933     if( p->szCell[idx]==0 ){
6934       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6935     }else{
6936       assert( CORRUPT_DB ||
6937               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6938     }
6939     idx++;
6940     N--;
6941   }
6942 }
6943 
6944 /*
6945 ** Return the size of the Nth element of the cell array
6946 */
6947 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6948   assert( N>=0 && N<p->nCell );
6949   assert( p->szCell[N]==0 );
6950   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6951   return p->szCell[N];
6952 }
6953 static u16 cachedCellSize(CellArray *p, int N){
6954   assert( N>=0 && N<p->nCell );
6955   if( p->szCell[N] ) return p->szCell[N];
6956   return computeCellSize(p, N);
6957 }
6958 
6959 /*
6960 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6961 ** szCell[] array contains the size in bytes of each cell. This function
6962 ** replaces the current contents of page pPg with the contents of the cell
6963 ** array.
6964 **
6965 ** Some of the cells in apCell[] may currently be stored in pPg. This
6966 ** function works around problems caused by this by making a copy of any
6967 ** such cells before overwriting the page data.
6968 **
6969 ** The MemPage.nFree field is invalidated by this function. It is the
6970 ** responsibility of the caller to set it correctly.
6971 */
6972 static int rebuildPage(
6973   CellArray *pCArray,             /* Content to be added to page pPg */
6974   int iFirst,                     /* First cell in pCArray to use */
6975   int nCell,                      /* Final number of cells on page */
6976   MemPage *pPg                    /* The page to be reconstructed */
6977 ){
6978   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
6979   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
6980   const int usableSize = pPg->pBt->usableSize;
6981   u8 * const pEnd = &aData[usableSize];
6982   int i = iFirst;                 /* Which cell to copy from pCArray*/
6983   u32 j;                          /* Start of cell content area */
6984   int iEnd = i+nCell;             /* Loop terminator */
6985   u8 *pCellptr = pPg->aCellIdx;
6986   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6987   u8 *pData;
6988   int k;                          /* Current slot in pCArray->apEnd[] */
6989   u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
6990 
6991   assert( i<iEnd );
6992   j = get2byte(&aData[hdr+5]);
6993   if( NEVER(j>(u32)usableSize) ){ j = 0; }
6994   memcpy(&pTmp[j], &aData[j], usableSize - j);
6995 
6996   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
6997   pSrcEnd = pCArray->apEnd[k];
6998 
6999   pData = pEnd;
7000   while( 1/*exit by break*/ ){
7001     u8 *pCell = pCArray->apCell[i];
7002     u16 sz = pCArray->szCell[i];
7003     assert( sz>0 );
7004     if( SQLITE_WITHIN(pCell,aData,pEnd) ){
7005       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7006       pCell = &pTmp[pCell - aData];
7007     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7008            && (uptr)(pCell)<(uptr)pSrcEnd
7009     ){
7010       return SQLITE_CORRUPT_BKPT;
7011     }
7012 
7013     pData -= sz;
7014     put2byte(pCellptr, (pData - aData));
7015     pCellptr += 2;
7016     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7017     memcpy(pData, pCell, sz);
7018     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7019     testcase( sz!=pPg->xCellSize(pPg,pCell) )
7020     i++;
7021     if( i>=iEnd ) break;
7022     if( pCArray->ixNx[k]<=i ){
7023       k++;
7024       pSrcEnd = pCArray->apEnd[k];
7025     }
7026   }
7027 
7028   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7029   pPg->nCell = nCell;
7030   pPg->nOverflow = 0;
7031 
7032   put2byte(&aData[hdr+1], 0);
7033   put2byte(&aData[hdr+3], pPg->nCell);
7034   put2byte(&aData[hdr+5], pData - aData);
7035   aData[hdr+7] = 0x00;
7036   return SQLITE_OK;
7037 }
7038 
7039 /*
7040 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7041 ** This function attempts to add the cells stored in the array to page pPg.
7042 ** If it cannot (because the page needs to be defragmented before the cells
7043 ** will fit), non-zero is returned. Otherwise, if the cells are added
7044 ** successfully, zero is returned.
7045 **
7046 ** Argument pCellptr points to the first entry in the cell-pointer array
7047 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7048 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7049 ** cell in the array. It is the responsibility of the caller to ensure
7050 ** that it is safe to overwrite this part of the cell-pointer array.
7051 **
7052 ** When this function is called, *ppData points to the start of the
7053 ** content area on page pPg. If the size of the content area is extended,
7054 ** *ppData is updated to point to the new start of the content area
7055 ** before returning.
7056 **
7057 ** Finally, argument pBegin points to the byte immediately following the
7058 ** end of the space required by this page for the cell-pointer area (for
7059 ** all cells - not just those inserted by the current call). If the content
7060 ** area must be extended to before this point in order to accomodate all
7061 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7062 */
7063 static int pageInsertArray(
7064   MemPage *pPg,                   /* Page to add cells to */
7065   u8 *pBegin,                     /* End of cell-pointer array */
7066   u8 **ppData,                    /* IN/OUT: Page content-area pointer */
7067   u8 *pCellptr,                   /* Pointer to cell-pointer area */
7068   int iFirst,                     /* Index of first cell to add */
7069   int nCell,                      /* Number of cells to add to pPg */
7070   CellArray *pCArray              /* Array of cells */
7071 ){
7072   int i = iFirst;                 /* Loop counter - cell index to insert */
7073   u8 *aData = pPg->aData;         /* Complete page */
7074   u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
7075   int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
7076   int k;                          /* Current slot in pCArray->apEnd[] */
7077   u8 *pEnd;                       /* Maximum extent of cell data */
7078   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
7079   if( iEnd<=iFirst ) return 0;
7080   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7081   pEnd = pCArray->apEnd[k];
7082   while( 1 /*Exit by break*/ ){
7083     int sz, rc;
7084     u8 *pSlot;
7085     assert( pCArray->szCell[i]!=0 );
7086     sz = pCArray->szCell[i];
7087     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7088       if( (pData - pBegin)<sz ) return 1;
7089       pData -= sz;
7090       pSlot = pData;
7091     }
7092     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7093     ** database.  But they might for a corrupt database.  Hence use memmove()
7094     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7095     assert( (pSlot+sz)<=pCArray->apCell[i]
7096          || pSlot>=(pCArray->apCell[i]+sz)
7097          || CORRUPT_DB );
7098     if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7099      && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7100     ){
7101       assert( CORRUPT_DB );
7102       (void)SQLITE_CORRUPT_BKPT;
7103       return 1;
7104     }
7105     memmove(pSlot, pCArray->apCell[i], sz);
7106     put2byte(pCellptr, (pSlot - aData));
7107     pCellptr += 2;
7108     i++;
7109     if( i>=iEnd ) break;
7110     if( pCArray->ixNx[k]<=i ){
7111       k++;
7112       pEnd = pCArray->apEnd[k];
7113     }
7114   }
7115   *ppData = pData;
7116   return 0;
7117 }
7118 
7119 /*
7120 ** The pCArray object contains pointers to b-tree cells and their sizes.
7121 **
7122 ** This function adds the space associated with each cell in the array
7123 ** that is currently stored within the body of pPg to the pPg free-list.
7124 ** The cell-pointers and other fields of the page are not updated.
7125 **
7126 ** This function returns the total number of cells added to the free-list.
7127 */
7128 static int pageFreeArray(
7129   MemPage *pPg,                   /* Page to edit */
7130   int iFirst,                     /* First cell to delete */
7131   int nCell,                      /* Cells to delete */
7132   CellArray *pCArray              /* Array of cells */
7133 ){
7134   u8 * const aData = pPg->aData;
7135   u8 * const pEnd = &aData[pPg->pBt->usableSize];
7136   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7137   int nRet = 0;
7138   int i;
7139   int iEnd = iFirst + nCell;
7140   u8 *pFree = 0;
7141   int szFree = 0;
7142 
7143   for(i=iFirst; i<iEnd; i++){
7144     u8 *pCell = pCArray->apCell[i];
7145     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7146       int sz;
7147       /* No need to use cachedCellSize() here.  The sizes of all cells that
7148       ** are to be freed have already been computing while deciding which
7149       ** cells need freeing */
7150       sz = pCArray->szCell[i];  assert( sz>0 );
7151       if( pFree!=(pCell + sz) ){
7152         if( pFree ){
7153           assert( pFree>aData && (pFree - aData)<65536 );
7154           freeSpace(pPg, (u16)(pFree - aData), szFree);
7155         }
7156         pFree = pCell;
7157         szFree = sz;
7158         if( pFree+sz>pEnd ) return 0;
7159       }else{
7160         pFree = pCell;
7161         szFree += sz;
7162       }
7163       nRet++;
7164     }
7165   }
7166   if( pFree ){
7167     assert( pFree>aData && (pFree - aData)<65536 );
7168     freeSpace(pPg, (u16)(pFree - aData), szFree);
7169   }
7170   return nRet;
7171 }
7172 
7173 /*
7174 ** pCArray contains pointers to and sizes of all cells in the page being
7175 ** balanced.  The current page, pPg, has pPg->nCell cells starting with
7176 ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
7177 ** starting at apCell[iNew].
7178 **
7179 ** This routine makes the necessary adjustments to pPg so that it contains
7180 ** the correct cells after being balanced.
7181 **
7182 ** The pPg->nFree field is invalid when this function returns. It is the
7183 ** responsibility of the caller to set it correctly.
7184 */
7185 static int editPage(
7186   MemPage *pPg,                   /* Edit this page */
7187   int iOld,                       /* Index of first cell currently on page */
7188   int iNew,                       /* Index of new first cell on page */
7189   int nNew,                       /* Final number of cells on page */
7190   CellArray *pCArray              /* Array of cells and sizes */
7191 ){
7192   u8 * const aData = pPg->aData;
7193   const int hdr = pPg->hdrOffset;
7194   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7195   int nCell = pPg->nCell;       /* Cells stored on pPg */
7196   u8 *pData;
7197   u8 *pCellptr;
7198   int i;
7199   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7200   int iNewEnd = iNew + nNew;
7201 
7202 #ifdef SQLITE_DEBUG
7203   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7204   memcpy(pTmp, aData, pPg->pBt->usableSize);
7205 #endif
7206 
7207   /* Remove cells from the start and end of the page */
7208   assert( nCell>=0 );
7209   if( iOld<iNew ){
7210     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7211     if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7212     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7213     nCell -= nShift;
7214   }
7215   if( iNewEnd < iOldEnd ){
7216     int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7217     assert( nCell>=nTail );
7218     nCell -= nTail;
7219   }
7220 
7221   pData = &aData[get2byteNotZero(&aData[hdr+5])];
7222   if( pData<pBegin ) goto editpage_fail;
7223 
7224   /* Add cells to the start of the page */
7225   if( iNew<iOld ){
7226     int nAdd = MIN(nNew,iOld-iNew);
7227     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7228     assert( nAdd>=0 );
7229     pCellptr = pPg->aCellIdx;
7230     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7231     if( pageInsertArray(
7232           pPg, pBegin, &pData, pCellptr,
7233           iNew, nAdd, pCArray
7234     ) ) goto editpage_fail;
7235     nCell += nAdd;
7236   }
7237 
7238   /* Add any overflow cells */
7239   for(i=0; i<pPg->nOverflow; i++){
7240     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7241     if( iCell>=0 && iCell<nNew ){
7242       pCellptr = &pPg->aCellIdx[iCell * 2];
7243       if( nCell>iCell ){
7244         memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7245       }
7246       nCell++;
7247       cachedCellSize(pCArray, iCell+iNew);
7248       if( pageInsertArray(
7249             pPg, pBegin, &pData, pCellptr,
7250             iCell+iNew, 1, pCArray
7251       ) ) goto editpage_fail;
7252     }
7253   }
7254 
7255   /* Append cells to the end of the page */
7256   assert( nCell>=0 );
7257   pCellptr = &pPg->aCellIdx[nCell*2];
7258   if( pageInsertArray(
7259         pPg, pBegin, &pData, pCellptr,
7260         iNew+nCell, nNew-nCell, pCArray
7261   ) ) goto editpage_fail;
7262 
7263   pPg->nCell = nNew;
7264   pPg->nOverflow = 0;
7265 
7266   put2byte(&aData[hdr+3], pPg->nCell);
7267   put2byte(&aData[hdr+5], pData - aData);
7268 
7269 #ifdef SQLITE_DEBUG
7270   for(i=0; i<nNew && !CORRUPT_DB; i++){
7271     u8 *pCell = pCArray->apCell[i+iNew];
7272     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7273     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7274       pCell = &pTmp[pCell - aData];
7275     }
7276     assert( 0==memcmp(pCell, &aData[iOff],
7277             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7278   }
7279 #endif
7280 
7281   return SQLITE_OK;
7282  editpage_fail:
7283   /* Unable to edit this page. Rebuild it from scratch instead. */
7284   populateCellCache(pCArray, iNew, nNew);
7285   return rebuildPage(pCArray, iNew, nNew, pPg);
7286 }
7287 
7288 
7289 #ifndef SQLITE_OMIT_QUICKBALANCE
7290 /*
7291 ** This version of balance() handles the common special case where
7292 ** a new entry is being inserted on the extreme right-end of the
7293 ** tree, in other words, when the new entry will become the largest
7294 ** entry in the tree.
7295 **
7296 ** Instead of trying to balance the 3 right-most leaf pages, just add
7297 ** a new page to the right-hand side and put the one new entry in
7298 ** that page.  This leaves the right side of the tree somewhat
7299 ** unbalanced.  But odds are that we will be inserting new entries
7300 ** at the end soon afterwards so the nearly empty page will quickly
7301 ** fill up.  On average.
7302 **
7303 ** pPage is the leaf page which is the right-most page in the tree.
7304 ** pParent is its parent.  pPage must have a single overflow entry
7305 ** which is also the right-most entry on the page.
7306 **
7307 ** The pSpace buffer is used to store a temporary copy of the divider
7308 ** cell that will be inserted into pParent. Such a cell consists of a 4
7309 ** byte page number followed by a variable length integer. In other
7310 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7311 ** least 13 bytes in size.
7312 */
7313 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7314   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7315   MemPage *pNew;                       /* Newly allocated page */
7316   int rc;                              /* Return Code */
7317   Pgno pgnoNew;                        /* Page number of pNew */
7318 
7319   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7320   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7321   assert( pPage->nOverflow==1 );
7322 
7323   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
7324   assert( pPage->nFree>=0 );
7325   assert( pParent->nFree>=0 );
7326 
7327   /* Allocate a new page. This page will become the right-sibling of
7328   ** pPage. Make the parent page writable, so that the new divider cell
7329   ** may be inserted. If both these operations are successful, proceed.
7330   */
7331   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7332 
7333   if( rc==SQLITE_OK ){
7334 
7335     u8 *pOut = &pSpace[4];
7336     u8 *pCell = pPage->apOvfl[0];
7337     u16 szCell = pPage->xCellSize(pPage, pCell);
7338     u8 *pStop;
7339     CellArray b;
7340 
7341     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7342     assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7343     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7344     b.nCell = 1;
7345     b.pRef = pPage;
7346     b.apCell = &pCell;
7347     b.szCell = &szCell;
7348     b.apEnd[0] = pPage->aDataEnd;
7349     b.ixNx[0] = 2;
7350     rc = rebuildPage(&b, 0, 1, pNew);
7351     if( NEVER(rc) ){
7352       releasePage(pNew);
7353       return rc;
7354     }
7355     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7356 
7357     /* If this is an auto-vacuum database, update the pointer map
7358     ** with entries for the new page, and any pointer from the
7359     ** cell on the page to an overflow page. If either of these
7360     ** operations fails, the return code is set, but the contents
7361     ** of the parent page are still manipulated by thh code below.
7362     ** That is Ok, at this point the parent page is guaranteed to
7363     ** be marked as dirty. Returning an error code will cause a
7364     ** rollback, undoing any changes made to the parent page.
7365     */
7366     if( ISAUTOVACUUM ){
7367       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7368       if( szCell>pNew->minLocal ){
7369         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7370       }
7371     }
7372 
7373     /* Create a divider cell to insert into pParent. The divider cell
7374     ** consists of a 4-byte page number (the page number of pPage) and
7375     ** a variable length key value (which must be the same value as the
7376     ** largest key on pPage).
7377     **
7378     ** To find the largest key value on pPage, first find the right-most
7379     ** cell on pPage. The first two fields of this cell are the
7380     ** record-length (a variable length integer at most 32-bits in size)
7381     ** and the key value (a variable length integer, may have any value).
7382     ** The first of the while(...) loops below skips over the record-length
7383     ** field. The second while(...) loop copies the key value from the
7384     ** cell on pPage into the pSpace buffer.
7385     */
7386     pCell = findCell(pPage, pPage->nCell-1);
7387     pStop = &pCell[9];
7388     while( (*(pCell++)&0x80) && pCell<pStop );
7389     pStop = &pCell[9];
7390     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7391 
7392     /* Insert the new divider cell into pParent. */
7393     if( rc==SQLITE_OK ){
7394       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7395                    0, pPage->pgno, &rc);
7396     }
7397 
7398     /* Set the right-child pointer of pParent to point to the new page. */
7399     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7400 
7401     /* Release the reference to the new page. */
7402     releasePage(pNew);
7403   }
7404 
7405   return rc;
7406 }
7407 #endif /* SQLITE_OMIT_QUICKBALANCE */
7408 
7409 #if 0
7410 /*
7411 ** This function does not contribute anything to the operation of SQLite.
7412 ** it is sometimes activated temporarily while debugging code responsible
7413 ** for setting pointer-map entries.
7414 */
7415 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7416   int i, j;
7417   for(i=0; i<nPage; i++){
7418     Pgno n;
7419     u8 e;
7420     MemPage *pPage = apPage[i];
7421     BtShared *pBt = pPage->pBt;
7422     assert( pPage->isInit );
7423 
7424     for(j=0; j<pPage->nCell; j++){
7425       CellInfo info;
7426       u8 *z;
7427 
7428       z = findCell(pPage, j);
7429       pPage->xParseCell(pPage, z, &info);
7430       if( info.nLocal<info.nPayload ){
7431         Pgno ovfl = get4byte(&z[info.nSize-4]);
7432         ptrmapGet(pBt, ovfl, &e, &n);
7433         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7434       }
7435       if( !pPage->leaf ){
7436         Pgno child = get4byte(z);
7437         ptrmapGet(pBt, child, &e, &n);
7438         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7439       }
7440     }
7441     if( !pPage->leaf ){
7442       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7443       ptrmapGet(pBt, child, &e, &n);
7444       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7445     }
7446   }
7447   return 1;
7448 }
7449 #endif
7450 
7451 /*
7452 ** This function is used to copy the contents of the b-tree node stored
7453 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7454 ** the pointer-map entries for each child page are updated so that the
7455 ** parent page stored in the pointer map is page pTo. If pFrom contained
7456 ** any cells with overflow page pointers, then the corresponding pointer
7457 ** map entries are also updated so that the parent page is page pTo.
7458 **
7459 ** If pFrom is currently carrying any overflow cells (entries in the
7460 ** MemPage.apOvfl[] array), they are not copied to pTo.
7461 **
7462 ** Before returning, page pTo is reinitialized using btreeInitPage().
7463 **
7464 ** The performance of this function is not critical. It is only used by
7465 ** the balance_shallower() and balance_deeper() procedures, neither of
7466 ** which are called often under normal circumstances.
7467 */
7468 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7469   if( (*pRC)==SQLITE_OK ){
7470     BtShared * const pBt = pFrom->pBt;
7471     u8 * const aFrom = pFrom->aData;
7472     u8 * const aTo = pTo->aData;
7473     int const iFromHdr = pFrom->hdrOffset;
7474     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7475     int rc;
7476     int iData;
7477 
7478 
7479     assert( pFrom->isInit );
7480     assert( pFrom->nFree>=iToHdr );
7481     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7482 
7483     /* Copy the b-tree node content from page pFrom to page pTo. */
7484     iData = get2byte(&aFrom[iFromHdr+5]);
7485     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7486     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7487 
7488     /* Reinitialize page pTo so that the contents of the MemPage structure
7489     ** match the new data. The initialization of pTo can actually fail under
7490     ** fairly obscure circumstances, even though it is a copy of initialized
7491     ** page pFrom.
7492     */
7493     pTo->isInit = 0;
7494     rc = btreeInitPage(pTo);
7495     if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7496     if( rc!=SQLITE_OK ){
7497       *pRC = rc;
7498       return;
7499     }
7500 
7501     /* If this is an auto-vacuum database, update the pointer-map entries
7502     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7503     */
7504     if( ISAUTOVACUUM ){
7505       *pRC = setChildPtrmaps(pTo);
7506     }
7507   }
7508 }
7509 
7510 /*
7511 ** This routine redistributes cells on the iParentIdx'th child of pParent
7512 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7513 ** same amount of free space. Usually a single sibling on either side of the
7514 ** page are used in the balancing, though both siblings might come from one
7515 ** side if the page is the first or last child of its parent. If the page
7516 ** has fewer than 2 siblings (something which can only happen if the page
7517 ** is a root page or a child of a root page) then all available siblings
7518 ** participate in the balancing.
7519 **
7520 ** The number of siblings of the page might be increased or decreased by
7521 ** one or two in an effort to keep pages nearly full but not over full.
7522 **
7523 ** Note that when this routine is called, some of the cells on the page
7524 ** might not actually be stored in MemPage.aData[]. This can happen
7525 ** if the page is overfull. This routine ensures that all cells allocated
7526 ** to the page and its siblings fit into MemPage.aData[] before returning.
7527 **
7528 ** In the course of balancing the page and its siblings, cells may be
7529 ** inserted into or removed from the parent page (pParent). Doing so
7530 ** may cause the parent page to become overfull or underfull. If this
7531 ** happens, it is the responsibility of the caller to invoke the correct
7532 ** balancing routine to fix this problem (see the balance() routine).
7533 **
7534 ** If this routine fails for any reason, it might leave the database
7535 ** in a corrupted state. So if this routine fails, the database should
7536 ** be rolled back.
7537 **
7538 ** The third argument to this function, aOvflSpace, is a pointer to a
7539 ** buffer big enough to hold one page. If while inserting cells into the parent
7540 ** page (pParent) the parent page becomes overfull, this buffer is
7541 ** used to store the parent's overflow cells. Because this function inserts
7542 ** a maximum of four divider cells into the parent page, and the maximum
7543 ** size of a cell stored within an internal node is always less than 1/4
7544 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7545 ** enough for all overflow cells.
7546 **
7547 ** If aOvflSpace is set to a null pointer, this function returns
7548 ** SQLITE_NOMEM.
7549 */
7550 static int balance_nonroot(
7551   MemPage *pParent,               /* Parent page of siblings being balanced */
7552   int iParentIdx,                 /* Index of "the page" in pParent */
7553   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7554   int isRoot,                     /* True if pParent is a root-page */
7555   int bBulk                       /* True if this call is part of a bulk load */
7556 ){
7557   BtShared *pBt;               /* The whole database */
7558   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7559   int nNew = 0;                /* Number of pages in apNew[] */
7560   int nOld;                    /* Number of pages in apOld[] */
7561   int i, j, k;                 /* Loop counters */
7562   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7563   int rc = SQLITE_OK;          /* The return code */
7564   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7565   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7566   int usableSpace;             /* Bytes in pPage beyond the header */
7567   int pageFlags;               /* Value of pPage->aData[0] */
7568   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7569   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7570   int szScratch;               /* Size of scratch memory requested */
7571   MemPage *apOld[NB];          /* pPage and up to two siblings */
7572   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7573   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7574   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7575   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7576   int cntOld[NB+2];            /* Old index in b.apCell[] */
7577   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7578   u8 *aSpace1;                 /* Space for copies of dividers cells */
7579   Pgno pgno;                   /* Temp var to store a page number in */
7580   u8 abDone[NB+2];             /* True after i'th new page is populated */
7581   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7582   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7583   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7584   CellArray b;                  /* Parsed information on cells being balanced */
7585 
7586   memset(abDone, 0, sizeof(abDone));
7587   b.nCell = 0;
7588   b.apCell = 0;
7589   pBt = pParent->pBt;
7590   assert( sqlite3_mutex_held(pBt->mutex) );
7591   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7592 
7593   /* At this point pParent may have at most one overflow cell. And if
7594   ** this overflow cell is present, it must be the cell with
7595   ** index iParentIdx. This scenario comes about when this function
7596   ** is called (indirectly) from sqlite3BtreeDelete().
7597   */
7598   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7599   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7600 
7601   if( !aOvflSpace ){
7602     return SQLITE_NOMEM_BKPT;
7603   }
7604   assert( pParent->nFree>=0 );
7605 
7606   /* Find the sibling pages to balance. Also locate the cells in pParent
7607   ** that divide the siblings. An attempt is made to find NN siblings on
7608   ** either side of pPage. More siblings are taken from one side, however,
7609   ** if there are fewer than NN siblings on the other side. If pParent
7610   ** has NB or fewer children then all children of pParent are taken.
7611   **
7612   ** This loop also drops the divider cells from the parent page. This
7613   ** way, the remainder of the function does not have to deal with any
7614   ** overflow cells in the parent page, since if any existed they will
7615   ** have already been removed.
7616   */
7617   i = pParent->nOverflow + pParent->nCell;
7618   if( i<2 ){
7619     nxDiv = 0;
7620   }else{
7621     assert( bBulk==0 || bBulk==1 );
7622     if( iParentIdx==0 ){
7623       nxDiv = 0;
7624     }else if( iParentIdx==i ){
7625       nxDiv = i-2+bBulk;
7626     }else{
7627       nxDiv = iParentIdx-1;
7628     }
7629     i = 2-bBulk;
7630   }
7631   nOld = i+1;
7632   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7633     pRight = &pParent->aData[pParent->hdrOffset+8];
7634   }else{
7635     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7636   }
7637   pgno = get4byte(pRight);
7638   while( 1 ){
7639     rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7640     if( rc ){
7641       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7642       goto balance_cleanup;
7643     }
7644     if( apOld[i]->nFree<0 ){
7645       rc = btreeComputeFreeSpace(apOld[i]);
7646       if( rc ){
7647         memset(apOld, 0, (i)*sizeof(MemPage*));
7648         goto balance_cleanup;
7649       }
7650     }
7651     if( (i--)==0 ) break;
7652 
7653     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7654       apDiv[i] = pParent->apOvfl[0];
7655       pgno = get4byte(apDiv[i]);
7656       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7657       pParent->nOverflow = 0;
7658     }else{
7659       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7660       pgno = get4byte(apDiv[i]);
7661       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7662 
7663       /* Drop the cell from the parent page. apDiv[i] still points to
7664       ** the cell within the parent, even though it has been dropped.
7665       ** This is safe because dropping a cell only overwrites the first
7666       ** four bytes of it, and this function does not need the first
7667       ** four bytes of the divider cell. So the pointer is safe to use
7668       ** later on.
7669       **
7670       ** But not if we are in secure-delete mode. In secure-delete mode,
7671       ** the dropCell() routine will overwrite the entire cell with zeroes.
7672       ** In this case, temporarily copy the cell into the aOvflSpace[]
7673       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7674       ** is allocated.  */
7675       if( pBt->btsFlags & BTS_FAST_SECURE ){
7676         int iOff;
7677 
7678         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7679         if( (iOff+szNew[i])>(int)pBt->usableSize ){
7680           rc = SQLITE_CORRUPT_BKPT;
7681           memset(apOld, 0, (i+1)*sizeof(MemPage*));
7682           goto balance_cleanup;
7683         }else{
7684           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7685           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7686         }
7687       }
7688       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7689     }
7690   }
7691 
7692   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7693   ** alignment */
7694   nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
7695   nMaxCells = (nMaxCells + 3)&~3;
7696 
7697   /*
7698   ** Allocate space for memory structures
7699   */
7700   szScratch =
7701        nMaxCells*sizeof(u8*)                       /* b.apCell */
7702      + nMaxCells*sizeof(u16)                       /* b.szCell */
7703      + pBt->pageSize;                              /* aSpace1 */
7704 
7705   assert( szScratch<=7*(int)pBt->pageSize );
7706   b.apCell = sqlite3StackAllocRaw(0, szScratch );
7707   if( b.apCell==0 ){
7708     rc = SQLITE_NOMEM_BKPT;
7709     goto balance_cleanup;
7710   }
7711   b.szCell = (u16*)&b.apCell[nMaxCells];
7712   aSpace1 = (u8*)&b.szCell[nMaxCells];
7713   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7714 
7715   /*
7716   ** Load pointers to all cells on sibling pages and the divider cells
7717   ** into the local b.apCell[] array.  Make copies of the divider cells
7718   ** into space obtained from aSpace1[]. The divider cells have already
7719   ** been removed from pParent.
7720   **
7721   ** If the siblings are on leaf pages, then the child pointers of the
7722   ** divider cells are stripped from the cells before they are copied
7723   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7724   ** child pointers.  If siblings are not leaves, then all cell in
7725   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7726   ** are alike.
7727   **
7728   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7729   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7730   */
7731   b.pRef = apOld[0];
7732   leafCorrection = b.pRef->leaf*4;
7733   leafData = b.pRef->intKeyLeaf;
7734   for(i=0; i<nOld; i++){
7735     MemPage *pOld = apOld[i];
7736     int limit = pOld->nCell;
7737     u8 *aData = pOld->aData;
7738     u16 maskPage = pOld->maskPage;
7739     u8 *piCell = aData + pOld->cellOffset;
7740     u8 *piEnd;
7741     VVA_ONLY( int nCellAtStart = b.nCell; )
7742 
7743     /* Verify that all sibling pages are of the same "type" (table-leaf,
7744     ** table-interior, index-leaf, or index-interior).
7745     */
7746     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7747       rc = SQLITE_CORRUPT_BKPT;
7748       goto balance_cleanup;
7749     }
7750 
7751     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7752     ** contains overflow cells, include them in the b.apCell[] array
7753     ** in the correct spot.
7754     **
7755     ** Note that when there are multiple overflow cells, it is always the
7756     ** case that they are sequential and adjacent.  This invariant arises
7757     ** because multiple overflows can only occurs when inserting divider
7758     ** cells into a parent on a prior balance, and divider cells are always
7759     ** adjacent and are inserted in order.  There is an assert() tagged
7760     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7761     ** invariant.
7762     **
7763     ** This must be done in advance.  Once the balance starts, the cell
7764     ** offset section of the btree page will be overwritten and we will no
7765     ** long be able to find the cells if a pointer to each cell is not saved
7766     ** first.
7767     */
7768     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7769     if( pOld->nOverflow>0 ){
7770       if( NEVER(limit<pOld->aiOvfl[0]) ){
7771         rc = SQLITE_CORRUPT_BKPT;
7772         goto balance_cleanup;
7773       }
7774       limit = pOld->aiOvfl[0];
7775       for(j=0; j<limit; j++){
7776         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7777         piCell += 2;
7778         b.nCell++;
7779       }
7780       for(k=0; k<pOld->nOverflow; k++){
7781         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7782         b.apCell[b.nCell] = pOld->apOvfl[k];
7783         b.nCell++;
7784       }
7785     }
7786     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7787     while( piCell<piEnd ){
7788       assert( b.nCell<nMaxCells );
7789       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7790       piCell += 2;
7791       b.nCell++;
7792     }
7793     assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7794 
7795     cntOld[i] = b.nCell;
7796     if( i<nOld-1 && !leafData){
7797       u16 sz = (u16)szNew[i];
7798       u8 *pTemp;
7799       assert( b.nCell<nMaxCells );
7800       b.szCell[b.nCell] = sz;
7801       pTemp = &aSpace1[iSpace1];
7802       iSpace1 += sz;
7803       assert( sz<=pBt->maxLocal+23 );
7804       assert( iSpace1 <= (int)pBt->pageSize );
7805       memcpy(pTemp, apDiv[i], sz);
7806       b.apCell[b.nCell] = pTemp+leafCorrection;
7807       assert( leafCorrection==0 || leafCorrection==4 );
7808       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7809       if( !pOld->leaf ){
7810         assert( leafCorrection==0 );
7811         assert( pOld->hdrOffset==0 );
7812         /* The right pointer of the child page pOld becomes the left
7813         ** pointer of the divider cell */
7814         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7815       }else{
7816         assert( leafCorrection==4 );
7817         while( b.szCell[b.nCell]<4 ){
7818           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7819           ** does exist, pad it with 0x00 bytes. */
7820           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7821           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7822           aSpace1[iSpace1++] = 0x00;
7823           b.szCell[b.nCell]++;
7824         }
7825       }
7826       b.nCell++;
7827     }
7828   }
7829 
7830   /*
7831   ** Figure out the number of pages needed to hold all b.nCell cells.
7832   ** Store this number in "k".  Also compute szNew[] which is the total
7833   ** size of all cells on the i-th page and cntNew[] which is the index
7834   ** in b.apCell[] of the cell that divides page i from page i+1.
7835   ** cntNew[k] should equal b.nCell.
7836   **
7837   ** Values computed by this block:
7838   **
7839   **           k: The total number of sibling pages
7840   **    szNew[i]: Spaced used on the i-th sibling page.
7841   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7842   **              the right of the i-th sibling page.
7843   ** usableSpace: Number of bytes of space available on each sibling.
7844   **
7845   */
7846   usableSpace = pBt->usableSize - 12 + leafCorrection;
7847   for(i=k=0; i<nOld; i++, k++){
7848     MemPage *p = apOld[i];
7849     b.apEnd[k] = p->aDataEnd;
7850     b.ixNx[k] = cntOld[i];
7851     if( k && b.ixNx[k]==b.ixNx[k-1] ){
7852       k--;  /* Omit b.ixNx[] entry for child pages with no cells */
7853     }
7854     if( !leafData ){
7855       k++;
7856       b.apEnd[k] = pParent->aDataEnd;
7857       b.ixNx[k] = cntOld[i]+1;
7858     }
7859     assert( p->nFree>=0 );
7860     szNew[i] = usableSpace - p->nFree;
7861     for(j=0; j<p->nOverflow; j++){
7862       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7863     }
7864     cntNew[i] = cntOld[i];
7865   }
7866   k = nOld;
7867   for(i=0; i<k; i++){
7868     int sz;
7869     while( szNew[i]>usableSpace ){
7870       if( i+1>=k ){
7871         k = i+2;
7872         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7873         szNew[k-1] = 0;
7874         cntNew[k-1] = b.nCell;
7875       }
7876       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7877       szNew[i] -= sz;
7878       if( !leafData ){
7879         if( cntNew[i]<b.nCell ){
7880           sz = 2 + cachedCellSize(&b, cntNew[i]);
7881         }else{
7882           sz = 0;
7883         }
7884       }
7885       szNew[i+1] += sz;
7886       cntNew[i]--;
7887     }
7888     while( cntNew[i]<b.nCell ){
7889       sz = 2 + cachedCellSize(&b, cntNew[i]);
7890       if( szNew[i]+sz>usableSpace ) break;
7891       szNew[i] += sz;
7892       cntNew[i]++;
7893       if( !leafData ){
7894         if( cntNew[i]<b.nCell ){
7895           sz = 2 + cachedCellSize(&b, cntNew[i]);
7896         }else{
7897           sz = 0;
7898         }
7899       }
7900       szNew[i+1] -= sz;
7901     }
7902     if( cntNew[i]>=b.nCell ){
7903       k = i+1;
7904     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7905       rc = SQLITE_CORRUPT_BKPT;
7906       goto balance_cleanup;
7907     }
7908   }
7909 
7910   /*
7911   ** The packing computed by the previous block is biased toward the siblings
7912   ** on the left side (siblings with smaller keys). The left siblings are
7913   ** always nearly full, while the right-most sibling might be nearly empty.
7914   ** The next block of code attempts to adjust the packing of siblings to
7915   ** get a better balance.
7916   **
7917   ** This adjustment is more than an optimization.  The packing above might
7918   ** be so out of balance as to be illegal.  For example, the right-most
7919   ** sibling might be completely empty.  This adjustment is not optional.
7920   */
7921   for(i=k-1; i>0; i--){
7922     int szRight = szNew[i];  /* Size of sibling on the right */
7923     int szLeft = szNew[i-1]; /* Size of sibling on the left */
7924     int r;              /* Index of right-most cell in left sibling */
7925     int d;              /* Index of first cell to the left of right sibling */
7926 
7927     r = cntNew[i-1] - 1;
7928     d = r + 1 - leafData;
7929     (void)cachedCellSize(&b, d);
7930     do{
7931       assert( d<nMaxCells );
7932       assert( r<nMaxCells );
7933       (void)cachedCellSize(&b, r);
7934       if( szRight!=0
7935        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7936         break;
7937       }
7938       szRight += b.szCell[d] + 2;
7939       szLeft -= b.szCell[r] + 2;
7940       cntNew[i-1] = r;
7941       r--;
7942       d--;
7943     }while( r>=0 );
7944     szNew[i] = szRight;
7945     szNew[i-1] = szLeft;
7946     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7947       rc = SQLITE_CORRUPT_BKPT;
7948       goto balance_cleanup;
7949     }
7950   }
7951 
7952   /* Sanity check:  For a non-corrupt database file one of the follwing
7953   ** must be true:
7954   **    (1) We found one or more cells (cntNew[0])>0), or
7955   **    (2) pPage is a virtual root page.  A virtual root page is when
7956   **        the real root page is page 1 and we are the only child of
7957   **        that page.
7958   */
7959   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7960   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7961     apOld[0]->pgno, apOld[0]->nCell,
7962     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7963     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7964   ));
7965 
7966   /*
7967   ** Allocate k new pages.  Reuse old pages where possible.
7968   */
7969   pageFlags = apOld[0]->aData[0];
7970   for(i=0; i<k; i++){
7971     MemPage *pNew;
7972     if( i<nOld ){
7973       pNew = apNew[i] = apOld[i];
7974       apOld[i] = 0;
7975       rc = sqlite3PagerWrite(pNew->pDbPage);
7976       nNew++;
7977       if( rc ) goto balance_cleanup;
7978     }else{
7979       assert( i>0 );
7980       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7981       if( rc ) goto balance_cleanup;
7982       zeroPage(pNew, pageFlags);
7983       apNew[i] = pNew;
7984       nNew++;
7985       cntOld[i] = b.nCell;
7986 
7987       /* Set the pointer-map entry for the new sibling page. */
7988       if( ISAUTOVACUUM ){
7989         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7990         if( rc!=SQLITE_OK ){
7991           goto balance_cleanup;
7992         }
7993       }
7994     }
7995   }
7996 
7997   /*
7998   ** Reassign page numbers so that the new pages are in ascending order.
7999   ** This helps to keep entries in the disk file in order so that a scan
8000   ** of the table is closer to a linear scan through the file. That in turn
8001   ** helps the operating system to deliver pages from the disk more rapidly.
8002   **
8003   ** An O(n^2) insertion sort algorithm is used, but since n is never more
8004   ** than (NB+2) (a small constant), that should not be a problem.
8005   **
8006   ** When NB==3, this one optimization makes the database about 25% faster
8007   ** for large insertions and deletions.
8008   */
8009   for(i=0; i<nNew; i++){
8010     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8011     aPgFlags[i] = apNew[i]->pDbPage->flags;
8012     for(j=0; j<i; j++){
8013       if( aPgno[j]==aPgno[i] ){
8014         /* This branch is taken if the set of sibling pages somehow contains
8015         ** duplicate entries. This can happen if the database is corrupt.
8016         ** It would be simpler to detect this as part of the loop below, but
8017         ** we do the detection here in order to avoid populating the pager
8018         ** cache with two separate objects associated with the same
8019         ** page number.  */
8020         assert( CORRUPT_DB );
8021         rc = SQLITE_CORRUPT_BKPT;
8022         goto balance_cleanup;
8023       }
8024     }
8025   }
8026   for(i=0; i<nNew; i++){
8027     int iBest = 0;                /* aPgno[] index of page number to use */
8028     for(j=1; j<nNew; j++){
8029       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8030     }
8031     pgno = aPgOrder[iBest];
8032     aPgOrder[iBest] = 0xffffffff;
8033     if( iBest!=i ){
8034       if( iBest>i ){
8035         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8036       }
8037       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8038       apNew[i]->pgno = pgno;
8039     }
8040   }
8041 
8042   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8043          "%d(%d nc=%d) %d(%d nc=%d)\n",
8044     apNew[0]->pgno, szNew[0], cntNew[0],
8045     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8046     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8047     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8048     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8049     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8050     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8051     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8052     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8053   ));
8054 
8055   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8056   assert( nNew>=1 && nNew<=ArraySize(apNew) );
8057   assert( apNew[nNew-1]!=0 );
8058   put4byte(pRight, apNew[nNew-1]->pgno);
8059 
8060   /* If the sibling pages are not leaves, ensure that the right-child pointer
8061   ** of the right-most new sibling page is set to the value that was
8062   ** originally in the same field of the right-most old sibling page. */
8063   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8064     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8065     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8066   }
8067 
8068   /* Make any required updates to pointer map entries associated with
8069   ** cells stored on sibling pages following the balance operation. Pointer
8070   ** map entries associated with divider cells are set by the insertCell()
8071   ** routine. The associated pointer map entries are:
8072   **
8073   **   a) if the cell contains a reference to an overflow chain, the
8074   **      entry associated with the first page in the overflow chain, and
8075   **
8076   **   b) if the sibling pages are not leaves, the child page associated
8077   **      with the cell.
8078   **
8079   ** If the sibling pages are not leaves, then the pointer map entry
8080   ** associated with the right-child of each sibling may also need to be
8081   ** updated. This happens below, after the sibling pages have been
8082   ** populated, not here.
8083   */
8084   if( ISAUTOVACUUM ){
8085     MemPage *pOld;
8086     MemPage *pNew = pOld = apNew[0];
8087     int cntOldNext = pNew->nCell + pNew->nOverflow;
8088     int iNew = 0;
8089     int iOld = 0;
8090 
8091     for(i=0; i<b.nCell; i++){
8092       u8 *pCell = b.apCell[i];
8093       while( i==cntOldNext ){
8094         iOld++;
8095         assert( iOld<nNew || iOld<nOld );
8096         assert( iOld>=0 && iOld<NB );
8097         pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8098         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8099       }
8100       if( i==cntNew[iNew] ){
8101         pNew = apNew[++iNew];
8102         if( !leafData ) continue;
8103       }
8104 
8105       /* Cell pCell is destined for new sibling page pNew. Originally, it
8106       ** was either part of sibling page iOld (possibly an overflow cell),
8107       ** or else the divider cell to the left of sibling page iOld. So,
8108       ** if sibling page iOld had the same page number as pNew, and if
8109       ** pCell really was a part of sibling page iOld (not a divider or
8110       ** overflow cell), we can skip updating the pointer map entries.  */
8111       if( iOld>=nNew
8112        || pNew->pgno!=aPgno[iOld]
8113        || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8114       ){
8115         if( !leafCorrection ){
8116           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8117         }
8118         if( cachedCellSize(&b,i)>pNew->minLocal ){
8119           ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8120         }
8121         if( rc ) goto balance_cleanup;
8122       }
8123     }
8124   }
8125 
8126   /* Insert new divider cells into pParent. */
8127   for(i=0; i<nNew-1; i++){
8128     u8 *pCell;
8129     u8 *pTemp;
8130     int sz;
8131     MemPage *pNew = apNew[i];
8132     j = cntNew[i];
8133 
8134     assert( j<nMaxCells );
8135     assert( b.apCell[j]!=0 );
8136     pCell = b.apCell[j];
8137     sz = b.szCell[j] + leafCorrection;
8138     pTemp = &aOvflSpace[iOvflSpace];
8139     if( !pNew->leaf ){
8140       memcpy(&pNew->aData[8], pCell, 4);
8141     }else if( leafData ){
8142       /* If the tree is a leaf-data tree, and the siblings are leaves,
8143       ** then there is no divider cell in b.apCell[]. Instead, the divider
8144       ** cell consists of the integer key for the right-most cell of
8145       ** the sibling-page assembled above only.
8146       */
8147       CellInfo info;
8148       j--;
8149       pNew->xParseCell(pNew, b.apCell[j], &info);
8150       pCell = pTemp;
8151       sz = 4 + putVarint(&pCell[4], info.nKey);
8152       pTemp = 0;
8153     }else{
8154       pCell -= 4;
8155       /* Obscure case for non-leaf-data trees: If the cell at pCell was
8156       ** previously stored on a leaf node, and its reported size was 4
8157       ** bytes, then it may actually be smaller than this
8158       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8159       ** any cell). But it is important to pass the correct size to
8160       ** insertCell(), so reparse the cell now.
8161       **
8162       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8163       ** and WITHOUT ROWID tables with exactly one column which is the
8164       ** primary key.
8165       */
8166       if( b.szCell[j]==4 ){
8167         assert(leafCorrection==4);
8168         sz = pParent->xCellSize(pParent, pCell);
8169       }
8170     }
8171     iOvflSpace += sz;
8172     assert( sz<=pBt->maxLocal+23 );
8173     assert( iOvflSpace <= (int)pBt->pageSize );
8174     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8175     if( rc!=SQLITE_OK ) goto balance_cleanup;
8176     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8177   }
8178 
8179   /* Now update the actual sibling pages. The order in which they are updated
8180   ** is important, as this code needs to avoid disrupting any page from which
8181   ** cells may still to be read. In practice, this means:
8182   **
8183   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8184   **      then it is not safe to update page apNew[iPg] until after
8185   **      the left-hand sibling apNew[iPg-1] has been updated.
8186   **
8187   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8188   **      then it is not safe to update page apNew[iPg] until after
8189   **      the right-hand sibling apNew[iPg+1] has been updated.
8190   **
8191   ** If neither of the above apply, the page is safe to update.
8192   **
8193   ** The iPg value in the following loop starts at nNew-1 goes down
8194   ** to 0, then back up to nNew-1 again, thus making two passes over
8195   ** the pages.  On the initial downward pass, only condition (1) above
8196   ** needs to be tested because (2) will always be true from the previous
8197   ** step.  On the upward pass, both conditions are always true, so the
8198   ** upwards pass simply processes pages that were missed on the downward
8199   ** pass.
8200   */
8201   for(i=1-nNew; i<nNew; i++){
8202     int iPg = i<0 ? -i : i;
8203     assert( iPg>=0 && iPg<nNew );
8204     if( abDone[iPg] ) continue;         /* Skip pages already processed */
8205     if( i>=0                            /* On the upwards pass, or... */
8206      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
8207     ){
8208       int iNew;
8209       int iOld;
8210       int nNewCell;
8211 
8212       /* Verify condition (1):  If cells are moving left, update iPg
8213       ** only after iPg-1 has already been updated. */
8214       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8215 
8216       /* Verify condition (2):  If cells are moving right, update iPg
8217       ** only after iPg+1 has already been updated. */
8218       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8219 
8220       if( iPg==0 ){
8221         iNew = iOld = 0;
8222         nNewCell = cntNew[0];
8223       }else{
8224         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8225         iNew = cntNew[iPg-1] + !leafData;
8226         nNewCell = cntNew[iPg] - iNew;
8227       }
8228 
8229       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8230       if( rc ) goto balance_cleanup;
8231       abDone[iPg]++;
8232       apNew[iPg]->nFree = usableSpace-szNew[iPg];
8233       assert( apNew[iPg]->nOverflow==0 );
8234       assert( apNew[iPg]->nCell==nNewCell );
8235     }
8236   }
8237 
8238   /* All pages have been processed exactly once */
8239   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8240 
8241   assert( nOld>0 );
8242   assert( nNew>0 );
8243 
8244   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8245     /* The root page of the b-tree now contains no cells. The only sibling
8246     ** page is the right-child of the parent. Copy the contents of the
8247     ** child page into the parent, decreasing the overall height of the
8248     ** b-tree structure by one. This is described as the "balance-shallower"
8249     ** sub-algorithm in some documentation.
8250     **
8251     ** If this is an auto-vacuum database, the call to copyNodeContent()
8252     ** sets all pointer-map entries corresponding to database image pages
8253     ** for which the pointer is stored within the content being copied.
8254     **
8255     ** It is critical that the child page be defragmented before being
8256     ** copied into the parent, because if the parent is page 1 then it will
8257     ** by smaller than the child due to the database header, and so all the
8258     ** free space needs to be up front.
8259     */
8260     assert( nNew==1 || CORRUPT_DB );
8261     rc = defragmentPage(apNew[0], -1);
8262     testcase( rc!=SQLITE_OK );
8263     assert( apNew[0]->nFree ==
8264         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8265           - apNew[0]->nCell*2)
8266       || rc!=SQLITE_OK
8267     );
8268     copyNodeContent(apNew[0], pParent, &rc);
8269     freePage(apNew[0], &rc);
8270   }else if( ISAUTOVACUUM && !leafCorrection ){
8271     /* Fix the pointer map entries associated with the right-child of each
8272     ** sibling page. All other pointer map entries have already been taken
8273     ** care of.  */
8274     for(i=0; i<nNew; i++){
8275       u32 key = get4byte(&apNew[i]->aData[8]);
8276       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8277     }
8278   }
8279 
8280   assert( pParent->isInit );
8281   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8282           nOld, nNew, b.nCell));
8283 
8284   /* Free any old pages that were not reused as new pages.
8285   */
8286   for(i=nNew; i<nOld; i++){
8287     freePage(apOld[i], &rc);
8288   }
8289 
8290 #if 0
8291   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8292     /* The ptrmapCheckPages() contains assert() statements that verify that
8293     ** all pointer map pages are set correctly. This is helpful while
8294     ** debugging. This is usually disabled because a corrupt database may
8295     ** cause an assert() statement to fail.  */
8296     ptrmapCheckPages(apNew, nNew);
8297     ptrmapCheckPages(&pParent, 1);
8298   }
8299 #endif
8300 
8301   /*
8302   ** Cleanup before returning.
8303   */
8304 balance_cleanup:
8305   sqlite3StackFree(0, b.apCell);
8306   for(i=0; i<nOld; i++){
8307     releasePage(apOld[i]);
8308   }
8309   for(i=0; i<nNew; i++){
8310     releasePage(apNew[i]);
8311   }
8312 
8313   return rc;
8314 }
8315 
8316 
8317 /*
8318 ** This function is called when the root page of a b-tree structure is
8319 ** overfull (has one or more overflow pages).
8320 **
8321 ** A new child page is allocated and the contents of the current root
8322 ** page, including overflow cells, are copied into the child. The root
8323 ** page is then overwritten to make it an empty page with the right-child
8324 ** pointer pointing to the new page.
8325 **
8326 ** Before returning, all pointer-map entries corresponding to pages
8327 ** that the new child-page now contains pointers to are updated. The
8328 ** entry corresponding to the new right-child pointer of the root
8329 ** page is also updated.
8330 **
8331 ** If successful, *ppChild is set to contain a reference to the child
8332 ** page and SQLITE_OK is returned. In this case the caller is required
8333 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8334 ** an error code is returned and *ppChild is set to 0.
8335 */
8336 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8337   int rc;                        /* Return value from subprocedures */
8338   MemPage *pChild = 0;           /* Pointer to a new child page */
8339   Pgno pgnoChild = 0;            /* Page number of the new child page */
8340   BtShared *pBt = pRoot->pBt;    /* The BTree */
8341 
8342   assert( pRoot->nOverflow>0 );
8343   assert( sqlite3_mutex_held(pBt->mutex) );
8344 
8345   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8346   ** page that will become the new right-child of pPage. Copy the contents
8347   ** of the node stored on pRoot into the new child page.
8348   */
8349   rc = sqlite3PagerWrite(pRoot->pDbPage);
8350   if( rc==SQLITE_OK ){
8351     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8352     copyNodeContent(pRoot, pChild, &rc);
8353     if( ISAUTOVACUUM ){
8354       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8355     }
8356   }
8357   if( rc ){
8358     *ppChild = 0;
8359     releasePage(pChild);
8360     return rc;
8361   }
8362   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8363   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8364   assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8365 
8366   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8367 
8368   /* Copy the overflow cells from pRoot to pChild */
8369   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8370          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8371   memcpy(pChild->apOvfl, pRoot->apOvfl,
8372          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8373   pChild->nOverflow = pRoot->nOverflow;
8374 
8375   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8376   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8377   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8378 
8379   *ppChild = pChild;
8380   return SQLITE_OK;
8381 }
8382 
8383 /*
8384 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8385 ** on the same B-tree as pCur.
8386 **
8387 ** This can if a database is corrupt with two or more SQL tables
8388 ** pointing to the same b-tree.  If an insert occurs on one SQL table
8389 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8390 ** table linked to the same b-tree.  If the secondary insert causes a
8391 ** rebalance, that can change content out from under the cursor on the
8392 ** first SQL table, violating invariants on the first insert.
8393 */
8394 static int anotherValidCursor(BtCursor *pCur){
8395   BtCursor *pOther;
8396   for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8397     if( pOther!=pCur
8398      && pOther->eState==CURSOR_VALID
8399      && pOther->pPage==pCur->pPage
8400     ){
8401       return SQLITE_CORRUPT_BKPT;
8402     }
8403   }
8404   return SQLITE_OK;
8405 }
8406 
8407 /*
8408 ** The page that pCur currently points to has just been modified in
8409 ** some way. This function figures out if this modification means the
8410 ** tree needs to be balanced, and if so calls the appropriate balancing
8411 ** routine. Balancing routines are:
8412 **
8413 **   balance_quick()
8414 **   balance_deeper()
8415 **   balance_nonroot()
8416 */
8417 static int balance(BtCursor *pCur){
8418   int rc = SQLITE_OK;
8419   const int nMin = pCur->pBt->usableSize * 2 / 3;
8420   u8 aBalanceQuickSpace[13];
8421   u8 *pFree = 0;
8422 
8423   VVA_ONLY( int balance_quick_called = 0 );
8424   VVA_ONLY( int balance_deeper_called = 0 );
8425 
8426   do {
8427     int iPage;
8428     MemPage *pPage = pCur->pPage;
8429 
8430     if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8431     if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8432       break;
8433     }else if( (iPage = pCur->iPage)==0 ){
8434       if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8435         /* The root page of the b-tree is overfull. In this case call the
8436         ** balance_deeper() function to create a new child for the root-page
8437         ** and copy the current contents of the root-page to it. The
8438         ** next iteration of the do-loop will balance the child page.
8439         */
8440         assert( balance_deeper_called==0 );
8441         VVA_ONLY( balance_deeper_called++ );
8442         rc = balance_deeper(pPage, &pCur->apPage[1]);
8443         if( rc==SQLITE_OK ){
8444           pCur->iPage = 1;
8445           pCur->ix = 0;
8446           pCur->aiIdx[0] = 0;
8447           pCur->apPage[0] = pPage;
8448           pCur->pPage = pCur->apPage[1];
8449           assert( pCur->pPage->nOverflow );
8450         }
8451       }else{
8452         break;
8453       }
8454     }else{
8455       MemPage * const pParent = pCur->apPage[iPage-1];
8456       int const iIdx = pCur->aiIdx[iPage-1];
8457 
8458       rc = sqlite3PagerWrite(pParent->pDbPage);
8459       if( rc==SQLITE_OK && pParent->nFree<0 ){
8460         rc = btreeComputeFreeSpace(pParent);
8461       }
8462       if( rc==SQLITE_OK ){
8463 #ifndef SQLITE_OMIT_QUICKBALANCE
8464         if( pPage->intKeyLeaf
8465          && pPage->nOverflow==1
8466          && pPage->aiOvfl[0]==pPage->nCell
8467          && pParent->pgno!=1
8468          && pParent->nCell==iIdx
8469         ){
8470           /* Call balance_quick() to create a new sibling of pPage on which
8471           ** to store the overflow cell. balance_quick() inserts a new cell
8472           ** into pParent, which may cause pParent overflow. If this
8473           ** happens, the next iteration of the do-loop will balance pParent
8474           ** use either balance_nonroot() or balance_deeper(). Until this
8475           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8476           ** buffer.
8477           **
8478           ** The purpose of the following assert() is to check that only a
8479           ** single call to balance_quick() is made for each call to this
8480           ** function. If this were not verified, a subtle bug involving reuse
8481           ** of the aBalanceQuickSpace[] might sneak in.
8482           */
8483           assert( balance_quick_called==0 );
8484           VVA_ONLY( balance_quick_called++ );
8485           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8486         }else
8487 #endif
8488         {
8489           /* In this case, call balance_nonroot() to redistribute cells
8490           ** between pPage and up to 2 of its sibling pages. This involves
8491           ** modifying the contents of pParent, which may cause pParent to
8492           ** become overfull or underfull. The next iteration of the do-loop
8493           ** will balance the parent page to correct this.
8494           **
8495           ** If the parent page becomes overfull, the overflow cell or cells
8496           ** are stored in the pSpace buffer allocated immediately below.
8497           ** A subsequent iteration of the do-loop will deal with this by
8498           ** calling balance_nonroot() (balance_deeper() may be called first,
8499           ** but it doesn't deal with overflow cells - just moves them to a
8500           ** different page). Once this subsequent call to balance_nonroot()
8501           ** has completed, it is safe to release the pSpace buffer used by
8502           ** the previous call, as the overflow cell data will have been
8503           ** copied either into the body of a database page or into the new
8504           ** pSpace buffer passed to the latter call to balance_nonroot().
8505           */
8506           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8507           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8508                                pCur->hints&BTREE_BULKLOAD);
8509           if( pFree ){
8510             /* If pFree is not NULL, it points to the pSpace buffer used
8511             ** by a previous call to balance_nonroot(). Its contents are
8512             ** now stored either on real database pages or within the
8513             ** new pSpace buffer, so it may be safely freed here. */
8514             sqlite3PageFree(pFree);
8515           }
8516 
8517           /* The pSpace buffer will be freed after the next call to
8518           ** balance_nonroot(), or just before this function returns, whichever
8519           ** comes first. */
8520           pFree = pSpace;
8521         }
8522       }
8523 
8524       pPage->nOverflow = 0;
8525 
8526       /* The next iteration of the do-loop balances the parent page. */
8527       releasePage(pPage);
8528       pCur->iPage--;
8529       assert( pCur->iPage>=0 );
8530       pCur->pPage = pCur->apPage[pCur->iPage];
8531     }
8532   }while( rc==SQLITE_OK );
8533 
8534   if( pFree ){
8535     sqlite3PageFree(pFree);
8536   }
8537   return rc;
8538 }
8539 
8540 /* Overwrite content from pX into pDest.  Only do the write if the
8541 ** content is different from what is already there.
8542 */
8543 static int btreeOverwriteContent(
8544   MemPage *pPage,           /* MemPage on which writing will occur */
8545   u8 *pDest,                /* Pointer to the place to start writing */
8546   const BtreePayload *pX,   /* Source of data to write */
8547   int iOffset,              /* Offset of first byte to write */
8548   int iAmt                  /* Number of bytes to be written */
8549 ){
8550   int nData = pX->nData - iOffset;
8551   if( nData<=0 ){
8552     /* Overwritting with zeros */
8553     int i;
8554     for(i=0; i<iAmt && pDest[i]==0; i++){}
8555     if( i<iAmt ){
8556       int rc = sqlite3PagerWrite(pPage->pDbPage);
8557       if( rc ) return rc;
8558       memset(pDest + i, 0, iAmt - i);
8559     }
8560   }else{
8561     if( nData<iAmt ){
8562       /* Mixed read data and zeros at the end.  Make a recursive call
8563       ** to write the zeros then fall through to write the real data */
8564       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8565                                  iAmt-nData);
8566       if( rc ) return rc;
8567       iAmt = nData;
8568     }
8569     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8570       int rc = sqlite3PagerWrite(pPage->pDbPage);
8571       if( rc ) return rc;
8572       /* In a corrupt database, it is possible for the source and destination
8573       ** buffers to overlap.  This is harmless since the database is already
8574       ** corrupt but it does cause valgrind and ASAN warnings.  So use
8575       ** memmove(). */
8576       memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8577     }
8578   }
8579   return SQLITE_OK;
8580 }
8581 
8582 /*
8583 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8584 ** contained in pX.
8585 */
8586 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8587   int iOffset;                        /* Next byte of pX->pData to write */
8588   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8589   int rc;                             /* Return code */
8590   MemPage *pPage = pCur->pPage;       /* Page being written */
8591   BtShared *pBt;                      /* Btree */
8592   Pgno ovflPgno;                      /* Next overflow page to write */
8593   u32 ovflPageSize;                   /* Size to write on overflow page */
8594 
8595   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8596    || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8597   ){
8598     return SQLITE_CORRUPT_BKPT;
8599   }
8600   /* Overwrite the local portion first */
8601   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8602                              0, pCur->info.nLocal);
8603   if( rc ) return rc;
8604   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8605 
8606   /* Now overwrite the overflow pages */
8607   iOffset = pCur->info.nLocal;
8608   assert( nTotal>=0 );
8609   assert( iOffset>=0 );
8610   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8611   pBt = pPage->pBt;
8612   ovflPageSize = pBt->usableSize - 4;
8613   do{
8614     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8615     if( rc ) return rc;
8616     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8617       rc = SQLITE_CORRUPT_BKPT;
8618     }else{
8619       if( iOffset+ovflPageSize<(u32)nTotal ){
8620         ovflPgno = get4byte(pPage->aData);
8621       }else{
8622         ovflPageSize = nTotal - iOffset;
8623       }
8624       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8625                                  iOffset, ovflPageSize);
8626     }
8627     sqlite3PagerUnref(pPage->pDbPage);
8628     if( rc ) return rc;
8629     iOffset += ovflPageSize;
8630   }while( iOffset<nTotal );
8631   return SQLITE_OK;
8632 }
8633 
8634 
8635 /*
8636 ** Insert a new record into the BTree.  The content of the new record
8637 ** is described by the pX object.  The pCur cursor is used only to
8638 ** define what table the record should be inserted into, and is left
8639 ** pointing at a random location.
8640 **
8641 ** For a table btree (used for rowid tables), only the pX.nKey value of
8642 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8643 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8644 ** hold the content of the row.
8645 **
8646 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8647 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8648 ** pX.pData,nData,nZero fields must be zero.
8649 **
8650 ** If the seekResult parameter is non-zero, then a successful call to
8651 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8652 ** been performed.  In other words, if seekResult!=0 then the cursor
8653 ** is currently pointing to a cell that will be adjacent to the cell
8654 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8655 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8656 ** that is larger than (pKey,nKey).
8657 **
8658 ** If seekResult==0, that means pCur is pointing at some unknown location.
8659 ** In that case, this routine must seek the cursor to the correct insertion
8660 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8661 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8662 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8663 ** to decode the key.
8664 */
8665 int sqlite3BtreeInsert(
8666   BtCursor *pCur,                /* Insert data into the table of this cursor */
8667   const BtreePayload *pX,        /* Content of the row to be inserted */
8668   int flags,                     /* True if this is likely an append */
8669   int seekResult                 /* Result of prior MovetoUnpacked() call */
8670 ){
8671   int rc;
8672   int loc = seekResult;          /* -1: before desired location  +1: after */
8673   int szNew = 0;
8674   int idx;
8675   MemPage *pPage;
8676   Btree *p = pCur->pBtree;
8677   BtShared *pBt = p->pBt;
8678   unsigned char *oldCell;
8679   unsigned char *newCell = 0;
8680 
8681   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8682   assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8683 
8684   if( pCur->eState==CURSOR_FAULT ){
8685     assert( pCur->skipNext!=SQLITE_OK );
8686     return pCur->skipNext;
8687   }
8688 
8689   assert( cursorOwnsBtShared(pCur) );
8690   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8691               && pBt->inTransaction==TRANS_WRITE
8692               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8693   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8694 
8695   /* Assert that the caller has been consistent. If this cursor was opened
8696   ** expecting an index b-tree, then the caller should be inserting blob
8697   ** keys with no associated data. If the cursor was opened expecting an
8698   ** intkey table, the caller should be inserting integer keys with a
8699   ** blob of associated data.  */
8700   assert( (pX->pKey==0)==(pCur->pKeyInfo==0) || (flags & BTREE_PREFORMAT) );
8701 
8702   /* Save the positions of any other cursors open on this table.
8703   **
8704   ** In some cases, the call to btreeMoveto() below is a no-op. For
8705   ** example, when inserting data into a table with auto-generated integer
8706   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8707   ** integer key to use. It then calls this function to actually insert the
8708   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8709   ** that the cursor is already where it needs to be and returns without
8710   ** doing any work. To avoid thwarting these optimizations, it is important
8711   ** not to clear the cursor here.
8712   */
8713   if( pCur->curFlags & BTCF_Multiple ){
8714     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8715     if( rc ) return rc;
8716   }
8717 
8718   if( pCur->pKeyInfo==0 ){
8719     assert( pX->pKey==0 );
8720     /* If this is an insert into a table b-tree, invalidate any incrblob
8721     ** cursors open on the row being replaced */
8722     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8723 
8724     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8725     ** to a row with the same key as the new entry being inserted.
8726     */
8727 #ifdef SQLITE_DEBUG
8728     if( flags & BTREE_SAVEPOSITION ){
8729       assert( pCur->curFlags & BTCF_ValidNKey );
8730       assert( pX->nKey==pCur->info.nKey );
8731       assert( loc==0 );
8732     }
8733 #endif
8734 
8735     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8736     ** that the cursor is not pointing to a row to be overwritten.
8737     ** So do a complete check.
8738     */
8739     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8740       /* The cursor is pointing to the entry that is to be
8741       ** overwritten */
8742       assert( pX->nData>=0 && pX->nZero>=0 );
8743       if( pCur->info.nSize!=0
8744        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8745       ){
8746         /* New entry is the same size as the old.  Do an overwrite */
8747         return btreeOverwriteCell(pCur, pX);
8748       }
8749       assert( loc==0 );
8750     }else if( loc==0 ){
8751       /* The cursor is *not* pointing to the cell to be overwritten, nor
8752       ** to an adjacent cell.  Move the cursor so that it is pointing either
8753       ** to the cell to be overwritten or an adjacent cell.
8754       */
8755       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8756       if( rc ) return rc;
8757     }
8758   }else{
8759     /* This is an index or a WITHOUT ROWID table */
8760 
8761     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8762     ** to a row with the same key as the new entry being inserted.
8763     */
8764     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8765 
8766     /* If the cursor is not already pointing either to the cell to be
8767     ** overwritten, or if a new cell is being inserted, if the cursor is
8768     ** not pointing to an immediately adjacent cell, then move the cursor
8769     ** so that it does.
8770     */
8771     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8772       if( pX->nMem ){
8773         UnpackedRecord r;
8774         r.pKeyInfo = pCur->pKeyInfo;
8775         r.aMem = pX->aMem;
8776         r.nField = pX->nMem;
8777         r.default_rc = 0;
8778         r.errCode = 0;
8779         r.r1 = 0;
8780         r.r2 = 0;
8781         r.eqSeen = 0;
8782         rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8783       }else{
8784         rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8785       }
8786       if( rc ) return rc;
8787     }
8788 
8789     /* If the cursor is currently pointing to an entry to be overwritten
8790     ** and the new content is the same as as the old, then use the
8791     ** overwrite optimization.
8792     */
8793     if( loc==0 ){
8794       getCellInfo(pCur);
8795       if( pCur->info.nKey==pX->nKey ){
8796         BtreePayload x2;
8797         x2.pData = pX->pKey;
8798         x2.nData = pX->nKey;
8799         x2.nZero = 0;
8800         return btreeOverwriteCell(pCur, &x2);
8801       }
8802     }
8803 
8804   }
8805   assert( pCur->eState==CURSOR_VALID
8806        || (pCur->eState==CURSOR_INVALID && loc)
8807        || CORRUPT_DB );
8808 
8809   pPage = pCur->pPage;
8810   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8811   assert( pPage->leaf || !pPage->intKey );
8812   if( pPage->nFree<0 ){
8813     if( pCur->eState>CURSOR_INVALID ){
8814       rc = SQLITE_CORRUPT_BKPT;
8815     }else{
8816       rc = btreeComputeFreeSpace(pPage);
8817     }
8818     if( rc ) return rc;
8819   }
8820 
8821   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8822           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8823           loc==0 ? "overwrite" : "new entry"));
8824   assert( pPage->isInit );
8825   newCell = pBt->pTmpSpace;
8826   assert( newCell!=0 );
8827   if( flags & BTREE_PREFORMAT ){
8828     rc = SQLITE_OK;
8829     szNew = pBt->nPreformatSize;
8830     if( szNew<4 ) szNew = 4;
8831     if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
8832       CellInfo info;
8833       pPage->xParseCell(pPage, newCell, &info);
8834       if( info.nPayload!=info.nLocal ){
8835         Pgno ovfl = get4byte(&newCell[szNew-4]);
8836         ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
8837       }
8838     }
8839   }else{
8840     rc = fillInCell(pPage, newCell, pX, &szNew);
8841   }
8842   if( rc ) goto end_insert;
8843   assert( szNew==pPage->xCellSize(pPage, newCell) );
8844   assert( szNew <= MX_CELL_SIZE(pBt) );
8845   idx = pCur->ix;
8846   if( loc==0 ){
8847     CellInfo info;
8848     assert( idx<pPage->nCell );
8849     rc = sqlite3PagerWrite(pPage->pDbPage);
8850     if( rc ){
8851       goto end_insert;
8852     }
8853     oldCell = findCell(pPage, idx);
8854     if( !pPage->leaf ){
8855       memcpy(newCell, oldCell, 4);
8856     }
8857     rc = clearCell(pPage, oldCell, &info);
8858     testcase( pCur->curFlags & BTCF_ValidOvfl );
8859     invalidateOverflowCache(pCur);
8860     if( info.nSize==szNew && info.nLocal==info.nPayload
8861      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8862     ){
8863       /* Overwrite the old cell with the new if they are the same size.
8864       ** We could also try to do this if the old cell is smaller, then add
8865       ** the leftover space to the free list.  But experiments show that
8866       ** doing that is no faster then skipping this optimization and just
8867       ** calling dropCell() and insertCell().
8868       **
8869       ** This optimization cannot be used on an autovacuum database if the
8870       ** new entry uses overflow pages, as the insertCell() call below is
8871       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
8872       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8873       if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
8874         return SQLITE_CORRUPT_BKPT;
8875       }
8876       if( oldCell+szNew > pPage->aDataEnd ){
8877         return SQLITE_CORRUPT_BKPT;
8878       }
8879       memcpy(oldCell, newCell, szNew);
8880       return SQLITE_OK;
8881     }
8882     dropCell(pPage, idx, info.nSize, &rc);
8883     if( rc ) goto end_insert;
8884   }else if( loc<0 && pPage->nCell>0 ){
8885     assert( pPage->leaf );
8886     idx = ++pCur->ix;
8887     pCur->curFlags &= ~BTCF_ValidNKey;
8888   }else{
8889     assert( pPage->leaf );
8890   }
8891   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8892   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8893   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8894 
8895   /* If no error has occurred and pPage has an overflow cell, call balance()
8896   ** to redistribute the cells within the tree. Since balance() may move
8897   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8898   ** variables.
8899   **
8900   ** Previous versions of SQLite called moveToRoot() to move the cursor
8901   ** back to the root page as balance() used to invalidate the contents
8902   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8903   ** set the cursor state to "invalid". This makes common insert operations
8904   ** slightly faster.
8905   **
8906   ** There is a subtle but important optimization here too. When inserting
8907   ** multiple records into an intkey b-tree using a single cursor (as can
8908   ** happen while processing an "INSERT INTO ... SELECT" statement), it
8909   ** is advantageous to leave the cursor pointing to the last entry in
8910   ** the b-tree if possible. If the cursor is left pointing to the last
8911   ** entry in the table, and the next row inserted has an integer key
8912   ** larger than the largest existing key, it is possible to insert the
8913   ** row without seeking the cursor. This can be a big performance boost.
8914   */
8915   pCur->info.nSize = 0;
8916   if( pPage->nOverflow ){
8917     assert( rc==SQLITE_OK );
8918     pCur->curFlags &= ~(BTCF_ValidNKey);
8919     rc = balance(pCur);
8920 
8921     /* Must make sure nOverflow is reset to zero even if the balance()
8922     ** fails. Internal data structure corruption will result otherwise.
8923     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8924     ** from trying to save the current position of the cursor.  */
8925     pCur->pPage->nOverflow = 0;
8926     pCur->eState = CURSOR_INVALID;
8927     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8928       btreeReleaseAllCursorPages(pCur);
8929       if( pCur->pKeyInfo ){
8930         assert( pCur->pKey==0 );
8931         pCur->pKey = sqlite3Malloc( pX->nKey );
8932         if( pCur->pKey==0 ){
8933           rc = SQLITE_NOMEM;
8934         }else{
8935           memcpy(pCur->pKey, pX->pKey, pX->nKey);
8936         }
8937       }
8938       pCur->eState = CURSOR_REQUIRESEEK;
8939       pCur->nKey = pX->nKey;
8940     }
8941   }
8942   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8943 
8944 end_insert:
8945   return rc;
8946 }
8947 
8948 /*
8949 ** This function is used as part of copying the current row from cursor
8950 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
8951 ** parameter iKey is used as the rowid value when the record is copied
8952 ** into pDest. Otherwise, the record is copied verbatim.
8953 **
8954 ** This function does not actually write the new value to cursor pDest.
8955 ** Instead, it creates and populates any required overflow pages and
8956 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
8957 ** for the destination database. The size of the cell, in bytes, is left
8958 ** in BtShared.nPreformatSize. The caller completes the insertion by
8959 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
8960 **
8961 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
8962 */
8963 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
8964   int rc = SQLITE_OK;
8965   BtShared *pBt = pDest->pBt;
8966   u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
8967   const u8 *aIn;                /* Pointer to next input buffer */
8968   int nIn;                      /* Size of input buffer aIn[] */
8969   int nRem;                     /* Bytes of data still to copy */
8970 
8971   getCellInfo(pSrc);
8972   aOut += putVarint32(aOut, pSrc->info.nPayload);
8973   if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
8974   nIn = pSrc->info.nLocal;
8975   aIn = pSrc->info.pPayload;
8976   nRem = pSrc->info.nPayload;
8977   if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
8978     memcpy(aOut, aIn, nIn);
8979     pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
8980   }else{
8981     Pager *pSrcPager = pSrc->pBt->pPager;
8982     u8 *pPgnoOut = 0;
8983     Pgno ovflIn = 0;
8984     DbPage *pPageIn = 0;
8985     MemPage *pPageOut = 0;
8986     int nOut;                     /* Size of output buffer aOut[] */
8987 
8988     nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
8989     pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
8990     if( nOut<pSrc->info.nPayload ){
8991       pPgnoOut = &aOut[nOut];
8992       pBt->nPreformatSize += 4;
8993     }
8994 
8995     if( nRem>nIn ){
8996       ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
8997     }
8998 
8999     do {
9000       nRem -= nOut;
9001       do{
9002         assert( nOut>0 );
9003         if( nIn>0 ){
9004           int nCopy = MIN(nOut, nIn);
9005           memcpy(aOut, aIn, nCopy);
9006           nOut -= nCopy;
9007           nIn -= nCopy;
9008           aOut += nCopy;
9009           aIn += nCopy;
9010         }
9011         if( nOut>0 ){
9012           sqlite3PagerUnref(pPageIn);
9013           pPageIn = 0;
9014           rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9015           if( rc==SQLITE_OK ){
9016             aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9017             ovflIn = get4byte(aIn);
9018             aIn += 4;
9019             nIn = pSrc->pBt->usableSize - 4;
9020           }
9021         }
9022       }while( rc==SQLITE_OK && nOut>0 );
9023 
9024       if( rc==SQLITE_OK && nRem>0 ){
9025         Pgno pgnoNew;
9026         MemPage *pNew = 0;
9027         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9028         put4byte(pPgnoOut, pgnoNew);
9029         if( ISAUTOVACUUM && pPageOut ){
9030           ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9031         }
9032         releasePage(pPageOut);
9033         pPageOut = pNew;
9034         if( pPageOut ){
9035           pPgnoOut = pPageOut->aData;
9036           put4byte(pPgnoOut, 0);
9037           aOut = &pPgnoOut[4];
9038           nOut = MIN(pBt->usableSize - 4, nRem);
9039         }
9040       }
9041     }while( nRem>0 && rc==SQLITE_OK );
9042 
9043     releasePage(pPageOut);
9044     sqlite3PagerUnref(pPageIn);
9045   }
9046 
9047   return rc;
9048 }
9049 
9050 /*
9051 ** Delete the entry that the cursor is pointing to.
9052 **
9053 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9054 ** the cursor is left pointing at an arbitrary location after the delete.
9055 ** But if that bit is set, then the cursor is left in a state such that
9056 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9057 ** as it would have been on if the call to BtreeDelete() had been omitted.
9058 **
9059 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9060 ** associated with a single table entry and its indexes.  Only one of those
9061 ** deletes is considered the "primary" delete.  The primary delete occurs
9062 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
9063 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9064 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9065 ** but which might be used by alternative storage engines.
9066 */
9067 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9068   Btree *p = pCur->pBtree;
9069   BtShared *pBt = p->pBt;
9070   int rc;                              /* Return code */
9071   MemPage *pPage;                      /* Page to delete cell from */
9072   unsigned char *pCell;                /* Pointer to cell to delete */
9073   int iCellIdx;                        /* Index of cell to delete */
9074   int iCellDepth;                      /* Depth of node containing pCell */
9075   CellInfo info;                       /* Size of the cell being deleted */
9076   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
9077   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
9078 
9079   assert( cursorOwnsBtShared(pCur) );
9080   assert( pBt->inTransaction==TRANS_WRITE );
9081   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9082   assert( pCur->curFlags & BTCF_WriteFlag );
9083   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9084   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9085   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9086   if( pCur->eState==CURSOR_REQUIRESEEK ){
9087     rc = btreeRestoreCursorPosition(pCur);
9088     if( rc ) return rc;
9089   }
9090   assert( pCur->eState==CURSOR_VALID );
9091 
9092   iCellDepth = pCur->iPage;
9093   iCellIdx = pCur->ix;
9094   pPage = pCur->pPage;
9095   pCell = findCell(pPage, iCellIdx);
9096   if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
9097 
9098   /* If the bPreserve flag is set to true, then the cursor position must
9099   ** be preserved following this delete operation. If the current delete
9100   ** will cause a b-tree rebalance, then this is done by saving the cursor
9101   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9102   ** returning.
9103   **
9104   ** Or, if the current delete will not cause a rebalance, then the cursor
9105   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9106   ** before or after the deleted entry. In this case set bSkipnext to true.  */
9107   if( bPreserve ){
9108     if( !pPage->leaf
9109      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9110      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
9111     ){
9112       /* A b-tree rebalance will be required after deleting this entry.
9113       ** Save the cursor key.  */
9114       rc = saveCursorKey(pCur);
9115       if( rc ) return rc;
9116     }else{
9117       bSkipnext = 1;
9118     }
9119   }
9120 
9121   /* If the page containing the entry to delete is not a leaf page, move
9122   ** the cursor to the largest entry in the tree that is smaller than
9123   ** the entry being deleted. This cell will replace the cell being deleted
9124   ** from the internal node. The 'previous' entry is used for this instead
9125   ** of the 'next' entry, as the previous entry is always a part of the
9126   ** sub-tree headed by the child page of the cell being deleted. This makes
9127   ** balancing the tree following the delete operation easier.  */
9128   if( !pPage->leaf ){
9129     rc = sqlite3BtreePrevious(pCur, 0);
9130     assert( rc!=SQLITE_DONE );
9131     if( rc ) return rc;
9132   }
9133 
9134   /* Save the positions of any other cursors open on this table before
9135   ** making any modifications.  */
9136   if( pCur->curFlags & BTCF_Multiple ){
9137     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9138     if( rc ) return rc;
9139   }
9140 
9141   /* If this is a delete operation to remove a row from a table b-tree,
9142   ** invalidate any incrblob cursors open on the row being deleted.  */
9143   if( pCur->pKeyInfo==0 ){
9144     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9145   }
9146 
9147   /* Make the page containing the entry to be deleted writable. Then free any
9148   ** overflow pages associated with the entry and finally remove the cell
9149   ** itself from within the page.  */
9150   rc = sqlite3PagerWrite(pPage->pDbPage);
9151   if( rc ) return rc;
9152   rc = clearCell(pPage, pCell, &info);
9153   dropCell(pPage, iCellIdx, info.nSize, &rc);
9154   if( rc ) return rc;
9155 
9156   /* If the cell deleted was not located on a leaf page, then the cursor
9157   ** is currently pointing to the largest entry in the sub-tree headed
9158   ** by the child-page of the cell that was just deleted from an internal
9159   ** node. The cell from the leaf node needs to be moved to the internal
9160   ** node to replace the deleted cell.  */
9161   if( !pPage->leaf ){
9162     MemPage *pLeaf = pCur->pPage;
9163     int nCell;
9164     Pgno n;
9165     unsigned char *pTmp;
9166 
9167     if( pLeaf->nFree<0 ){
9168       rc = btreeComputeFreeSpace(pLeaf);
9169       if( rc ) return rc;
9170     }
9171     if( iCellDepth<pCur->iPage-1 ){
9172       n = pCur->apPage[iCellDepth+1]->pgno;
9173     }else{
9174       n = pCur->pPage->pgno;
9175     }
9176     pCell = findCell(pLeaf, pLeaf->nCell-1);
9177     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9178     nCell = pLeaf->xCellSize(pLeaf, pCell);
9179     assert( MX_CELL_SIZE(pBt) >= nCell );
9180     pTmp = pBt->pTmpSpace;
9181     assert( pTmp!=0 );
9182     rc = sqlite3PagerWrite(pLeaf->pDbPage);
9183     if( rc==SQLITE_OK ){
9184       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9185     }
9186     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9187     if( rc ) return rc;
9188   }
9189 
9190   /* Balance the tree. If the entry deleted was located on a leaf page,
9191   ** then the cursor still points to that page. In this case the first
9192   ** call to balance() repairs the tree, and the if(...) condition is
9193   ** never true.
9194   **
9195   ** Otherwise, if the entry deleted was on an internal node page, then
9196   ** pCur is pointing to the leaf page from which a cell was removed to
9197   ** replace the cell deleted from the internal node. This is slightly
9198   ** tricky as the leaf node may be underfull, and the internal node may
9199   ** be either under or overfull. In this case run the balancing algorithm
9200   ** on the leaf node first. If the balance proceeds far enough up the
9201   ** tree that we can be sure that any problem in the internal node has
9202   ** been corrected, so be it. Otherwise, after balancing the leaf node,
9203   ** walk the cursor up the tree to the internal node and balance it as
9204   ** well.  */
9205   rc = balance(pCur);
9206   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9207     releasePageNotNull(pCur->pPage);
9208     pCur->iPage--;
9209     while( pCur->iPage>iCellDepth ){
9210       releasePage(pCur->apPage[pCur->iPage--]);
9211     }
9212     pCur->pPage = pCur->apPage[pCur->iPage];
9213     rc = balance(pCur);
9214   }
9215 
9216   if( rc==SQLITE_OK ){
9217     if( bSkipnext ){
9218       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9219       assert( pPage==pCur->pPage || CORRUPT_DB );
9220       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9221       pCur->eState = CURSOR_SKIPNEXT;
9222       if( iCellIdx>=pPage->nCell ){
9223         pCur->skipNext = -1;
9224         pCur->ix = pPage->nCell-1;
9225       }else{
9226         pCur->skipNext = 1;
9227       }
9228     }else{
9229       rc = moveToRoot(pCur);
9230       if( bPreserve ){
9231         btreeReleaseAllCursorPages(pCur);
9232         pCur->eState = CURSOR_REQUIRESEEK;
9233       }
9234       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9235     }
9236   }
9237   return rc;
9238 }
9239 
9240 /*
9241 ** Create a new BTree table.  Write into *piTable the page
9242 ** number for the root page of the new table.
9243 **
9244 ** The type of type is determined by the flags parameter.  Only the
9245 ** following values of flags are currently in use.  Other values for
9246 ** flags might not work:
9247 **
9248 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
9249 **     BTREE_ZERODATA                  Used for SQL indices
9250 */
9251 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9252   BtShared *pBt = p->pBt;
9253   MemPage *pRoot;
9254   Pgno pgnoRoot;
9255   int rc;
9256   int ptfFlags;          /* Page-type flage for the root page of new table */
9257 
9258   assert( sqlite3BtreeHoldsMutex(p) );
9259   assert( pBt->inTransaction==TRANS_WRITE );
9260   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9261 
9262 #ifdef SQLITE_OMIT_AUTOVACUUM
9263   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9264   if( rc ){
9265     return rc;
9266   }
9267 #else
9268   if( pBt->autoVacuum ){
9269     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
9270     MemPage *pPageMove; /* The page to move to. */
9271 
9272     /* Creating a new table may probably require moving an existing database
9273     ** to make room for the new tables root page. In case this page turns
9274     ** out to be an overflow page, delete all overflow page-map caches
9275     ** held by open cursors.
9276     */
9277     invalidateAllOverflowCache(pBt);
9278 
9279     /* Read the value of meta[3] from the database to determine where the
9280     ** root page of the new table should go. meta[3] is the largest root-page
9281     ** created so far, so the new root-page is (meta[3]+1).
9282     */
9283     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9284     if( pgnoRoot>btreePagecount(pBt) ){
9285       return SQLITE_CORRUPT_BKPT;
9286     }
9287     pgnoRoot++;
9288 
9289     /* The new root-page may not be allocated on a pointer-map page, or the
9290     ** PENDING_BYTE page.
9291     */
9292     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9293         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9294       pgnoRoot++;
9295     }
9296     assert( pgnoRoot>=3 );
9297 
9298     /* Allocate a page. The page that currently resides at pgnoRoot will
9299     ** be moved to the allocated page (unless the allocated page happens
9300     ** to reside at pgnoRoot).
9301     */
9302     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9303     if( rc!=SQLITE_OK ){
9304       return rc;
9305     }
9306 
9307     if( pgnoMove!=pgnoRoot ){
9308       /* pgnoRoot is the page that will be used for the root-page of
9309       ** the new table (assuming an error did not occur). But we were
9310       ** allocated pgnoMove. If required (i.e. if it was not allocated
9311       ** by extending the file), the current page at position pgnoMove
9312       ** is already journaled.
9313       */
9314       u8 eType = 0;
9315       Pgno iPtrPage = 0;
9316 
9317       /* Save the positions of any open cursors. This is required in
9318       ** case they are holding a reference to an xFetch reference
9319       ** corresponding to page pgnoRoot.  */
9320       rc = saveAllCursors(pBt, 0, 0);
9321       releasePage(pPageMove);
9322       if( rc!=SQLITE_OK ){
9323         return rc;
9324       }
9325 
9326       /* Move the page currently at pgnoRoot to pgnoMove. */
9327       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9328       if( rc!=SQLITE_OK ){
9329         return rc;
9330       }
9331       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9332       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9333         rc = SQLITE_CORRUPT_BKPT;
9334       }
9335       if( rc!=SQLITE_OK ){
9336         releasePage(pRoot);
9337         return rc;
9338       }
9339       assert( eType!=PTRMAP_ROOTPAGE );
9340       assert( eType!=PTRMAP_FREEPAGE );
9341       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9342       releasePage(pRoot);
9343 
9344       /* Obtain the page at pgnoRoot */
9345       if( rc!=SQLITE_OK ){
9346         return rc;
9347       }
9348       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9349       if( rc!=SQLITE_OK ){
9350         return rc;
9351       }
9352       rc = sqlite3PagerWrite(pRoot->pDbPage);
9353       if( rc!=SQLITE_OK ){
9354         releasePage(pRoot);
9355         return rc;
9356       }
9357     }else{
9358       pRoot = pPageMove;
9359     }
9360 
9361     /* Update the pointer-map and meta-data with the new root-page number. */
9362     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9363     if( rc ){
9364       releasePage(pRoot);
9365       return rc;
9366     }
9367 
9368     /* When the new root page was allocated, page 1 was made writable in
9369     ** order either to increase the database filesize, or to decrement the
9370     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9371     */
9372     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9373     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9374     if( NEVER(rc) ){
9375       releasePage(pRoot);
9376       return rc;
9377     }
9378 
9379   }else{
9380     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9381     if( rc ) return rc;
9382   }
9383 #endif
9384   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9385   if( createTabFlags & BTREE_INTKEY ){
9386     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9387   }else{
9388     ptfFlags = PTF_ZERODATA | PTF_LEAF;
9389   }
9390   zeroPage(pRoot, ptfFlags);
9391   sqlite3PagerUnref(pRoot->pDbPage);
9392   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9393   *piTable = pgnoRoot;
9394   return SQLITE_OK;
9395 }
9396 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9397   int rc;
9398   sqlite3BtreeEnter(p);
9399   rc = btreeCreateTable(p, piTable, flags);
9400   sqlite3BtreeLeave(p);
9401   return rc;
9402 }
9403 
9404 /*
9405 ** Erase the given database page and all its children.  Return
9406 ** the page to the freelist.
9407 */
9408 static int clearDatabasePage(
9409   BtShared *pBt,           /* The BTree that contains the table */
9410   Pgno pgno,               /* Page number to clear */
9411   int freePageFlag,        /* Deallocate page if true */
9412   int *pnChange            /* Add number of Cells freed to this counter */
9413 ){
9414   MemPage *pPage;
9415   int rc;
9416   unsigned char *pCell;
9417   int i;
9418   int hdr;
9419   CellInfo info;
9420 
9421   assert( sqlite3_mutex_held(pBt->mutex) );
9422   if( pgno>btreePagecount(pBt) ){
9423     return SQLITE_CORRUPT_BKPT;
9424   }
9425   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9426   if( rc ) return rc;
9427   if( pPage->bBusy ){
9428     rc = SQLITE_CORRUPT_BKPT;
9429     goto cleardatabasepage_out;
9430   }
9431   pPage->bBusy = 1;
9432   hdr = pPage->hdrOffset;
9433   for(i=0; i<pPage->nCell; i++){
9434     pCell = findCell(pPage, i);
9435     if( !pPage->leaf ){
9436       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9437       if( rc ) goto cleardatabasepage_out;
9438     }
9439     rc = clearCell(pPage, pCell, &info);
9440     if( rc ) goto cleardatabasepage_out;
9441   }
9442   if( !pPage->leaf ){
9443     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9444     if( rc ) goto cleardatabasepage_out;
9445   }else if( pnChange ){
9446     assert( pPage->intKey || CORRUPT_DB );
9447     testcase( !pPage->intKey );
9448     *pnChange += pPage->nCell;
9449   }
9450   if( freePageFlag ){
9451     freePage(pPage, &rc);
9452   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9453     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9454   }
9455 
9456 cleardatabasepage_out:
9457   pPage->bBusy = 0;
9458   releasePage(pPage);
9459   return rc;
9460 }
9461 
9462 /*
9463 ** Delete all information from a single table in the database.  iTable is
9464 ** the page number of the root of the table.  After this routine returns,
9465 ** the root page is empty, but still exists.
9466 **
9467 ** This routine will fail with SQLITE_LOCKED if there are any open
9468 ** read cursors on the table.  Open write cursors are moved to the
9469 ** root of the table.
9470 **
9471 ** If pnChange is not NULL, then table iTable must be an intkey table. The
9472 ** integer value pointed to by pnChange is incremented by the number of
9473 ** entries in the table.
9474 */
9475 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
9476   int rc;
9477   BtShared *pBt = p->pBt;
9478   sqlite3BtreeEnter(p);
9479   assert( p->inTrans==TRANS_WRITE );
9480 
9481   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9482 
9483   if( SQLITE_OK==rc ){
9484     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9485     ** is the root of a table b-tree - if it is not, the following call is
9486     ** a no-op).  */
9487     invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9488     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9489   }
9490   sqlite3BtreeLeave(p);
9491   return rc;
9492 }
9493 
9494 /*
9495 ** Delete all information from the single table that pCur is open on.
9496 **
9497 ** This routine only work for pCur on an ephemeral table.
9498 */
9499 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9500   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9501 }
9502 
9503 /*
9504 ** Erase all information in a table and add the root of the table to
9505 ** the freelist.  Except, the root of the principle table (the one on
9506 ** page 1) is never added to the freelist.
9507 **
9508 ** This routine will fail with SQLITE_LOCKED if there are any open
9509 ** cursors on the table.
9510 **
9511 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9512 ** root page in the database file, then the last root page
9513 ** in the database file is moved into the slot formerly occupied by
9514 ** iTable and that last slot formerly occupied by the last root page
9515 ** is added to the freelist instead of iTable.  In this say, all
9516 ** root pages are kept at the beginning of the database file, which
9517 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9518 ** page number that used to be the last root page in the file before
9519 ** the move.  If no page gets moved, *piMoved is set to 0.
9520 ** The last root page is recorded in meta[3] and the value of
9521 ** meta[3] is updated by this procedure.
9522 */
9523 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9524   int rc;
9525   MemPage *pPage = 0;
9526   BtShared *pBt = p->pBt;
9527 
9528   assert( sqlite3BtreeHoldsMutex(p) );
9529   assert( p->inTrans==TRANS_WRITE );
9530   assert( iTable>=2 );
9531   if( iTable>btreePagecount(pBt) ){
9532     return SQLITE_CORRUPT_BKPT;
9533   }
9534 
9535   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9536   if( rc ) return rc;
9537   rc = sqlite3BtreeClearTable(p, iTable, 0);
9538   if( rc ){
9539     releasePage(pPage);
9540     return rc;
9541   }
9542 
9543   *piMoved = 0;
9544 
9545 #ifdef SQLITE_OMIT_AUTOVACUUM
9546   freePage(pPage, &rc);
9547   releasePage(pPage);
9548 #else
9549   if( pBt->autoVacuum ){
9550     Pgno maxRootPgno;
9551     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9552 
9553     if( iTable==maxRootPgno ){
9554       /* If the table being dropped is the table with the largest root-page
9555       ** number in the database, put the root page on the free list.
9556       */
9557       freePage(pPage, &rc);
9558       releasePage(pPage);
9559       if( rc!=SQLITE_OK ){
9560         return rc;
9561       }
9562     }else{
9563       /* The table being dropped does not have the largest root-page
9564       ** number in the database. So move the page that does into the
9565       ** gap left by the deleted root-page.
9566       */
9567       MemPage *pMove;
9568       releasePage(pPage);
9569       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9570       if( rc!=SQLITE_OK ){
9571         return rc;
9572       }
9573       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9574       releasePage(pMove);
9575       if( rc!=SQLITE_OK ){
9576         return rc;
9577       }
9578       pMove = 0;
9579       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9580       freePage(pMove, &rc);
9581       releasePage(pMove);
9582       if( rc!=SQLITE_OK ){
9583         return rc;
9584       }
9585       *piMoved = maxRootPgno;
9586     }
9587 
9588     /* Set the new 'max-root-page' value in the database header. This
9589     ** is the old value less one, less one more if that happens to
9590     ** be a root-page number, less one again if that is the
9591     ** PENDING_BYTE_PAGE.
9592     */
9593     maxRootPgno--;
9594     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9595            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9596       maxRootPgno--;
9597     }
9598     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9599 
9600     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9601   }else{
9602     freePage(pPage, &rc);
9603     releasePage(pPage);
9604   }
9605 #endif
9606   return rc;
9607 }
9608 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9609   int rc;
9610   sqlite3BtreeEnter(p);
9611   rc = btreeDropTable(p, iTable, piMoved);
9612   sqlite3BtreeLeave(p);
9613   return rc;
9614 }
9615 
9616 
9617 /*
9618 ** This function may only be called if the b-tree connection already
9619 ** has a read or write transaction open on the database.
9620 **
9621 ** Read the meta-information out of a database file.  Meta[0]
9622 ** is the number of free pages currently in the database.  Meta[1]
9623 ** through meta[15] are available for use by higher layers.  Meta[0]
9624 ** is read-only, the others are read/write.
9625 **
9626 ** The schema layer numbers meta values differently.  At the schema
9627 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9628 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
9629 **
9630 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
9631 ** of reading the value out of the header, it instead loads the "DataVersion"
9632 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
9633 ** database file.  It is a number computed by the pager.  But its access
9634 ** pattern is the same as header meta values, and so it is convenient to
9635 ** read it from this routine.
9636 */
9637 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9638   BtShared *pBt = p->pBt;
9639 
9640   sqlite3BtreeEnter(p);
9641   assert( p->inTrans>TRANS_NONE );
9642   assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9643   assert( pBt->pPage1 );
9644   assert( idx>=0 && idx<=15 );
9645 
9646   if( idx==BTREE_DATA_VERSION ){
9647     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
9648   }else{
9649     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9650   }
9651 
9652   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9653   ** database, mark the database as read-only.  */
9654 #ifdef SQLITE_OMIT_AUTOVACUUM
9655   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9656     pBt->btsFlags |= BTS_READ_ONLY;
9657   }
9658 #endif
9659 
9660   sqlite3BtreeLeave(p);
9661 }
9662 
9663 /*
9664 ** Write meta-information back into the database.  Meta[0] is
9665 ** read-only and may not be written.
9666 */
9667 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9668   BtShared *pBt = p->pBt;
9669   unsigned char *pP1;
9670   int rc;
9671   assert( idx>=1 && idx<=15 );
9672   sqlite3BtreeEnter(p);
9673   assert( p->inTrans==TRANS_WRITE );
9674   assert( pBt->pPage1!=0 );
9675   pP1 = pBt->pPage1->aData;
9676   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9677   if( rc==SQLITE_OK ){
9678     put4byte(&pP1[36 + idx*4], iMeta);
9679 #ifndef SQLITE_OMIT_AUTOVACUUM
9680     if( idx==BTREE_INCR_VACUUM ){
9681       assert( pBt->autoVacuum || iMeta==0 );
9682       assert( iMeta==0 || iMeta==1 );
9683       pBt->incrVacuum = (u8)iMeta;
9684     }
9685 #endif
9686   }
9687   sqlite3BtreeLeave(p);
9688   return rc;
9689 }
9690 
9691 /*
9692 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9693 ** number of entries in the b-tree and write the result to *pnEntry.
9694 **
9695 ** SQLITE_OK is returned if the operation is successfully executed.
9696 ** Otherwise, if an error is encountered (i.e. an IO error or database
9697 ** corruption) an SQLite error code is returned.
9698 */
9699 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9700   i64 nEntry = 0;                      /* Value to return in *pnEntry */
9701   int rc;                              /* Return code */
9702 
9703   rc = moveToRoot(pCur);
9704   if( rc==SQLITE_EMPTY ){
9705     *pnEntry = 0;
9706     return SQLITE_OK;
9707   }
9708 
9709   /* Unless an error occurs, the following loop runs one iteration for each
9710   ** page in the B-Tree structure (not including overflow pages).
9711   */
9712   while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9713     int iIdx;                          /* Index of child node in parent */
9714     MemPage *pPage;                    /* Current page of the b-tree */
9715 
9716     /* If this is a leaf page or the tree is not an int-key tree, then
9717     ** this page contains countable entries. Increment the entry counter
9718     ** accordingly.
9719     */
9720     pPage = pCur->pPage;
9721     if( pPage->leaf || !pPage->intKey ){
9722       nEntry += pPage->nCell;
9723     }
9724 
9725     /* pPage is a leaf node. This loop navigates the cursor so that it
9726     ** points to the first interior cell that it points to the parent of
9727     ** the next page in the tree that has not yet been visited. The
9728     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9729     ** of the page, or to the number of cells in the page if the next page
9730     ** to visit is the right-child of its parent.
9731     **
9732     ** If all pages in the tree have been visited, return SQLITE_OK to the
9733     ** caller.
9734     */
9735     if( pPage->leaf ){
9736       do {
9737         if( pCur->iPage==0 ){
9738           /* All pages of the b-tree have been visited. Return successfully. */
9739           *pnEntry = nEntry;
9740           return moveToRoot(pCur);
9741         }
9742         moveToParent(pCur);
9743       }while ( pCur->ix>=pCur->pPage->nCell );
9744 
9745       pCur->ix++;
9746       pPage = pCur->pPage;
9747     }
9748 
9749     /* Descend to the child node of the cell that the cursor currently
9750     ** points at. This is the right-child if (iIdx==pPage->nCell).
9751     */
9752     iIdx = pCur->ix;
9753     if( iIdx==pPage->nCell ){
9754       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9755     }else{
9756       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9757     }
9758   }
9759 
9760   /* An error has occurred. Return an error code. */
9761   return rc;
9762 }
9763 
9764 /*
9765 ** Return the pager associated with a BTree.  This routine is used for
9766 ** testing and debugging only.
9767 */
9768 Pager *sqlite3BtreePager(Btree *p){
9769   return p->pBt->pPager;
9770 }
9771 
9772 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9773 /*
9774 ** Append a message to the error message string.
9775 */
9776 static void checkAppendMsg(
9777   IntegrityCk *pCheck,
9778   const char *zFormat,
9779   ...
9780 ){
9781   va_list ap;
9782   if( !pCheck->mxErr ) return;
9783   pCheck->mxErr--;
9784   pCheck->nErr++;
9785   va_start(ap, zFormat);
9786   if( pCheck->errMsg.nChar ){
9787     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9788   }
9789   if( pCheck->zPfx ){
9790     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9791   }
9792   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9793   va_end(ap);
9794   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9795     pCheck->bOomFault = 1;
9796   }
9797 }
9798 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9799 
9800 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9801 
9802 /*
9803 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9804 ** corresponds to page iPg is already set.
9805 */
9806 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9807   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9808   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9809 }
9810 
9811 /*
9812 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9813 */
9814 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9815   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9816   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9817 }
9818 
9819 
9820 /*
9821 ** Add 1 to the reference count for page iPage.  If this is the second
9822 ** reference to the page, add an error message to pCheck->zErrMsg.
9823 ** Return 1 if there are 2 or more references to the page and 0 if
9824 ** if this is the first reference to the page.
9825 **
9826 ** Also check that the page number is in bounds.
9827 */
9828 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9829   if( iPage>pCheck->nPage || iPage==0 ){
9830     checkAppendMsg(pCheck, "invalid page number %d", iPage);
9831     return 1;
9832   }
9833   if( getPageReferenced(pCheck, iPage) ){
9834     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9835     return 1;
9836   }
9837   if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9838   setPageReferenced(pCheck, iPage);
9839   return 0;
9840 }
9841 
9842 #ifndef SQLITE_OMIT_AUTOVACUUM
9843 /*
9844 ** Check that the entry in the pointer-map for page iChild maps to
9845 ** page iParent, pointer type ptrType. If not, append an error message
9846 ** to pCheck.
9847 */
9848 static void checkPtrmap(
9849   IntegrityCk *pCheck,   /* Integrity check context */
9850   Pgno iChild,           /* Child page number */
9851   u8 eType,              /* Expected pointer map type */
9852   Pgno iParent           /* Expected pointer map parent page number */
9853 ){
9854   int rc;
9855   u8 ePtrmapType;
9856   Pgno iPtrmapParent;
9857 
9858   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9859   if( rc!=SQLITE_OK ){
9860     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
9861     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9862     return;
9863   }
9864 
9865   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9866     checkAppendMsg(pCheck,
9867       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9868       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9869   }
9870 }
9871 #endif
9872 
9873 /*
9874 ** Check the integrity of the freelist or of an overflow page list.
9875 ** Verify that the number of pages on the list is N.
9876 */
9877 static void checkList(
9878   IntegrityCk *pCheck,  /* Integrity checking context */
9879   int isFreeList,       /* True for a freelist.  False for overflow page list */
9880   Pgno iPage,           /* Page number for first page in the list */
9881   u32 N                 /* Expected number of pages in the list */
9882 ){
9883   int i;
9884   u32 expected = N;
9885   int nErrAtStart = pCheck->nErr;
9886   while( iPage!=0 && pCheck->mxErr ){
9887     DbPage *pOvflPage;
9888     unsigned char *pOvflData;
9889     if( checkRef(pCheck, iPage) ) break;
9890     N--;
9891     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9892       checkAppendMsg(pCheck, "failed to get page %d", iPage);
9893       break;
9894     }
9895     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9896     if( isFreeList ){
9897       u32 n = (u32)get4byte(&pOvflData[4]);
9898 #ifndef SQLITE_OMIT_AUTOVACUUM
9899       if( pCheck->pBt->autoVacuum ){
9900         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9901       }
9902 #endif
9903       if( n>pCheck->pBt->usableSize/4-2 ){
9904         checkAppendMsg(pCheck,
9905            "freelist leaf count too big on page %d", iPage);
9906         N--;
9907       }else{
9908         for(i=0; i<(int)n; i++){
9909           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9910 #ifndef SQLITE_OMIT_AUTOVACUUM
9911           if( pCheck->pBt->autoVacuum ){
9912             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9913           }
9914 #endif
9915           checkRef(pCheck, iFreePage);
9916         }
9917         N -= n;
9918       }
9919     }
9920 #ifndef SQLITE_OMIT_AUTOVACUUM
9921     else{
9922       /* If this database supports auto-vacuum and iPage is not the last
9923       ** page in this overflow list, check that the pointer-map entry for
9924       ** the following page matches iPage.
9925       */
9926       if( pCheck->pBt->autoVacuum && N>0 ){
9927         i = get4byte(pOvflData);
9928         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9929       }
9930     }
9931 #endif
9932     iPage = get4byte(pOvflData);
9933     sqlite3PagerUnref(pOvflPage);
9934   }
9935   if( N && nErrAtStart==pCheck->nErr ){
9936     checkAppendMsg(pCheck,
9937       "%s is %d but should be %d",
9938       isFreeList ? "size" : "overflow list length",
9939       expected-N, expected);
9940   }
9941 }
9942 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9943 
9944 /*
9945 ** An implementation of a min-heap.
9946 **
9947 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
9948 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
9949 ** and aHeap[N*2+1].
9950 **
9951 ** The heap property is this:  Every node is less than or equal to both
9952 ** of its daughter nodes.  A consequence of the heap property is that the
9953 ** root node aHeap[1] is always the minimum value currently in the heap.
9954 **
9955 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9956 ** the heap, preserving the heap property.  The btreeHeapPull() routine
9957 ** removes the root element from the heap (the minimum value in the heap)
9958 ** and then moves other nodes around as necessary to preserve the heap
9959 ** property.
9960 **
9961 ** This heap is used for cell overlap and coverage testing.  Each u32
9962 ** entry represents the span of a cell or freeblock on a btree page.
9963 ** The upper 16 bits are the index of the first byte of a range and the
9964 ** lower 16 bits are the index of the last byte of that range.
9965 */
9966 static void btreeHeapInsert(u32 *aHeap, u32 x){
9967   u32 j, i = ++aHeap[0];
9968   aHeap[i] = x;
9969   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9970     x = aHeap[j];
9971     aHeap[j] = aHeap[i];
9972     aHeap[i] = x;
9973     i = j;
9974   }
9975 }
9976 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9977   u32 j, i, x;
9978   if( (x = aHeap[0])==0 ) return 0;
9979   *pOut = aHeap[1];
9980   aHeap[1] = aHeap[x];
9981   aHeap[x] = 0xffffffff;
9982   aHeap[0]--;
9983   i = 1;
9984   while( (j = i*2)<=aHeap[0] ){
9985     if( aHeap[j]>aHeap[j+1] ) j++;
9986     if( aHeap[i]<aHeap[j] ) break;
9987     x = aHeap[i];
9988     aHeap[i] = aHeap[j];
9989     aHeap[j] = x;
9990     i = j;
9991   }
9992   return 1;
9993 }
9994 
9995 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9996 /*
9997 ** Do various sanity checks on a single page of a tree.  Return
9998 ** the tree depth.  Root pages return 0.  Parents of root pages
9999 ** return 1, and so forth.
10000 **
10001 ** These checks are done:
10002 **
10003 **      1.  Make sure that cells and freeblocks do not overlap
10004 **          but combine to completely cover the page.
10005 **      2.  Make sure integer cell keys are in order.
10006 **      3.  Check the integrity of overflow pages.
10007 **      4.  Recursively call checkTreePage on all children.
10008 **      5.  Verify that the depth of all children is the same.
10009 */
10010 static int checkTreePage(
10011   IntegrityCk *pCheck,  /* Context for the sanity check */
10012   Pgno iPage,           /* Page number of the page to check */
10013   i64 *piMinKey,        /* Write minimum integer primary key here */
10014   i64 maxKey            /* Error if integer primary key greater than this */
10015 ){
10016   MemPage *pPage = 0;      /* The page being analyzed */
10017   int i;                   /* Loop counter */
10018   int rc;                  /* Result code from subroutine call */
10019   int depth = -1, d2;      /* Depth of a subtree */
10020   int pgno;                /* Page number */
10021   int nFrag;               /* Number of fragmented bytes on the page */
10022   int hdr;                 /* Offset to the page header */
10023   int cellStart;           /* Offset to the start of the cell pointer array */
10024   int nCell;               /* Number of cells */
10025   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10026   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
10027                            ** False if IPK must be strictly less than maxKey */
10028   u8 *data;                /* Page content */
10029   u8 *pCell;               /* Cell content */
10030   u8 *pCellIdx;            /* Next element of the cell pointer array */
10031   BtShared *pBt;           /* The BtShared object that owns pPage */
10032   u32 pc;                  /* Address of a cell */
10033   u32 usableSize;          /* Usable size of the page */
10034   u32 contentOffset;       /* Offset to the start of the cell content area */
10035   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
10036   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
10037   const char *saved_zPfx = pCheck->zPfx;
10038   int saved_v1 = pCheck->v1;
10039   int saved_v2 = pCheck->v2;
10040   u8 savedIsInit = 0;
10041 
10042   /* Check that the page exists
10043   */
10044   pBt = pCheck->pBt;
10045   usableSize = pBt->usableSize;
10046   if( iPage==0 ) return 0;
10047   if( checkRef(pCheck, iPage) ) return 0;
10048   pCheck->zPfx = "Page %u: ";
10049   pCheck->v1 = iPage;
10050   if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10051     checkAppendMsg(pCheck,
10052        "unable to get the page. error code=%d", rc);
10053     goto end_of_check;
10054   }
10055 
10056   /* Clear MemPage.isInit to make sure the corruption detection code in
10057   ** btreeInitPage() is executed.  */
10058   savedIsInit = pPage->isInit;
10059   pPage->isInit = 0;
10060   if( (rc = btreeInitPage(pPage))!=0 ){
10061     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
10062     checkAppendMsg(pCheck,
10063                    "btreeInitPage() returns error code %d", rc);
10064     goto end_of_check;
10065   }
10066   if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10067     assert( rc==SQLITE_CORRUPT );
10068     checkAppendMsg(pCheck, "free space corruption", rc);
10069     goto end_of_check;
10070   }
10071   data = pPage->aData;
10072   hdr = pPage->hdrOffset;
10073 
10074   /* Set up for cell analysis */
10075   pCheck->zPfx = "On tree page %u cell %d: ";
10076   contentOffset = get2byteNotZero(&data[hdr+5]);
10077   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
10078 
10079   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10080   ** number of cells on the page. */
10081   nCell = get2byte(&data[hdr+3]);
10082   assert( pPage->nCell==nCell );
10083 
10084   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10085   ** immediately follows the b-tree page header. */
10086   cellStart = hdr + 12 - 4*pPage->leaf;
10087   assert( pPage->aCellIdx==&data[cellStart] );
10088   pCellIdx = &data[cellStart + 2*(nCell-1)];
10089 
10090   if( !pPage->leaf ){
10091     /* Analyze the right-child page of internal pages */
10092     pgno = get4byte(&data[hdr+8]);
10093 #ifndef SQLITE_OMIT_AUTOVACUUM
10094     if( pBt->autoVacuum ){
10095       pCheck->zPfx = "On page %u at right child: ";
10096       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10097     }
10098 #endif
10099     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10100     keyCanBeEqual = 0;
10101   }else{
10102     /* For leaf pages, the coverage check will occur in the same loop
10103     ** as the other cell checks, so initialize the heap.  */
10104     heap = pCheck->heap;
10105     heap[0] = 0;
10106   }
10107 
10108   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10109   ** integer offsets to the cell contents. */
10110   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10111     CellInfo info;
10112 
10113     /* Check cell size */
10114     pCheck->v2 = i;
10115     assert( pCellIdx==&data[cellStart + i*2] );
10116     pc = get2byteAligned(pCellIdx);
10117     pCellIdx -= 2;
10118     if( pc<contentOffset || pc>usableSize-4 ){
10119       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10120                              pc, contentOffset, usableSize-4);
10121       doCoverageCheck = 0;
10122       continue;
10123     }
10124     pCell = &data[pc];
10125     pPage->xParseCell(pPage, pCell, &info);
10126     if( pc+info.nSize>usableSize ){
10127       checkAppendMsg(pCheck, "Extends off end of page");
10128       doCoverageCheck = 0;
10129       continue;
10130     }
10131 
10132     /* Check for integer primary key out of range */
10133     if( pPage->intKey ){
10134       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10135         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10136       }
10137       maxKey = info.nKey;
10138       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
10139     }
10140 
10141     /* Check the content overflow list */
10142     if( info.nPayload>info.nLocal ){
10143       u32 nPage;       /* Number of pages on the overflow chain */
10144       Pgno pgnoOvfl;   /* First page of the overflow chain */
10145       assert( pc + info.nSize - 4 <= usableSize );
10146       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10147       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10148 #ifndef SQLITE_OMIT_AUTOVACUUM
10149       if( pBt->autoVacuum ){
10150         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10151       }
10152 #endif
10153       checkList(pCheck, 0, pgnoOvfl, nPage);
10154     }
10155 
10156     if( !pPage->leaf ){
10157       /* Check sanity of left child page for internal pages */
10158       pgno = get4byte(pCell);
10159 #ifndef SQLITE_OMIT_AUTOVACUUM
10160       if( pBt->autoVacuum ){
10161         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10162       }
10163 #endif
10164       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10165       keyCanBeEqual = 0;
10166       if( d2!=depth ){
10167         checkAppendMsg(pCheck, "Child page depth differs");
10168         depth = d2;
10169       }
10170     }else{
10171       /* Populate the coverage-checking heap for leaf pages */
10172       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10173     }
10174   }
10175   *piMinKey = maxKey;
10176 
10177   /* Check for complete coverage of the page
10178   */
10179   pCheck->zPfx = 0;
10180   if( doCoverageCheck && pCheck->mxErr>0 ){
10181     /* For leaf pages, the min-heap has already been initialized and the
10182     ** cells have already been inserted.  But for internal pages, that has
10183     ** not yet been done, so do it now */
10184     if( !pPage->leaf ){
10185       heap = pCheck->heap;
10186       heap[0] = 0;
10187       for(i=nCell-1; i>=0; i--){
10188         u32 size;
10189         pc = get2byteAligned(&data[cellStart+i*2]);
10190         size = pPage->xCellSize(pPage, &data[pc]);
10191         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10192       }
10193     }
10194     /* Add the freeblocks to the min-heap
10195     **
10196     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10197     ** is the offset of the first freeblock, or zero if there are no
10198     ** freeblocks on the page.
10199     */
10200     i = get2byte(&data[hdr+1]);
10201     while( i>0 ){
10202       int size, j;
10203       assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10204       size = get2byte(&data[i+2]);
10205       assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10206       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10207       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10208       ** big-endian integer which is the offset in the b-tree page of the next
10209       ** freeblock in the chain, or zero if the freeblock is the last on the
10210       ** chain. */
10211       j = get2byte(&data[i]);
10212       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10213       ** increasing offset. */
10214       assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
10215       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10216       i = j;
10217     }
10218     /* Analyze the min-heap looking for overlap between cells and/or
10219     ** freeblocks, and counting the number of untracked bytes in nFrag.
10220     **
10221     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
10222     ** There is an implied first entry the covers the page header, the cell
10223     ** pointer index, and the gap between the cell pointer index and the start
10224     ** of cell content.
10225     **
10226     ** The loop below pulls entries from the min-heap in order and compares
10227     ** the start_address against the previous end_address.  If there is an
10228     ** overlap, that means bytes are used multiple times.  If there is a gap,
10229     ** that gap is added to the fragmentation count.
10230     */
10231     nFrag = 0;
10232     prev = contentOffset - 1;   /* Implied first min-heap entry */
10233     while( btreeHeapPull(heap,&x) ){
10234       if( (prev&0xffff)>=(x>>16) ){
10235         checkAppendMsg(pCheck,
10236           "Multiple uses for byte %u of page %u", x>>16, iPage);
10237         break;
10238       }else{
10239         nFrag += (x>>16) - (prev&0xffff) - 1;
10240         prev = x;
10241       }
10242     }
10243     nFrag += usableSize - (prev&0xffff) - 1;
10244     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10245     ** is stored in the fifth field of the b-tree page header.
10246     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10247     ** number of fragmented free bytes within the cell content area.
10248     */
10249     if( heap[0]==0 && nFrag!=data[hdr+7] ){
10250       checkAppendMsg(pCheck,
10251           "Fragmentation of %d bytes reported as %d on page %u",
10252           nFrag, data[hdr+7], iPage);
10253     }
10254   }
10255 
10256 end_of_check:
10257   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10258   releasePage(pPage);
10259   pCheck->zPfx = saved_zPfx;
10260   pCheck->v1 = saved_v1;
10261   pCheck->v2 = saved_v2;
10262   return depth+1;
10263 }
10264 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10265 
10266 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10267 /*
10268 ** This routine does a complete check of the given BTree file.  aRoot[] is
10269 ** an array of pages numbers were each page number is the root page of
10270 ** a table.  nRoot is the number of entries in aRoot.
10271 **
10272 ** A read-only or read-write transaction must be opened before calling
10273 ** this function.
10274 **
10275 ** Write the number of error seen in *pnErr.  Except for some memory
10276 ** allocation errors,  an error message held in memory obtained from
10277 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
10278 ** returned.  If a memory allocation error occurs, NULL is returned.
10279 **
10280 ** If the first entry in aRoot[] is 0, that indicates that the list of
10281 ** root pages is incomplete.  This is a "partial integrity-check".  This
10282 ** happens when performing an integrity check on a single table.  The
10283 ** zero is skipped, of course.  But in addition, the freelist checks
10284 ** and the checks to make sure every page is referenced are also skipped,
10285 ** since obviously it is not possible to know which pages are covered by
10286 ** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
10287 ** checks are still performed.
10288 */
10289 char *sqlite3BtreeIntegrityCheck(
10290   sqlite3 *db,  /* Database connection that is running the check */
10291   Btree *p,     /* The btree to be checked */
10292   Pgno *aRoot,  /* An array of root pages numbers for individual trees */
10293   int nRoot,    /* Number of entries in aRoot[] */
10294   int mxErr,    /* Stop reporting errors after this many */
10295   int *pnErr    /* Write number of errors seen to this variable */
10296 ){
10297   Pgno i;
10298   IntegrityCk sCheck;
10299   BtShared *pBt = p->pBt;
10300   u64 savedDbFlags = pBt->db->flags;
10301   char zErr[100];
10302   int bPartial = 0;            /* True if not checking all btrees */
10303   int bCkFreelist = 1;         /* True to scan the freelist */
10304   VVA_ONLY( int nRef );
10305   assert( nRoot>0 );
10306 
10307   /* aRoot[0]==0 means this is a partial check */
10308   if( aRoot[0]==0 ){
10309     assert( nRoot>1 );
10310     bPartial = 1;
10311     if( aRoot[1]!=1 ) bCkFreelist = 0;
10312   }
10313 
10314   sqlite3BtreeEnter(p);
10315   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10316   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10317   assert( nRef>=0 );
10318   sCheck.db = db;
10319   sCheck.pBt = pBt;
10320   sCheck.pPager = pBt->pPager;
10321   sCheck.nPage = btreePagecount(sCheck.pBt);
10322   sCheck.mxErr = mxErr;
10323   sCheck.nErr = 0;
10324   sCheck.bOomFault = 0;
10325   sCheck.zPfx = 0;
10326   sCheck.v1 = 0;
10327   sCheck.v2 = 0;
10328   sCheck.aPgRef = 0;
10329   sCheck.heap = 0;
10330   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10331   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10332   if( sCheck.nPage==0 ){
10333     goto integrity_ck_cleanup;
10334   }
10335 
10336   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10337   if( !sCheck.aPgRef ){
10338     sCheck.bOomFault = 1;
10339     goto integrity_ck_cleanup;
10340   }
10341   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10342   if( sCheck.heap==0 ){
10343     sCheck.bOomFault = 1;
10344     goto integrity_ck_cleanup;
10345   }
10346 
10347   i = PENDING_BYTE_PAGE(pBt);
10348   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10349 
10350   /* Check the integrity of the freelist
10351   */
10352   if( bCkFreelist ){
10353     sCheck.zPfx = "Main freelist: ";
10354     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10355               get4byte(&pBt->pPage1->aData[36]));
10356     sCheck.zPfx = 0;
10357   }
10358 
10359   /* Check all the tables.
10360   */
10361 #ifndef SQLITE_OMIT_AUTOVACUUM
10362   if( !bPartial ){
10363     if( pBt->autoVacuum ){
10364       Pgno mx = 0;
10365       Pgno mxInHdr;
10366       for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10367       mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10368       if( mx!=mxInHdr ){
10369         checkAppendMsg(&sCheck,
10370           "max rootpage (%d) disagrees with header (%d)",
10371           mx, mxInHdr
10372         );
10373       }
10374     }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10375       checkAppendMsg(&sCheck,
10376         "incremental_vacuum enabled with a max rootpage of zero"
10377       );
10378     }
10379   }
10380 #endif
10381   testcase( pBt->db->flags & SQLITE_CellSizeCk );
10382   pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10383   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10384     i64 notUsed;
10385     if( aRoot[i]==0 ) continue;
10386 #ifndef SQLITE_OMIT_AUTOVACUUM
10387     if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10388       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10389     }
10390 #endif
10391     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10392   }
10393   pBt->db->flags = savedDbFlags;
10394 
10395   /* Make sure every page in the file is referenced
10396   */
10397   if( !bPartial ){
10398     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10399 #ifdef SQLITE_OMIT_AUTOVACUUM
10400       if( getPageReferenced(&sCheck, i)==0 ){
10401         checkAppendMsg(&sCheck, "Page %d is never used", i);
10402       }
10403 #else
10404       /* If the database supports auto-vacuum, make sure no tables contain
10405       ** references to pointer-map pages.
10406       */
10407       if( getPageReferenced(&sCheck, i)==0 &&
10408          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10409         checkAppendMsg(&sCheck, "Page %d is never used", i);
10410       }
10411       if( getPageReferenced(&sCheck, i)!=0 &&
10412          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10413         checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10414       }
10415 #endif
10416     }
10417   }
10418 
10419   /* Clean  up and report errors.
10420   */
10421 integrity_ck_cleanup:
10422   sqlite3PageFree(sCheck.heap);
10423   sqlite3_free(sCheck.aPgRef);
10424   if( sCheck.bOomFault ){
10425     sqlite3_str_reset(&sCheck.errMsg);
10426     sCheck.nErr++;
10427   }
10428   *pnErr = sCheck.nErr;
10429   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10430   /* Make sure this analysis did not leave any unref() pages. */
10431   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10432   sqlite3BtreeLeave(p);
10433   return sqlite3StrAccumFinish(&sCheck.errMsg);
10434 }
10435 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10436 
10437 /*
10438 ** Return the full pathname of the underlying database file.  Return
10439 ** an empty string if the database is in-memory or a TEMP database.
10440 **
10441 ** The pager filename is invariant as long as the pager is
10442 ** open so it is safe to access without the BtShared mutex.
10443 */
10444 const char *sqlite3BtreeGetFilename(Btree *p){
10445   assert( p->pBt->pPager!=0 );
10446   return sqlite3PagerFilename(p->pBt->pPager, 1);
10447 }
10448 
10449 /*
10450 ** Return the pathname of the journal file for this database. The return
10451 ** value of this routine is the same regardless of whether the journal file
10452 ** has been created or not.
10453 **
10454 ** The pager journal filename is invariant as long as the pager is
10455 ** open so it is safe to access without the BtShared mutex.
10456 */
10457 const char *sqlite3BtreeGetJournalname(Btree *p){
10458   assert( p->pBt->pPager!=0 );
10459   return sqlite3PagerJournalname(p->pBt->pPager);
10460 }
10461 
10462 /*
10463 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10464 ** to describe the current transaction state of Btree p.
10465 */
10466 int sqlite3BtreeTxnState(Btree *p){
10467   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10468   return p ? p->inTrans : 0;
10469 }
10470 
10471 #ifndef SQLITE_OMIT_WAL
10472 /*
10473 ** Run a checkpoint on the Btree passed as the first argument.
10474 **
10475 ** Return SQLITE_LOCKED if this or any other connection has an open
10476 ** transaction on the shared-cache the argument Btree is connected to.
10477 **
10478 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10479 */
10480 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10481   int rc = SQLITE_OK;
10482   if( p ){
10483     BtShared *pBt = p->pBt;
10484     sqlite3BtreeEnter(p);
10485     if( pBt->inTransaction!=TRANS_NONE ){
10486       rc = SQLITE_LOCKED;
10487     }else{
10488       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10489     }
10490     sqlite3BtreeLeave(p);
10491   }
10492   return rc;
10493 }
10494 #endif
10495 
10496 /*
10497 ** Return true if there is currently a backup running on Btree p.
10498 */
10499 int sqlite3BtreeIsInBackup(Btree *p){
10500   assert( p );
10501   assert( sqlite3_mutex_held(p->db->mutex) );
10502   return p->nBackup!=0;
10503 }
10504 
10505 /*
10506 ** This function returns a pointer to a blob of memory associated with
10507 ** a single shared-btree. The memory is used by client code for its own
10508 ** purposes (for example, to store a high-level schema associated with
10509 ** the shared-btree). The btree layer manages reference counting issues.
10510 **
10511 ** The first time this is called on a shared-btree, nBytes bytes of memory
10512 ** are allocated, zeroed, and returned to the caller. For each subsequent
10513 ** call the nBytes parameter is ignored and a pointer to the same blob
10514 ** of memory returned.
10515 **
10516 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10517 ** allocated, a null pointer is returned. If the blob has already been
10518 ** allocated, it is returned as normal.
10519 **
10520 ** Just before the shared-btree is closed, the function passed as the
10521 ** xFree argument when the memory allocation was made is invoked on the
10522 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10523 ** on the memory, the btree layer does that.
10524 */
10525 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10526   BtShared *pBt = p->pBt;
10527   sqlite3BtreeEnter(p);
10528   if( !pBt->pSchema && nBytes ){
10529     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10530     pBt->xFreeSchema = xFree;
10531   }
10532   sqlite3BtreeLeave(p);
10533   return pBt->pSchema;
10534 }
10535 
10536 /*
10537 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10538 ** btree as the argument handle holds an exclusive lock on the
10539 ** sqlite_schema table. Otherwise SQLITE_OK.
10540 */
10541 int sqlite3BtreeSchemaLocked(Btree *p){
10542   int rc;
10543   assert( sqlite3_mutex_held(p->db->mutex) );
10544   sqlite3BtreeEnter(p);
10545   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10546   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10547   sqlite3BtreeLeave(p);
10548   return rc;
10549 }
10550 
10551 
10552 #ifndef SQLITE_OMIT_SHARED_CACHE
10553 /*
10554 ** Obtain a lock on the table whose root page is iTab.  The
10555 ** lock is a write lock if isWritelock is true or a read lock
10556 ** if it is false.
10557 */
10558 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10559   int rc = SQLITE_OK;
10560   assert( p->inTrans!=TRANS_NONE );
10561   if( p->sharable ){
10562     u8 lockType = READ_LOCK + isWriteLock;
10563     assert( READ_LOCK+1==WRITE_LOCK );
10564     assert( isWriteLock==0 || isWriteLock==1 );
10565 
10566     sqlite3BtreeEnter(p);
10567     rc = querySharedCacheTableLock(p, iTab, lockType);
10568     if( rc==SQLITE_OK ){
10569       rc = setSharedCacheTableLock(p, iTab, lockType);
10570     }
10571     sqlite3BtreeLeave(p);
10572   }
10573   return rc;
10574 }
10575 #endif
10576 
10577 #ifndef SQLITE_OMIT_INCRBLOB
10578 /*
10579 ** Argument pCsr must be a cursor opened for writing on an
10580 ** INTKEY table currently pointing at a valid table entry.
10581 ** This function modifies the data stored as part of that entry.
10582 **
10583 ** Only the data content may only be modified, it is not possible to
10584 ** change the length of the data stored. If this function is called with
10585 ** parameters that attempt to write past the end of the existing data,
10586 ** no modifications are made and SQLITE_CORRUPT is returned.
10587 */
10588 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10589   int rc;
10590   assert( cursorOwnsBtShared(pCsr) );
10591   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10592   assert( pCsr->curFlags & BTCF_Incrblob );
10593 
10594   rc = restoreCursorPosition(pCsr);
10595   if( rc!=SQLITE_OK ){
10596     return rc;
10597   }
10598   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10599   if( pCsr->eState!=CURSOR_VALID ){
10600     return SQLITE_ABORT;
10601   }
10602 
10603   /* Save the positions of all other cursors open on this table. This is
10604   ** required in case any of them are holding references to an xFetch
10605   ** version of the b-tree page modified by the accessPayload call below.
10606   **
10607   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10608   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10609   ** saveAllCursors can only return SQLITE_OK.
10610   */
10611   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10612   assert( rc==SQLITE_OK );
10613 
10614   /* Check some assumptions:
10615   **   (a) the cursor is open for writing,
10616   **   (b) there is a read/write transaction open,
10617   **   (c) the connection holds a write-lock on the table (if required),
10618   **   (d) there are no conflicting read-locks, and
10619   **   (e) the cursor points at a valid row of an intKey table.
10620   */
10621   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10622     return SQLITE_READONLY;
10623   }
10624   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10625               && pCsr->pBt->inTransaction==TRANS_WRITE );
10626   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10627   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10628   assert( pCsr->pPage->intKey );
10629 
10630   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10631 }
10632 
10633 /*
10634 ** Mark this cursor as an incremental blob cursor.
10635 */
10636 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10637   pCur->curFlags |= BTCF_Incrblob;
10638   pCur->pBtree->hasIncrblobCur = 1;
10639 }
10640 #endif
10641 
10642 /*
10643 ** Set both the "read version" (single byte at byte offset 18) and
10644 ** "write version" (single byte at byte offset 19) fields in the database
10645 ** header to iVersion.
10646 */
10647 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10648   BtShared *pBt = pBtree->pBt;
10649   int rc;                         /* Return code */
10650 
10651   assert( iVersion==1 || iVersion==2 );
10652 
10653   /* If setting the version fields to 1, do not automatically open the
10654   ** WAL connection, even if the version fields are currently set to 2.
10655   */
10656   pBt->btsFlags &= ~BTS_NO_WAL;
10657   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10658 
10659   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10660   if( rc==SQLITE_OK ){
10661     u8 *aData = pBt->pPage1->aData;
10662     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10663       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10664       if( rc==SQLITE_OK ){
10665         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10666         if( rc==SQLITE_OK ){
10667           aData[18] = (u8)iVersion;
10668           aData[19] = (u8)iVersion;
10669         }
10670       }
10671     }
10672   }
10673 
10674   pBt->btsFlags &= ~BTS_NO_WAL;
10675   return rc;
10676 }
10677 
10678 /*
10679 ** Return true if the cursor has a hint specified.  This routine is
10680 ** only used from within assert() statements
10681 */
10682 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10683   return (pCsr->hints & mask)!=0;
10684 }
10685 
10686 /*
10687 ** Return true if the given Btree is read-only.
10688 */
10689 int sqlite3BtreeIsReadonly(Btree *p){
10690   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10691 }
10692 
10693 /*
10694 ** Return the size of the header added to each page by this module.
10695 */
10696 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10697 
10698 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10699 /*
10700 ** Return true if the Btree passed as the only argument is sharable.
10701 */
10702 int sqlite3BtreeSharable(Btree *p){
10703   return p->sharable;
10704 }
10705 
10706 /*
10707 ** Return the number of connections to the BtShared object accessed by
10708 ** the Btree handle passed as the only argument. For private caches
10709 ** this is always 1. For shared caches it may be 1 or greater.
10710 */
10711 int sqlite3BtreeConnectionCount(Btree *p){
10712   testcase( p->sharable );
10713   return p->pBt->nRef;
10714 }
10715 #endif
10716