xref: /sqlite-3.40.0/src/btree.c (revision 63e9ec2f)
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==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   assert( pBtree->hasIncrblobCur );
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 sqlite3BtreeIndexMoveto() 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     }else{
831       rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
832     }
833     sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
834   }else{
835     pIdxKey = 0;
836     rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
837   }
838   return rc;
839 }
840 
841 /*
842 ** Restore the cursor to the position it was in (or as close to as possible)
843 ** when saveCursorPosition() was called. Note that this call deletes the
844 ** saved position info stored by saveCursorPosition(), so there can be
845 ** at most one effective restoreCursorPosition() call after each
846 ** saveCursorPosition().
847 */
848 static int btreeRestoreCursorPosition(BtCursor *pCur){
849   int rc;
850   int skipNext = 0;
851   assert( cursorOwnsBtShared(pCur) );
852   assert( pCur->eState>=CURSOR_REQUIRESEEK );
853   if( pCur->eState==CURSOR_FAULT ){
854     return pCur->skipNext;
855   }
856   pCur->eState = CURSOR_INVALID;
857   if( sqlite3FaultSim(410) ){
858     rc = SQLITE_IOERR;
859   }else{
860     rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
861   }
862   if( rc==SQLITE_OK ){
863     sqlite3_free(pCur->pKey);
864     pCur->pKey = 0;
865     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
866     if( skipNext ) pCur->skipNext = skipNext;
867     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
868       pCur->eState = CURSOR_SKIPNEXT;
869     }
870   }
871   return rc;
872 }
873 
874 #define restoreCursorPosition(p) \
875   (p->eState>=CURSOR_REQUIRESEEK ? \
876          btreeRestoreCursorPosition(p) : \
877          SQLITE_OK)
878 
879 /*
880 ** Determine whether or not a cursor has moved from the position where
881 ** it was last placed, or has been invalidated for any other reason.
882 ** Cursors can move when the row they are pointing at is deleted out
883 ** from under them, for example.  Cursor might also move if a btree
884 ** is rebalanced.
885 **
886 ** Calling this routine with a NULL cursor pointer returns false.
887 **
888 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
889 ** back to where it ought to be if this routine returns true.
890 */
891 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
892   assert( EIGHT_BYTE_ALIGNMENT(pCur)
893        || pCur==sqlite3BtreeFakeValidCursor() );
894   assert( offsetof(BtCursor, eState)==0 );
895   assert( sizeof(pCur->eState)==1 );
896   return CURSOR_VALID != *(u8*)pCur;
897 }
898 
899 /*
900 ** Return a pointer to a fake BtCursor object that will always answer
901 ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
902 ** cursor returned must not be used with any other Btree interface.
903 */
904 BtCursor *sqlite3BtreeFakeValidCursor(void){
905   static u8 fakeCursor = CURSOR_VALID;
906   assert( offsetof(BtCursor, eState)==0 );
907   return (BtCursor*)&fakeCursor;
908 }
909 
910 /*
911 ** This routine restores a cursor back to its original position after it
912 ** has been moved by some outside activity (such as a btree rebalance or
913 ** a row having been deleted out from under the cursor).
914 **
915 ** On success, the *pDifferentRow parameter is false if the cursor is left
916 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
917 ** was pointing to has been deleted, forcing the cursor to point to some
918 ** nearby row.
919 **
920 ** This routine should only be called for a cursor that just returned
921 ** TRUE from sqlite3BtreeCursorHasMoved().
922 */
923 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
924   int rc;
925 
926   assert( pCur!=0 );
927   assert( pCur->eState!=CURSOR_VALID );
928   rc = restoreCursorPosition(pCur);
929   if( rc ){
930     *pDifferentRow = 1;
931     return rc;
932   }
933   if( pCur->eState!=CURSOR_VALID ){
934     *pDifferentRow = 1;
935   }else{
936     *pDifferentRow = 0;
937   }
938   return SQLITE_OK;
939 }
940 
941 #ifdef SQLITE_ENABLE_CURSOR_HINTS
942 /*
943 ** Provide hints to the cursor.  The particular hint given (and the type
944 ** and number of the varargs parameters) is determined by the eHintType
945 ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
946 */
947 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
948   /* Used only by system that substitute their own storage engine */
949 }
950 #endif
951 
952 /*
953 ** Provide flag hints to the cursor.
954 */
955 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
956   assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
957   pCur->hints = x;
958 }
959 
960 
961 #ifndef SQLITE_OMIT_AUTOVACUUM
962 /*
963 ** Given a page number of a regular database page, return the page
964 ** number for the pointer-map page that contains the entry for the
965 ** input page number.
966 **
967 ** Return 0 (not a valid page) for pgno==1 since there is
968 ** no pointer map associated with page 1.  The integrity_check logic
969 ** requires that ptrmapPageno(*,1)!=1.
970 */
971 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
972   int nPagesPerMapPage;
973   Pgno iPtrMap, ret;
974   assert( sqlite3_mutex_held(pBt->mutex) );
975   if( pgno<2 ) return 0;
976   nPagesPerMapPage = (pBt->usableSize/5)+1;
977   iPtrMap = (pgno-2)/nPagesPerMapPage;
978   ret = (iPtrMap*nPagesPerMapPage) + 2;
979   if( ret==PENDING_BYTE_PAGE(pBt) ){
980     ret++;
981   }
982   return ret;
983 }
984 
985 /*
986 ** Write an entry into the pointer map.
987 **
988 ** This routine updates the pointer map entry for page number 'key'
989 ** so that it maps to type 'eType' and parent page number 'pgno'.
990 **
991 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
992 ** a no-op.  If an error occurs, the appropriate error code is written
993 ** into *pRC.
994 */
995 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
996   DbPage *pDbPage;  /* The pointer map page */
997   u8 *pPtrmap;      /* The pointer map data */
998   Pgno iPtrmap;     /* The pointer map page number */
999   int offset;       /* Offset in pointer map page */
1000   int rc;           /* Return code from subfunctions */
1001 
1002   if( *pRC ) return;
1003 
1004   assert( sqlite3_mutex_held(pBt->mutex) );
1005   /* The super-journal page number must never be used as a pointer map page */
1006   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1007 
1008   assert( pBt->autoVacuum );
1009   if( key==0 ){
1010     *pRC = SQLITE_CORRUPT_BKPT;
1011     return;
1012   }
1013   iPtrmap = PTRMAP_PAGENO(pBt, key);
1014   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1015   if( rc!=SQLITE_OK ){
1016     *pRC = rc;
1017     return;
1018   }
1019   if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1020     /* The first byte of the extra data is the MemPage.isInit byte.
1021     ** If that byte is set, it means this page is also being used
1022     ** as a btree page. */
1023     *pRC = SQLITE_CORRUPT_BKPT;
1024     goto ptrmap_exit;
1025   }
1026   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1027   if( offset<0 ){
1028     *pRC = SQLITE_CORRUPT_BKPT;
1029     goto ptrmap_exit;
1030   }
1031   assert( offset <= (int)pBt->usableSize-5 );
1032   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1033 
1034   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1035     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1036     *pRC= rc = sqlite3PagerWrite(pDbPage);
1037     if( rc==SQLITE_OK ){
1038       pPtrmap[offset] = eType;
1039       put4byte(&pPtrmap[offset+1], parent);
1040     }
1041   }
1042 
1043 ptrmap_exit:
1044   sqlite3PagerUnref(pDbPage);
1045 }
1046 
1047 /*
1048 ** Read an entry from the pointer map.
1049 **
1050 ** This routine retrieves the pointer map entry for page 'key', writing
1051 ** the type and parent page number to *pEType and *pPgno respectively.
1052 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1053 */
1054 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1055   DbPage *pDbPage;   /* The pointer map page */
1056   int iPtrmap;       /* Pointer map page index */
1057   u8 *pPtrmap;       /* Pointer map page data */
1058   int offset;        /* Offset of entry in pointer map */
1059   int rc;
1060 
1061   assert( sqlite3_mutex_held(pBt->mutex) );
1062 
1063   iPtrmap = PTRMAP_PAGENO(pBt, key);
1064   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1065   if( rc!=0 ){
1066     return rc;
1067   }
1068   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1069 
1070   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1071   if( offset<0 ){
1072     sqlite3PagerUnref(pDbPage);
1073     return SQLITE_CORRUPT_BKPT;
1074   }
1075   assert( offset <= (int)pBt->usableSize-5 );
1076   assert( pEType!=0 );
1077   *pEType = pPtrmap[offset];
1078   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1079 
1080   sqlite3PagerUnref(pDbPage);
1081   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1082   return SQLITE_OK;
1083 }
1084 
1085 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1086   #define ptrmapPut(w,x,y,z,rc)
1087   #define ptrmapGet(w,x,y,z) SQLITE_OK
1088   #define ptrmapPutOvflPtr(x, y, z, rc)
1089 #endif
1090 
1091 /*
1092 ** Given a btree page and a cell index (0 means the first cell on
1093 ** the page, 1 means the second cell, and so forth) return a pointer
1094 ** to the cell content.
1095 **
1096 ** findCellPastPtr() does the same except it skips past the initial
1097 ** 4-byte child pointer found on interior pages, if there is one.
1098 **
1099 ** This routine works only for pages that do not contain overflow cells.
1100 */
1101 #define findCell(P,I) \
1102   ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1103 #define findCellPastPtr(P,I) \
1104   ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1105 
1106 
1107 /*
1108 ** This is common tail processing for btreeParseCellPtr() and
1109 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1110 ** on a single B-tree page.  Make necessary adjustments to the CellInfo
1111 ** structure.
1112 */
1113 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1114   MemPage *pPage,         /* Page containing the cell */
1115   u8 *pCell,              /* Pointer to the cell text. */
1116   CellInfo *pInfo         /* Fill in this structure */
1117 ){
1118   /* If the payload will not fit completely on the local page, we have
1119   ** to decide how much to store locally and how much to spill onto
1120   ** overflow pages.  The strategy is to minimize the amount of unused
1121   ** space on overflow pages while keeping the amount of local storage
1122   ** in between minLocal and maxLocal.
1123   **
1124   ** Warning:  changing the way overflow payload is distributed in any
1125   ** way will result in an incompatible file format.
1126   */
1127   int minLocal;  /* Minimum amount of payload held locally */
1128   int maxLocal;  /* Maximum amount of payload held locally */
1129   int surplus;   /* Overflow payload available for local storage */
1130 
1131   minLocal = pPage->minLocal;
1132   maxLocal = pPage->maxLocal;
1133   surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1134   testcase( surplus==maxLocal );
1135   testcase( surplus==maxLocal+1 );
1136   if( surplus <= maxLocal ){
1137     pInfo->nLocal = (u16)surplus;
1138   }else{
1139     pInfo->nLocal = (u16)minLocal;
1140   }
1141   pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1142 }
1143 
1144 /*
1145 ** Given a record with nPayload bytes of payload stored within btree
1146 ** page pPage, return the number of bytes of payload stored locally.
1147 */
1148 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1149   int maxLocal;  /* Maximum amount of payload held locally */
1150   maxLocal = pPage->maxLocal;
1151   if( nPayload<=maxLocal ){
1152     return nPayload;
1153   }else{
1154     int minLocal;  /* Minimum amount of payload held locally */
1155     int surplus;   /* Overflow payload available for local storage */
1156     minLocal = pPage->minLocal;
1157     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1158     return ( surplus <= maxLocal ) ? surplus : minLocal;
1159   }
1160 }
1161 
1162 /*
1163 ** The following routines are implementations of the MemPage.xParseCell()
1164 ** method.
1165 **
1166 ** Parse a cell content block and fill in the CellInfo structure.
1167 **
1168 ** btreeParseCellPtr()        =>   table btree leaf nodes
1169 ** btreeParseCellNoPayload()  =>   table btree internal nodes
1170 ** btreeParseCellPtrIndex()   =>   index btree nodes
1171 **
1172 ** There is also a wrapper function btreeParseCell() that works for
1173 ** all MemPage types and that references the cell by index rather than
1174 ** by pointer.
1175 */
1176 static void btreeParseCellPtrNoPayload(
1177   MemPage *pPage,         /* Page containing the cell */
1178   u8 *pCell,              /* Pointer to the cell text. */
1179   CellInfo *pInfo         /* Fill in this structure */
1180 ){
1181   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1182   assert( pPage->leaf==0 );
1183   assert( pPage->childPtrSize==4 );
1184 #ifndef SQLITE_DEBUG
1185   UNUSED_PARAMETER(pPage);
1186 #endif
1187   pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1188   pInfo->nPayload = 0;
1189   pInfo->nLocal = 0;
1190   pInfo->pPayload = 0;
1191   return;
1192 }
1193 static void btreeParseCellPtr(
1194   MemPage *pPage,         /* Page containing the cell */
1195   u8 *pCell,              /* Pointer to the cell text. */
1196   CellInfo *pInfo         /* Fill in this structure */
1197 ){
1198   u8 *pIter;              /* For scanning through pCell */
1199   u32 nPayload;           /* Number of bytes of cell payload */
1200   u64 iKey;               /* Extracted Key value */
1201 
1202   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1203   assert( pPage->leaf==0 || pPage->leaf==1 );
1204   assert( pPage->intKeyLeaf );
1205   assert( pPage->childPtrSize==0 );
1206   pIter = pCell;
1207 
1208   /* The next block of code is equivalent to:
1209   **
1210   **     pIter += getVarint32(pIter, nPayload);
1211   **
1212   ** The code is inlined to avoid a function call.
1213   */
1214   nPayload = *pIter;
1215   if( nPayload>=0x80 ){
1216     u8 *pEnd = &pIter[8];
1217     nPayload &= 0x7f;
1218     do{
1219       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1220     }while( (*pIter)>=0x80 && pIter<pEnd );
1221   }
1222   pIter++;
1223 
1224   /* The next block of code is equivalent to:
1225   **
1226   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1227   **
1228   ** The code is inlined and the loop is unrolled for performance.
1229   ** This routine is a high-runner.
1230   */
1231   iKey = *pIter;
1232   if( iKey>=0x80 ){
1233     u8 x;
1234     iKey = ((iKey&0x7f)<<7) | ((x = *++pIter) & 0x7f);
1235     if( x>=0x80 ){
1236       iKey = (iKey<<7) | ((x =*++pIter) & 0x7f);
1237       if( x>=0x80 ){
1238         iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1239         if( x>=0x80 ){
1240           iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1241           if( x>=0x80 ){
1242             iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1243             if( x>=0x80 ){
1244               iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1245               if( x>=0x80 ){
1246                 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1247                 if( x>=0x80 ){
1248                   iKey = (iKey<<8) | (*++pIter);
1249                 }
1250               }
1251             }
1252           }
1253         }
1254       }
1255     }
1256   }
1257   pIter++;
1258 
1259   pInfo->nKey = *(i64*)&iKey;
1260   pInfo->nPayload = nPayload;
1261   pInfo->pPayload = pIter;
1262   testcase( nPayload==pPage->maxLocal );
1263   testcase( nPayload==(u32)pPage->maxLocal+1 );
1264   if( nPayload<=pPage->maxLocal ){
1265     /* This is the (easy) common case where the entire payload fits
1266     ** on the local page.  No overflow is required.
1267     */
1268     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1269     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1270     pInfo->nLocal = (u16)nPayload;
1271   }else{
1272     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1273   }
1274 }
1275 static void btreeParseCellPtrIndex(
1276   MemPage *pPage,         /* Page containing the cell */
1277   u8 *pCell,              /* Pointer to the cell text. */
1278   CellInfo *pInfo         /* Fill in this structure */
1279 ){
1280   u8 *pIter;              /* For scanning through pCell */
1281   u32 nPayload;           /* Number of bytes of cell payload */
1282 
1283   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1284   assert( pPage->leaf==0 || pPage->leaf==1 );
1285   assert( pPage->intKeyLeaf==0 );
1286   pIter = pCell + pPage->childPtrSize;
1287   nPayload = *pIter;
1288   if( nPayload>=0x80 ){
1289     u8 *pEnd = &pIter[8];
1290     nPayload &= 0x7f;
1291     do{
1292       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1293     }while( *(pIter)>=0x80 && pIter<pEnd );
1294   }
1295   pIter++;
1296   pInfo->nKey = nPayload;
1297   pInfo->nPayload = nPayload;
1298   pInfo->pPayload = pIter;
1299   testcase( nPayload==pPage->maxLocal );
1300   testcase( nPayload==(u32)pPage->maxLocal+1 );
1301   if( nPayload<=pPage->maxLocal ){
1302     /* This is the (easy) common case where the entire payload fits
1303     ** on the local page.  No overflow is required.
1304     */
1305     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1306     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1307     pInfo->nLocal = (u16)nPayload;
1308   }else{
1309     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1310   }
1311 }
1312 static void btreeParseCell(
1313   MemPage *pPage,         /* Page containing the cell */
1314   int iCell,              /* The cell index.  First cell is 0 */
1315   CellInfo *pInfo         /* Fill in this structure */
1316 ){
1317   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1318 }
1319 
1320 /*
1321 ** The following routines are implementations of the MemPage.xCellSize
1322 ** method.
1323 **
1324 ** Compute the total number of bytes that a Cell needs in the cell
1325 ** data area of the btree-page.  The return number includes the cell
1326 ** data header and the local payload, but not any overflow page or
1327 ** the space used by the cell pointer.
1328 **
1329 ** cellSizePtrNoPayload()    =>   table internal nodes
1330 ** cellSizePtrTableLeaf()    =>   table leaf nodes
1331 ** cellSizePtr()             =>   all index nodes & table leaf nodes
1332 */
1333 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1334   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1335   u8 *pEnd;                                /* End mark for a varint */
1336   u32 nSize;                               /* Size value to return */
1337 
1338 #ifdef SQLITE_DEBUG
1339   /* The value returned by this function should always be the same as
1340   ** the (CellInfo.nSize) value found by doing a full parse of the
1341   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1342   ** this function verifies that this invariant is not violated. */
1343   CellInfo debuginfo;
1344   pPage->xParseCell(pPage, pCell, &debuginfo);
1345 #endif
1346 
1347   nSize = *pIter;
1348   if( nSize>=0x80 ){
1349     pEnd = &pIter[8];
1350     nSize &= 0x7f;
1351     do{
1352       nSize = (nSize<<7) | (*++pIter & 0x7f);
1353     }while( *(pIter)>=0x80 && pIter<pEnd );
1354   }
1355   pIter++;
1356   testcase( nSize==pPage->maxLocal );
1357   testcase( nSize==(u32)pPage->maxLocal+1 );
1358   if( nSize<=pPage->maxLocal ){
1359     nSize += (u32)(pIter - pCell);
1360     if( nSize<4 ) nSize = 4;
1361   }else{
1362     int minLocal = pPage->minLocal;
1363     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1364     testcase( nSize==pPage->maxLocal );
1365     testcase( nSize==(u32)pPage->maxLocal+1 );
1366     if( nSize>pPage->maxLocal ){
1367       nSize = minLocal;
1368     }
1369     nSize += 4 + (u16)(pIter - pCell);
1370   }
1371   assert( nSize==debuginfo.nSize || CORRUPT_DB );
1372   return (u16)nSize;
1373 }
1374 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1375   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1376   u8 *pEnd;              /* End mark for a varint */
1377 
1378 #ifdef SQLITE_DEBUG
1379   /* The value returned by this function should always be the same as
1380   ** the (CellInfo.nSize) value found by doing a full parse of the
1381   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1382   ** this function verifies that this invariant is not violated. */
1383   CellInfo debuginfo;
1384   pPage->xParseCell(pPage, pCell, &debuginfo);
1385 #else
1386   UNUSED_PARAMETER(pPage);
1387 #endif
1388 
1389   assert( pPage->childPtrSize==4 );
1390   pEnd = pIter + 9;
1391   while( (*pIter++)&0x80 && pIter<pEnd );
1392   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1393   return (u16)(pIter - pCell);
1394 }
1395 static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
1396   u8 *pIter = pCell;   /* For looping over bytes of pCell */
1397   u8 *pEnd;            /* End mark for a varint */
1398   u32 nSize;           /* Size value to return */
1399 
1400 #ifdef SQLITE_DEBUG
1401   /* The value returned by this function should always be the same as
1402   ** the (CellInfo.nSize) value found by doing a full parse of the
1403   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1404   ** this function verifies that this invariant is not violated. */
1405   CellInfo debuginfo;
1406   pPage->xParseCell(pPage, pCell, &debuginfo);
1407 #endif
1408 
1409   nSize = *pIter;
1410   if( nSize>=0x80 ){
1411     pEnd = &pIter[8];
1412     nSize &= 0x7f;
1413     do{
1414       nSize = (nSize<<7) | (*++pIter & 0x7f);
1415     }while( *(pIter)>=0x80 && pIter<pEnd );
1416   }
1417   pIter++;
1418   /* pIter now points at the 64-bit integer key value, a variable length
1419   ** integer. The following block moves pIter to point at the first byte
1420   ** past the end of the key value. */
1421   if( (*pIter++)&0x80
1422    && (*pIter++)&0x80
1423    && (*pIter++)&0x80
1424    && (*pIter++)&0x80
1425    && (*pIter++)&0x80
1426    && (*pIter++)&0x80
1427    && (*pIter++)&0x80
1428    && (*pIter++)&0x80 ){ pIter++; }
1429   testcase( nSize==pPage->maxLocal );
1430   testcase( nSize==(u32)pPage->maxLocal+1 );
1431   if( nSize<=pPage->maxLocal ){
1432     nSize += (u32)(pIter - pCell);
1433     if( nSize<4 ) nSize = 4;
1434   }else{
1435     int minLocal = pPage->minLocal;
1436     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1437     testcase( nSize==pPage->maxLocal );
1438     testcase( nSize==(u32)pPage->maxLocal+1 );
1439     if( nSize>pPage->maxLocal ){
1440       nSize = minLocal;
1441     }
1442     nSize += 4 + (u16)(pIter - pCell);
1443   }
1444   assert( nSize==debuginfo.nSize || CORRUPT_DB );
1445   return (u16)nSize;
1446 }
1447 
1448 
1449 #ifdef SQLITE_DEBUG
1450 /* This variation on cellSizePtr() is used inside of assert() statements
1451 ** only. */
1452 static u16 cellSize(MemPage *pPage, int iCell){
1453   return pPage->xCellSize(pPage, findCell(pPage, iCell));
1454 }
1455 #endif
1456 
1457 #ifndef SQLITE_OMIT_AUTOVACUUM
1458 /*
1459 ** The cell pCell is currently part of page pSrc but will ultimately be part
1460 ** of pPage.  (pSrc and pPage are often the same.)  If pCell contains a
1461 ** pointer to an overflow page, insert an entry into the pointer-map for
1462 ** the overflow page that will be valid after pCell has been moved to pPage.
1463 */
1464 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1465   CellInfo info;
1466   if( *pRC ) return;
1467   assert( pCell!=0 );
1468   pPage->xParseCell(pPage, pCell, &info);
1469   if( info.nLocal<info.nPayload ){
1470     Pgno ovfl;
1471     if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1472       testcase( pSrc!=pPage );
1473       *pRC = SQLITE_CORRUPT_BKPT;
1474       return;
1475     }
1476     ovfl = get4byte(&pCell[info.nSize-4]);
1477     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1478   }
1479 }
1480 #endif
1481 
1482 
1483 /*
1484 ** Defragment the page given. This routine reorganizes cells within the
1485 ** page so that there are no free-blocks on the free-block list.
1486 **
1487 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1488 ** present in the page after this routine returns.
1489 **
1490 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1491 ** b-tree page so that there are no freeblocks or fragment bytes, all
1492 ** unused bytes are contained in the unallocated space region, and all
1493 ** cells are packed tightly at the end of the page.
1494 */
1495 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1496   int i;                     /* Loop counter */
1497   int pc;                    /* Address of the i-th cell */
1498   int hdr;                   /* Offset to the page header */
1499   int size;                  /* Size of a cell */
1500   int usableSize;            /* Number of usable bytes on a page */
1501   int cellOffset;            /* Offset to the cell pointer array */
1502   int cbrk;                  /* Offset to the cell content area */
1503   int nCell;                 /* Number of cells on the page */
1504   unsigned char *data;       /* The page data */
1505   unsigned char *temp;       /* Temp area for cell content */
1506   unsigned char *src;        /* Source of content */
1507   int iCellFirst;            /* First allowable cell index */
1508   int iCellLast;             /* Last possible cell index */
1509   int iCellStart;            /* First cell offset in input */
1510 
1511   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1512   assert( pPage->pBt!=0 );
1513   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1514   assert( pPage->nOverflow==0 );
1515   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1516   data = pPage->aData;
1517   hdr = pPage->hdrOffset;
1518   cellOffset = pPage->cellOffset;
1519   nCell = pPage->nCell;
1520   assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1521   iCellFirst = cellOffset + 2*nCell;
1522   usableSize = pPage->pBt->usableSize;
1523 
1524   /* This block handles pages with two or fewer free blocks and nMaxFrag
1525   ** or fewer fragmented bytes. In this case it is faster to move the
1526   ** two (or one) blocks of cells using memmove() and add the required
1527   ** offsets to each pointer in the cell-pointer array than it is to
1528   ** reconstruct the entire page.  */
1529   if( (int)data[hdr+7]<=nMaxFrag ){
1530     int iFree = get2byte(&data[hdr+1]);
1531     if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1532     if( iFree ){
1533       int iFree2 = get2byte(&data[iFree]);
1534       if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1535       if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1536         u8 *pEnd = &data[cellOffset + nCell*2];
1537         u8 *pAddr;
1538         int sz2 = 0;
1539         int sz = get2byte(&data[iFree+2]);
1540         int top = get2byte(&data[hdr+5]);
1541         if( top>=iFree ){
1542           return SQLITE_CORRUPT_PAGE(pPage);
1543         }
1544         if( iFree2 ){
1545           if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1546           sz2 = get2byte(&data[iFree2+2]);
1547           if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1548           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1549           sz += sz2;
1550         }else if( iFree+sz>usableSize ){
1551           return SQLITE_CORRUPT_PAGE(pPage);
1552         }
1553 
1554         cbrk = top+sz;
1555         assert( cbrk+(iFree-top) <= usableSize );
1556         memmove(&data[cbrk], &data[top], iFree-top);
1557         for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1558           pc = get2byte(pAddr);
1559           if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1560           else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1561         }
1562         goto defragment_out;
1563       }
1564     }
1565   }
1566 
1567   cbrk = usableSize;
1568   iCellLast = usableSize - 4;
1569   iCellStart = get2byte(&data[hdr+5]);
1570   if( nCell>0 ){
1571     temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1572     memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1573     src = temp;
1574     for(i=0; i<nCell; i++){
1575       u8 *pAddr;     /* The i-th cell pointer */
1576       pAddr = &data[cellOffset + i*2];
1577       pc = get2byte(pAddr);
1578       testcase( pc==iCellFirst );
1579       testcase( pc==iCellLast );
1580       /* These conditions have already been verified in btreeInitPage()
1581       ** if PRAGMA cell_size_check=ON.
1582       */
1583       if( pc<iCellStart || pc>iCellLast ){
1584         return SQLITE_CORRUPT_PAGE(pPage);
1585       }
1586       assert( pc>=iCellStart && pc<=iCellLast );
1587       size = pPage->xCellSize(pPage, &src[pc]);
1588       cbrk -= size;
1589       if( cbrk<iCellStart || pc+size>usableSize ){
1590         return SQLITE_CORRUPT_PAGE(pPage);
1591       }
1592       assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1593       testcase( cbrk+size==usableSize );
1594       testcase( pc+size==usableSize );
1595       put2byte(pAddr, cbrk);
1596       memcpy(&data[cbrk], &src[pc], size);
1597     }
1598   }
1599   data[hdr+7] = 0;
1600 
1601 defragment_out:
1602   assert( pPage->nFree>=0 );
1603   if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1604     return SQLITE_CORRUPT_PAGE(pPage);
1605   }
1606   assert( cbrk>=iCellFirst );
1607   put2byte(&data[hdr+5], cbrk);
1608   data[hdr+1] = 0;
1609   data[hdr+2] = 0;
1610   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1611   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1612   return SQLITE_OK;
1613 }
1614 
1615 /*
1616 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1617 ** size. If one can be found, return a pointer to the space and remove it
1618 ** from the free-list.
1619 **
1620 ** If no suitable space can be found on the free-list, return NULL.
1621 **
1622 ** This function may detect corruption within pPg.  If corruption is
1623 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1624 **
1625 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1626 ** will be ignored if adding the extra space to the fragmentation count
1627 ** causes the fragmentation count to exceed 60.
1628 */
1629 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1630   const int hdr = pPg->hdrOffset;            /* Offset to page header */
1631   u8 * const aData = pPg->aData;             /* Page data */
1632   int iAddr = hdr + 1;                       /* Address of ptr to pc */
1633   u8 *pTmp = &aData[iAddr];                  /* Temporary ptr into aData[] */
1634   int pc = get2byte(pTmp);                   /* Address of a free slot */
1635   int x;                                     /* Excess size of the slot */
1636   int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */
1637   int size;                                  /* Size of the free slot */
1638 
1639   assert( pc>0 );
1640   while( pc<=maxPC ){
1641     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1642     ** freeblock form a big-endian integer which is the size of the freeblock
1643     ** in bytes, including the 4-byte header. */
1644     pTmp = &aData[pc+2];
1645     size = get2byte(pTmp);
1646     if( (x = size - nByte)>=0 ){
1647       testcase( x==4 );
1648       testcase( x==3 );
1649       if( x<4 ){
1650         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1651         ** number of bytes in fragments may not exceed 60. */
1652         if( aData[hdr+7]>57 ) return 0;
1653 
1654         /* Remove the slot from the free-list. Update the number of
1655         ** fragmented bytes within the page. */
1656         memcpy(&aData[iAddr], &aData[pc], 2);
1657         aData[hdr+7] += (u8)x;
1658         testcase( pc+x>maxPC );
1659         return &aData[pc];
1660       }else if( x+pc > maxPC ){
1661         /* This slot extends off the end of the usable part of the page */
1662         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1663         return 0;
1664       }else{
1665         /* The slot remains on the free-list. Reduce its size to account
1666         ** for the portion used by the new allocation. */
1667         put2byte(&aData[pc+2], x);
1668       }
1669       return &aData[pc + x];
1670     }
1671     iAddr = pc;
1672     pTmp = &aData[pc];
1673     pc = get2byte(pTmp);
1674     if( pc<=iAddr ){
1675       if( pc ){
1676         /* The next slot in the chain comes before the current slot */
1677         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1678       }
1679       return 0;
1680     }
1681   }
1682   if( pc>maxPC+nByte-4 ){
1683     /* The free slot chain extends off the end of the page */
1684     *pRc = SQLITE_CORRUPT_PAGE(pPg);
1685   }
1686   return 0;
1687 }
1688 
1689 /*
1690 ** Allocate nByte bytes of space from within the B-Tree page passed
1691 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1692 ** of the first byte of allocated space. Return either SQLITE_OK or
1693 ** an error code (usually SQLITE_CORRUPT).
1694 **
1695 ** The caller guarantees that there is sufficient space to make the
1696 ** allocation.  This routine might need to defragment in order to bring
1697 ** all the space together, however.  This routine will avoid using
1698 ** the first two bytes past the cell pointer area since presumably this
1699 ** allocation is being made in order to insert a new cell, so we will
1700 ** also end up needing a new cell pointer.
1701 */
1702 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1703   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
1704   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
1705   int top;                             /* First byte of cell content area */
1706   int rc = SQLITE_OK;                  /* Integer return code */
1707   u8 *pTmp;                            /* Temp ptr into data[] */
1708   int gap;        /* First byte of gap between cell pointers and cell content */
1709 
1710   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1711   assert( pPage->pBt );
1712   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1713   assert( nByte>=0 );  /* Minimum cell size is 4 */
1714   assert( pPage->nFree>=nByte );
1715   assert( pPage->nOverflow==0 );
1716   assert( nByte < (int)(pPage->pBt->usableSize-8) );
1717 
1718   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1719   gap = pPage->cellOffset + 2*pPage->nCell;
1720   assert( gap<=65536 );
1721   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1722   ** and the reserved space is zero (the usual value for reserved space)
1723   ** then the cell content offset of an empty page wants to be 65536.
1724   ** However, that integer is too large to be stored in a 2-byte unsigned
1725   ** integer, so a value of 0 is used in its place. */
1726   pTmp = &data[hdr+5];
1727   top = get2byte(pTmp);
1728   assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1729   if( gap>top ){
1730     if( top==0 && pPage->pBt->usableSize==65536 ){
1731       top = 65536;
1732     }else{
1733       return SQLITE_CORRUPT_PAGE(pPage);
1734     }
1735   }
1736 
1737   /* If there is enough space between gap and top for one more cell pointer,
1738   ** and if the freelist is not empty, then search the
1739   ** freelist looking for a slot big enough to satisfy the request.
1740   */
1741   testcase( gap+2==top );
1742   testcase( gap+1==top );
1743   testcase( gap==top );
1744   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1745     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1746     if( pSpace ){
1747       int g2;
1748       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1749       *pIdx = g2 = (int)(pSpace-data);
1750       if( g2<=gap ){
1751         return SQLITE_CORRUPT_PAGE(pPage);
1752       }else{
1753         return SQLITE_OK;
1754       }
1755     }else if( rc ){
1756       return rc;
1757     }
1758   }
1759 
1760   /* The request could not be fulfilled using a freelist slot.  Check
1761   ** to see if defragmentation is necessary.
1762   */
1763   testcase( gap+2+nByte==top );
1764   if( gap+2+nByte>top ){
1765     assert( pPage->nCell>0 || CORRUPT_DB );
1766     assert( pPage->nFree>=0 );
1767     rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1768     if( rc ) return rc;
1769     top = get2byteNotZero(&data[hdr+5]);
1770     assert( gap+2+nByte<=top );
1771   }
1772 
1773 
1774   /* Allocate memory from the gap in between the cell pointer array
1775   ** and the cell content area.  The btreeComputeFreeSpace() call has already
1776   ** validated the freelist.  Given that the freelist is valid, there
1777   ** is no way that the allocation can extend off the end of the page.
1778   ** The assert() below verifies the previous sentence.
1779   */
1780   top -= nByte;
1781   put2byte(&data[hdr+5], top);
1782   assert( top+nByte <= (int)pPage->pBt->usableSize );
1783   *pIdx = top;
1784   return SQLITE_OK;
1785 }
1786 
1787 /*
1788 ** Return a section of the pPage->aData to the freelist.
1789 ** The first byte of the new free block is pPage->aData[iStart]
1790 ** and the size of the block is iSize bytes.
1791 **
1792 ** Adjacent freeblocks are coalesced.
1793 **
1794 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1795 ** that routine will not detect overlap between cells or freeblocks.  Nor
1796 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1797 ** at the end of the page.  So do additional corruption checks inside this
1798 ** routine and return SQLITE_CORRUPT if any problems are found.
1799 */
1800 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1801   u16 iPtr;                             /* Address of ptr to next freeblock */
1802   u16 iFreeBlk;                         /* Address of the next freeblock */
1803   u8 hdr;                               /* Page header size.  0 or 100 */
1804   u8 nFrag = 0;                         /* Reduction in fragmentation */
1805   u16 iOrigSize = iSize;                /* Original value of iSize */
1806   u16 x;                                /* Offset to cell content area */
1807   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
1808   unsigned char *data = pPage->aData;   /* Page content */
1809   u8 *pTmp;                             /* Temporary ptr into data[] */
1810 
1811   assert( pPage->pBt!=0 );
1812   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1813   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1814   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1815   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1816   assert( iSize>=4 );   /* Minimum cell size is 4 */
1817   assert( iStart<=pPage->pBt->usableSize-4 );
1818 
1819   /* The list of freeblocks must be in ascending order.  Find the
1820   ** spot on the list where iStart should be inserted.
1821   */
1822   hdr = pPage->hdrOffset;
1823   iPtr = hdr + 1;
1824   if( data[iPtr+1]==0 && data[iPtr]==0 ){
1825     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
1826   }else{
1827     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1828       if( iFreeBlk<=iPtr ){
1829         if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1830         return SQLITE_CORRUPT_PAGE(pPage);
1831       }
1832       iPtr = iFreeBlk;
1833     }
1834     if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1835       return SQLITE_CORRUPT_PAGE(pPage);
1836     }
1837     assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
1838 
1839     /* At this point:
1840     **    iFreeBlk:   First freeblock after iStart, or zero if none
1841     **    iPtr:       The address of a pointer to iFreeBlk
1842     **
1843     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1844     */
1845     if( iFreeBlk && iEnd+3>=iFreeBlk ){
1846       nFrag = iFreeBlk - iEnd;
1847       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1848       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1849       if( iEnd > pPage->pBt->usableSize ){
1850         return SQLITE_CORRUPT_PAGE(pPage);
1851       }
1852       iSize = iEnd - iStart;
1853       iFreeBlk = get2byte(&data[iFreeBlk]);
1854     }
1855 
1856     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1857     ** pointer in the page header) then check to see if iStart should be
1858     ** coalesced onto the end of iPtr.
1859     */
1860     if( iPtr>hdr+1 ){
1861       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1862       if( iPtrEnd+3>=iStart ){
1863         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1864         nFrag += iStart - iPtrEnd;
1865         iSize = iEnd - iPtr;
1866         iStart = iPtr;
1867       }
1868     }
1869     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1870     data[hdr+7] -= nFrag;
1871   }
1872   pTmp = &data[hdr+5];
1873   x = get2byte(pTmp);
1874   if( iStart<=x ){
1875     /* The new freeblock is at the beginning of the cell content area,
1876     ** so just extend the cell content area rather than create another
1877     ** freelist entry */
1878     if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1879     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1880     put2byte(&data[hdr+1], iFreeBlk);
1881     put2byte(&data[hdr+5], iEnd);
1882   }else{
1883     /* Insert the new freeblock into the freelist */
1884     put2byte(&data[iPtr], iStart);
1885   }
1886   if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1887     /* Overwrite deleted information with zeros when the secure_delete
1888     ** option is enabled */
1889     memset(&data[iStart], 0, iSize);
1890   }
1891   put2byte(&data[iStart], iFreeBlk);
1892   put2byte(&data[iStart+2], iSize);
1893   pPage->nFree += iOrigSize;
1894   return SQLITE_OK;
1895 }
1896 
1897 /*
1898 ** Decode the flags byte (the first byte of the header) for a page
1899 ** and initialize fields of the MemPage structure accordingly.
1900 **
1901 ** Only the following combinations are supported.  Anything different
1902 ** indicates a corrupt database files:
1903 **
1904 **         PTF_ZERODATA
1905 **         PTF_ZERODATA | PTF_LEAF
1906 **         PTF_LEAFDATA | PTF_INTKEY
1907 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1908 */
1909 static int decodeFlags(MemPage *pPage, int flagByte){
1910   BtShared *pBt;     /* A copy of pPage->pBt */
1911 
1912   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1913   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1914   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
1915   flagByte &= ~PTF_LEAF;
1916   pPage->childPtrSize = 4-4*pPage->leaf;
1917   pBt = pPage->pBt;
1918   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1919     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1920     ** interior table b-tree page. */
1921     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1922     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1923     ** leaf table b-tree page. */
1924     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1925     pPage->intKey = 1;
1926     if( pPage->leaf ){
1927       pPage->intKeyLeaf = 1;
1928       pPage->xCellSize = cellSizePtrTableLeaf;
1929       pPage->xParseCell = btreeParseCellPtr;
1930     }else{
1931       pPage->intKeyLeaf = 0;
1932       pPage->xCellSize = cellSizePtrNoPayload;
1933       pPage->xParseCell = btreeParseCellPtrNoPayload;
1934     }
1935     pPage->maxLocal = pBt->maxLeaf;
1936     pPage->minLocal = pBt->minLeaf;
1937   }else if( flagByte==PTF_ZERODATA ){
1938     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1939     ** interior index b-tree page. */
1940     assert( (PTF_ZERODATA)==2 );
1941     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1942     ** leaf index b-tree page. */
1943     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1944     pPage->intKey = 0;
1945     pPage->intKeyLeaf = 0;
1946     pPage->xCellSize = cellSizePtr;
1947     pPage->xParseCell = btreeParseCellPtrIndex;
1948     pPage->maxLocal = pBt->maxLocal;
1949     pPage->minLocal = pBt->minLocal;
1950   }else{
1951     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1952     ** an error. */
1953     pPage->intKey = 0;
1954     pPage->intKeyLeaf = 0;
1955     pPage->xCellSize = cellSizePtr;
1956     pPage->xParseCell = btreeParseCellPtrIndex;
1957     return SQLITE_CORRUPT_PAGE(pPage);
1958   }
1959   pPage->max1bytePayload = pBt->max1bytePayload;
1960   return SQLITE_OK;
1961 }
1962 
1963 /*
1964 ** Compute the amount of freespace on the page.  In other words, fill
1965 ** in the pPage->nFree field.
1966 */
1967 static int btreeComputeFreeSpace(MemPage *pPage){
1968   int pc;            /* Address of a freeblock within pPage->aData[] */
1969   u8 hdr;            /* Offset to beginning of page header */
1970   u8 *data;          /* Equal to pPage->aData */
1971   int usableSize;    /* Amount of usable space on each page */
1972   int nFree;         /* Number of unused bytes on the page */
1973   int top;           /* First byte of the cell content area */
1974   int iCellFirst;    /* First allowable cell or freeblock offset */
1975   int iCellLast;     /* Last possible cell or freeblock offset */
1976 
1977   assert( pPage->pBt!=0 );
1978   assert( pPage->pBt->db!=0 );
1979   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1980   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1981   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1982   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1983   assert( pPage->isInit==1 );
1984   assert( pPage->nFree<0 );
1985 
1986   usableSize = pPage->pBt->usableSize;
1987   hdr = pPage->hdrOffset;
1988   data = pPage->aData;
1989   /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1990   ** the start of the cell content area. A zero value for this integer is
1991   ** interpreted as 65536. */
1992   top = get2byteNotZero(&data[hdr+5]);
1993   iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1994   iCellLast = usableSize - 4;
1995 
1996   /* Compute the total free space on the page
1997   ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1998   ** start of the first freeblock on the page, or is zero if there are no
1999   ** freeblocks. */
2000   pc = get2byte(&data[hdr+1]);
2001   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
2002   if( pc>0 ){
2003     u32 next, size;
2004     if( pc<top ){
2005       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2006       ** always be at least one cell before the first freeblock.
2007       */
2008       return SQLITE_CORRUPT_PAGE(pPage);
2009     }
2010     while( 1 ){
2011       if( pc>iCellLast ){
2012         /* Freeblock off the end of the page */
2013         return SQLITE_CORRUPT_PAGE(pPage);
2014       }
2015       next = get2byte(&data[pc]);
2016       size = get2byte(&data[pc+2]);
2017       nFree = nFree + size;
2018       if( next<=pc+size+3 ) break;
2019       pc = next;
2020     }
2021     if( next>0 ){
2022       /* Freeblock not in ascending order */
2023       return SQLITE_CORRUPT_PAGE(pPage);
2024     }
2025     if( pc+size>(unsigned int)usableSize ){
2026       /* Last freeblock extends past page end */
2027       return SQLITE_CORRUPT_PAGE(pPage);
2028     }
2029   }
2030 
2031   /* At this point, nFree contains the sum of the offset to the start
2032   ** of the cell-content area plus the number of free bytes within
2033   ** the cell-content area. If this is greater than the usable-size
2034   ** of the page, then the page must be corrupted. This check also
2035   ** serves to verify that the offset to the start of the cell-content
2036   ** area, according to the page header, lies within the page.
2037   */
2038   if( nFree>usableSize || nFree<iCellFirst ){
2039     return SQLITE_CORRUPT_PAGE(pPage);
2040   }
2041   pPage->nFree = (u16)(nFree - iCellFirst);
2042   return SQLITE_OK;
2043 }
2044 
2045 /*
2046 ** Do additional sanity check after btreeInitPage() if
2047 ** PRAGMA cell_size_check=ON
2048 */
2049 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
2050   int iCellFirst;    /* First allowable cell or freeblock offset */
2051   int iCellLast;     /* Last possible cell or freeblock offset */
2052   int i;             /* Index into the cell pointer array */
2053   int sz;            /* Size of a cell */
2054   int pc;            /* Address of a freeblock within pPage->aData[] */
2055   u8 *data;          /* Equal to pPage->aData */
2056   int usableSize;    /* Maximum usable space on the page */
2057   int cellOffset;    /* Start of cell content area */
2058 
2059   iCellFirst = pPage->cellOffset + 2*pPage->nCell;
2060   usableSize = pPage->pBt->usableSize;
2061   iCellLast = usableSize - 4;
2062   data = pPage->aData;
2063   cellOffset = pPage->cellOffset;
2064   if( !pPage->leaf ) iCellLast--;
2065   for(i=0; i<pPage->nCell; i++){
2066     pc = get2byteAligned(&data[cellOffset+i*2]);
2067     testcase( pc==iCellFirst );
2068     testcase( pc==iCellLast );
2069     if( pc<iCellFirst || pc>iCellLast ){
2070       return SQLITE_CORRUPT_PAGE(pPage);
2071     }
2072     sz = pPage->xCellSize(pPage, &data[pc]);
2073     testcase( pc+sz==usableSize );
2074     if( pc+sz>usableSize ){
2075       return SQLITE_CORRUPT_PAGE(pPage);
2076     }
2077   }
2078   return SQLITE_OK;
2079 }
2080 
2081 /*
2082 ** Initialize the auxiliary information for a disk block.
2083 **
2084 ** Return SQLITE_OK on success.  If we see that the page does
2085 ** not contain a well-formed database page, then return
2086 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
2087 ** guarantee that the page is well-formed.  It only shows that
2088 ** we failed to detect any corruption.
2089 */
2090 static int btreeInitPage(MemPage *pPage){
2091   u8 *data;          /* Equal to pPage->aData */
2092   BtShared *pBt;        /* The main btree structure */
2093 
2094   assert( pPage->pBt!=0 );
2095   assert( pPage->pBt->db!=0 );
2096   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2097   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2098   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2099   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2100   assert( pPage->isInit==0 );
2101 
2102   pBt = pPage->pBt;
2103   data = pPage->aData + pPage->hdrOffset;
2104   /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2105   ** the b-tree page type. */
2106   if( decodeFlags(pPage, data[0]) ){
2107     return SQLITE_CORRUPT_PAGE(pPage);
2108   }
2109   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2110   pPage->maskPage = (u16)(pBt->pageSize - 1);
2111   pPage->nOverflow = 0;
2112   pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2113   pPage->aCellIdx = data + pPage->childPtrSize + 8;
2114   pPage->aDataEnd = pPage->aData + pBt->pageSize;
2115   pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2116   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2117   ** number of cells on the page. */
2118   pPage->nCell = get2byte(&data[3]);
2119   if( pPage->nCell>MX_CELL(pBt) ){
2120     /* To many cells for a single page.  The page must be corrupt */
2121     return SQLITE_CORRUPT_PAGE(pPage);
2122   }
2123   testcase( pPage->nCell==MX_CELL(pBt) );
2124   /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2125   ** possible for a root page of a table that contains no rows) then the
2126   ** offset to the cell content area will equal the page size minus the
2127   ** bytes of reserved space. */
2128   assert( pPage->nCell>0
2129        || get2byteNotZero(&data[5])==(int)pBt->usableSize
2130        || CORRUPT_DB );
2131   pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */
2132   pPage->isInit = 1;
2133   if( pBt->db->flags & SQLITE_CellSizeCk ){
2134     return btreeCellSizeCheck(pPage);
2135   }
2136   return SQLITE_OK;
2137 }
2138 
2139 /*
2140 ** Set up a raw page so that it looks like a database page holding
2141 ** no entries.
2142 */
2143 static void zeroPage(MemPage *pPage, int flags){
2144   unsigned char *data = pPage->aData;
2145   BtShared *pBt = pPage->pBt;
2146   u8 hdr = pPage->hdrOffset;
2147   u16 first;
2148 
2149   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
2150   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2151   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2152   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2153   assert( sqlite3_mutex_held(pBt->mutex) );
2154   if( pBt->btsFlags & BTS_FAST_SECURE ){
2155     memset(&data[hdr], 0, pBt->usableSize - hdr);
2156   }
2157   data[hdr] = (char)flags;
2158   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2159   memset(&data[hdr+1], 0, 4);
2160   data[hdr+7] = 0;
2161   put2byte(&data[hdr+5], pBt->usableSize);
2162   pPage->nFree = (u16)(pBt->usableSize - first);
2163   decodeFlags(pPage, flags);
2164   pPage->cellOffset = first;
2165   pPage->aDataEnd = &data[pBt->pageSize];
2166   pPage->aCellIdx = &data[first];
2167   pPage->aDataOfst = &data[pPage->childPtrSize];
2168   pPage->nOverflow = 0;
2169   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2170   pPage->maskPage = (u16)(pBt->pageSize - 1);
2171   pPage->nCell = 0;
2172   pPage->isInit = 1;
2173 }
2174 
2175 
2176 /*
2177 ** Convert a DbPage obtained from the pager into a MemPage used by
2178 ** the btree layer.
2179 */
2180 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2181   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2182   if( pgno!=pPage->pgno ){
2183     pPage->aData = sqlite3PagerGetData(pDbPage);
2184     pPage->pDbPage = pDbPage;
2185     pPage->pBt = pBt;
2186     pPage->pgno = pgno;
2187     pPage->hdrOffset = pgno==1 ? 100 : 0;
2188   }
2189   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2190   return pPage;
2191 }
2192 
2193 /*
2194 ** Get a page from the pager.  Initialize the MemPage.pBt and
2195 ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
2196 **
2197 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2198 ** about the content of the page at this time.  So do not go to the disk
2199 ** to fetch the content.  Just fill in the content with zeros for now.
2200 ** If in the future we call sqlite3PagerWrite() on this page, that
2201 ** means we have started to be concerned about content and the disk
2202 ** read should occur at that point.
2203 */
2204 static int btreeGetPage(
2205   BtShared *pBt,       /* The btree */
2206   Pgno pgno,           /* Number of the page to fetch */
2207   MemPage **ppPage,    /* Return the page in this parameter */
2208   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2209 ){
2210   int rc;
2211   DbPage *pDbPage;
2212 
2213   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2214   assert( sqlite3_mutex_held(pBt->mutex) );
2215   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2216   if( rc ) return rc;
2217   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2218   return SQLITE_OK;
2219 }
2220 
2221 /*
2222 ** Retrieve a page from the pager cache. If the requested page is not
2223 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2224 ** MemPage.aData elements if needed.
2225 */
2226 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2227   DbPage *pDbPage;
2228   assert( sqlite3_mutex_held(pBt->mutex) );
2229   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2230   if( pDbPage ){
2231     return btreePageFromDbPage(pDbPage, pgno, pBt);
2232   }
2233   return 0;
2234 }
2235 
2236 /*
2237 ** Return the size of the database file in pages. If there is any kind of
2238 ** error, return ((unsigned int)-1).
2239 */
2240 static Pgno btreePagecount(BtShared *pBt){
2241   return pBt->nPage;
2242 }
2243 Pgno sqlite3BtreeLastPage(Btree *p){
2244   assert( sqlite3BtreeHoldsMutex(p) );
2245   return btreePagecount(p->pBt);
2246 }
2247 
2248 /*
2249 ** Get a page from the pager and initialize it.
2250 **
2251 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2252 ** call.  Do additional sanity checking on the page in this case.
2253 ** And if the fetch fails, this routine must decrement pCur->iPage.
2254 **
2255 ** The page is fetched as read-write unless pCur is not NULL and is
2256 ** a read-only cursor.
2257 **
2258 ** If an error occurs, then *ppPage is undefined. It
2259 ** may remain unchanged, or it may be set to an invalid value.
2260 */
2261 static int getAndInitPage(
2262   BtShared *pBt,                  /* The database file */
2263   Pgno pgno,                      /* Number of the page to get */
2264   MemPage **ppPage,               /* Write the page pointer here */
2265   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
2266   int bReadOnly                   /* True for a read-only page */
2267 ){
2268   int rc;
2269   DbPage *pDbPage;
2270   assert( sqlite3_mutex_held(pBt->mutex) );
2271   assert( pCur==0 || ppPage==&pCur->pPage );
2272   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2273   assert( pCur==0 || pCur->iPage>0 );
2274 
2275   if( pgno>btreePagecount(pBt) ){
2276     rc = SQLITE_CORRUPT_BKPT;
2277     goto getAndInitPage_error1;
2278   }
2279   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2280   if( rc ){
2281     goto getAndInitPage_error1;
2282   }
2283   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2284   if( (*ppPage)->isInit==0 ){
2285     btreePageFromDbPage(pDbPage, pgno, pBt);
2286     rc = btreeInitPage(*ppPage);
2287     if( rc!=SQLITE_OK ){
2288       goto getAndInitPage_error2;
2289     }
2290   }
2291   assert( (*ppPage)->pgno==pgno || CORRUPT_DB );
2292   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2293 
2294   /* If obtaining a child page for a cursor, we must verify that the page is
2295   ** compatible with the root page. */
2296   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2297     rc = SQLITE_CORRUPT_PGNO(pgno);
2298     goto getAndInitPage_error2;
2299   }
2300   return SQLITE_OK;
2301 
2302 getAndInitPage_error2:
2303   releasePage(*ppPage);
2304 getAndInitPage_error1:
2305   if( pCur ){
2306     pCur->iPage--;
2307     pCur->pPage = pCur->apPage[pCur->iPage];
2308   }
2309   testcase( pgno==0 );
2310   assert( pgno!=0 || rc!=SQLITE_OK );
2311   return rc;
2312 }
2313 
2314 /*
2315 ** Release a MemPage.  This should be called once for each prior
2316 ** call to btreeGetPage.
2317 **
2318 ** Page1 is a special case and must be released using releasePageOne().
2319 */
2320 static void releasePageNotNull(MemPage *pPage){
2321   assert( pPage->aData );
2322   assert( pPage->pBt );
2323   assert( pPage->pDbPage!=0 );
2324   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2325   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2326   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2327   sqlite3PagerUnrefNotNull(pPage->pDbPage);
2328 }
2329 static void releasePage(MemPage *pPage){
2330   if( pPage ) releasePageNotNull(pPage);
2331 }
2332 static void releasePageOne(MemPage *pPage){
2333   assert( pPage!=0 );
2334   assert( pPage->aData );
2335   assert( pPage->pBt );
2336   assert( pPage->pDbPage!=0 );
2337   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2338   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2339   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2340   sqlite3PagerUnrefPageOne(pPage->pDbPage);
2341 }
2342 
2343 /*
2344 ** Get an unused page.
2345 **
2346 ** This works just like btreeGetPage() with the addition:
2347 **
2348 **   *  If the page is already in use for some other purpose, immediately
2349 **      release it and return an SQLITE_CURRUPT error.
2350 **   *  Make sure the isInit flag is clear
2351 */
2352 static int btreeGetUnusedPage(
2353   BtShared *pBt,       /* The btree */
2354   Pgno pgno,           /* Number of the page to fetch */
2355   MemPage **ppPage,    /* Return the page in this parameter */
2356   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2357 ){
2358   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2359   if( rc==SQLITE_OK ){
2360     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2361       releasePage(*ppPage);
2362       *ppPage = 0;
2363       return SQLITE_CORRUPT_BKPT;
2364     }
2365     (*ppPage)->isInit = 0;
2366   }else{
2367     *ppPage = 0;
2368   }
2369   return rc;
2370 }
2371 
2372 
2373 /*
2374 ** During a rollback, when the pager reloads information into the cache
2375 ** so that the cache is restored to its original state at the start of
2376 ** the transaction, for each page restored this routine is called.
2377 **
2378 ** This routine needs to reset the extra data section at the end of the
2379 ** page to agree with the restored data.
2380 */
2381 static void pageReinit(DbPage *pData){
2382   MemPage *pPage;
2383   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2384   assert( sqlite3PagerPageRefcount(pData)>0 );
2385   if( pPage->isInit ){
2386     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2387     pPage->isInit = 0;
2388     if( sqlite3PagerPageRefcount(pData)>1 ){
2389       /* pPage might not be a btree page;  it might be an overflow page
2390       ** or ptrmap page or a free page.  In those cases, the following
2391       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2392       ** But no harm is done by this.  And it is very important that
2393       ** btreeInitPage() be called on every btree page so we make
2394       ** the call for every page that comes in for re-initing. */
2395       btreeInitPage(pPage);
2396     }
2397   }
2398 }
2399 
2400 /*
2401 ** Invoke the busy handler for a btree.
2402 */
2403 static int btreeInvokeBusyHandler(void *pArg){
2404   BtShared *pBt = (BtShared*)pArg;
2405   assert( pBt->db );
2406   assert( sqlite3_mutex_held(pBt->db->mutex) );
2407   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2408 }
2409 
2410 /*
2411 ** Open a database file.
2412 **
2413 ** zFilename is the name of the database file.  If zFilename is NULL
2414 ** then an ephemeral database is created.  The ephemeral database might
2415 ** be exclusively in memory, or it might use a disk-based memory cache.
2416 ** Either way, the ephemeral database will be automatically deleted
2417 ** when sqlite3BtreeClose() is called.
2418 **
2419 ** If zFilename is ":memory:" then an in-memory database is created
2420 ** that is automatically destroyed when it is closed.
2421 **
2422 ** The "flags" parameter is a bitmask that might contain bits like
2423 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2424 **
2425 ** If the database is already opened in the same database connection
2426 ** and we are in shared cache mode, then the open will fail with an
2427 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
2428 ** objects in the same database connection since doing so will lead
2429 ** to problems with locking.
2430 */
2431 int sqlite3BtreeOpen(
2432   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
2433   const char *zFilename,  /* Name of the file containing the BTree database */
2434   sqlite3 *db,            /* Associated database handle */
2435   Btree **ppBtree,        /* Pointer to new Btree object written here */
2436   int flags,              /* Options */
2437   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
2438 ){
2439   BtShared *pBt = 0;             /* Shared part of btree structure */
2440   Btree *p;                      /* Handle to return */
2441   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
2442   int rc = SQLITE_OK;            /* Result code from this function */
2443   u8 nReserve;                   /* Byte of unused space on each page */
2444   unsigned char zDbHeader[100];  /* Database header content */
2445 
2446   /* True if opening an ephemeral, temporary database */
2447   const int isTempDb = zFilename==0 || zFilename[0]==0;
2448 
2449   /* Set the variable isMemdb to true for an in-memory database, or
2450   ** false for a file-based database.
2451   */
2452 #ifdef SQLITE_OMIT_MEMORYDB
2453   const int isMemdb = 0;
2454 #else
2455   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2456                        || (isTempDb && sqlite3TempInMemory(db))
2457                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2458 #endif
2459 
2460   assert( db!=0 );
2461   assert( pVfs!=0 );
2462   assert( sqlite3_mutex_held(db->mutex) );
2463   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
2464 
2465   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2466   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2467 
2468   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2469   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2470 
2471   if( isMemdb ){
2472     flags |= BTREE_MEMORY;
2473   }
2474   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2475     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2476   }
2477   p = sqlite3MallocZero(sizeof(Btree));
2478   if( !p ){
2479     return SQLITE_NOMEM_BKPT;
2480   }
2481   p->inTrans = TRANS_NONE;
2482   p->db = db;
2483 #ifndef SQLITE_OMIT_SHARED_CACHE
2484   p->lock.pBtree = p;
2485   p->lock.iTable = 1;
2486 #endif
2487 
2488 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2489   /*
2490   ** If this Btree is a candidate for shared cache, try to find an
2491   ** existing BtShared object that we can share with
2492   */
2493   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2494     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2495       int nFilename = sqlite3Strlen30(zFilename)+1;
2496       int nFullPathname = pVfs->mxPathname+1;
2497       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2498       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2499 
2500       p->sharable = 1;
2501       if( !zFullPathname ){
2502         sqlite3_free(p);
2503         return SQLITE_NOMEM_BKPT;
2504       }
2505       if( isMemdb ){
2506         memcpy(zFullPathname, zFilename, nFilename);
2507       }else{
2508         rc = sqlite3OsFullPathname(pVfs, zFilename,
2509                                    nFullPathname, zFullPathname);
2510         if( rc ){
2511           if( rc==SQLITE_OK_SYMLINK ){
2512             rc = SQLITE_OK;
2513           }else{
2514             sqlite3_free(zFullPathname);
2515             sqlite3_free(p);
2516             return rc;
2517           }
2518         }
2519       }
2520 #if SQLITE_THREADSAFE
2521       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2522       sqlite3_mutex_enter(mutexOpen);
2523       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2524       sqlite3_mutex_enter(mutexShared);
2525 #endif
2526       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2527         assert( pBt->nRef>0 );
2528         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2529                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2530           int iDb;
2531           for(iDb=db->nDb-1; iDb>=0; iDb--){
2532             Btree *pExisting = db->aDb[iDb].pBt;
2533             if( pExisting && pExisting->pBt==pBt ){
2534               sqlite3_mutex_leave(mutexShared);
2535               sqlite3_mutex_leave(mutexOpen);
2536               sqlite3_free(zFullPathname);
2537               sqlite3_free(p);
2538               return SQLITE_CONSTRAINT;
2539             }
2540           }
2541           p->pBt = pBt;
2542           pBt->nRef++;
2543           break;
2544         }
2545       }
2546       sqlite3_mutex_leave(mutexShared);
2547       sqlite3_free(zFullPathname);
2548     }
2549 #ifdef SQLITE_DEBUG
2550     else{
2551       /* In debug mode, we mark all persistent databases as sharable
2552       ** even when they are not.  This exercises the locking code and
2553       ** gives more opportunity for asserts(sqlite3_mutex_held())
2554       ** statements to find locking problems.
2555       */
2556       p->sharable = 1;
2557     }
2558 #endif
2559   }
2560 #endif
2561   if( pBt==0 ){
2562     /*
2563     ** The following asserts make sure that structures used by the btree are
2564     ** the right size.  This is to guard against size changes that result
2565     ** when compiling on a different architecture.
2566     */
2567     assert( sizeof(i64)==8 );
2568     assert( sizeof(u64)==8 );
2569     assert( sizeof(u32)==4 );
2570     assert( sizeof(u16)==2 );
2571     assert( sizeof(Pgno)==4 );
2572 
2573     pBt = sqlite3MallocZero( sizeof(*pBt) );
2574     if( pBt==0 ){
2575       rc = SQLITE_NOMEM_BKPT;
2576       goto btree_open_out;
2577     }
2578     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2579                           sizeof(MemPage), flags, vfsFlags, pageReinit);
2580     if( rc==SQLITE_OK ){
2581       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2582       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2583     }
2584     if( rc!=SQLITE_OK ){
2585       goto btree_open_out;
2586     }
2587     pBt->openFlags = (u8)flags;
2588     pBt->db = db;
2589     sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2590     p->pBt = pBt;
2591 
2592     pBt->pCursor = 0;
2593     pBt->pPage1 = 0;
2594     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2595 #if defined(SQLITE_SECURE_DELETE)
2596     pBt->btsFlags |= BTS_SECURE_DELETE;
2597 #elif defined(SQLITE_FAST_SECURE_DELETE)
2598     pBt->btsFlags |= BTS_OVERWRITE;
2599 #endif
2600     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2601     ** determined by the 2-byte integer located at an offset of 16 bytes from
2602     ** the beginning of the database file. */
2603     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2604     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2605          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2606       pBt->pageSize = 0;
2607 #ifndef SQLITE_OMIT_AUTOVACUUM
2608       /* If the magic name ":memory:" will create an in-memory database, then
2609       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2610       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2611       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2612       ** regular file-name. In this case the auto-vacuum applies as per normal.
2613       */
2614       if( zFilename && !isMemdb ){
2615         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2616         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2617       }
2618 #endif
2619       nReserve = 0;
2620     }else{
2621       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2622       ** determined by the one-byte unsigned integer found at an offset of 20
2623       ** into the database file header. */
2624       nReserve = zDbHeader[20];
2625       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2626 #ifndef SQLITE_OMIT_AUTOVACUUM
2627       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2628       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2629 #endif
2630     }
2631     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2632     if( rc ) goto btree_open_out;
2633     pBt->usableSize = pBt->pageSize - nReserve;
2634     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
2635 
2636 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2637     /* Add the new BtShared object to the linked list sharable BtShareds.
2638     */
2639     pBt->nRef = 1;
2640     if( p->sharable ){
2641       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2642       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2643       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2644         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2645         if( pBt->mutex==0 ){
2646           rc = SQLITE_NOMEM_BKPT;
2647           goto btree_open_out;
2648         }
2649       }
2650       sqlite3_mutex_enter(mutexShared);
2651       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2652       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2653       sqlite3_mutex_leave(mutexShared);
2654     }
2655 #endif
2656   }
2657 
2658 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2659   /* If the new Btree uses a sharable pBtShared, then link the new
2660   ** Btree into the list of all sharable Btrees for the same connection.
2661   ** The list is kept in ascending order by pBt address.
2662   */
2663   if( p->sharable ){
2664     int i;
2665     Btree *pSib;
2666     for(i=0; i<db->nDb; i++){
2667       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2668         while( pSib->pPrev ){ pSib = pSib->pPrev; }
2669         if( (uptr)p->pBt<(uptr)pSib->pBt ){
2670           p->pNext = pSib;
2671           p->pPrev = 0;
2672           pSib->pPrev = p;
2673         }else{
2674           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2675             pSib = pSib->pNext;
2676           }
2677           p->pNext = pSib->pNext;
2678           p->pPrev = pSib;
2679           if( p->pNext ){
2680             p->pNext->pPrev = p;
2681           }
2682           pSib->pNext = p;
2683         }
2684         break;
2685       }
2686     }
2687   }
2688 #endif
2689   *ppBtree = p;
2690 
2691 btree_open_out:
2692   if( rc!=SQLITE_OK ){
2693     if( pBt && pBt->pPager ){
2694       sqlite3PagerClose(pBt->pPager, 0);
2695     }
2696     sqlite3_free(pBt);
2697     sqlite3_free(p);
2698     *ppBtree = 0;
2699   }else{
2700     sqlite3_file *pFile;
2701 
2702     /* If the B-Tree was successfully opened, set the pager-cache size to the
2703     ** default value. Except, when opening on an existing shared pager-cache,
2704     ** do not change the pager-cache size.
2705     */
2706     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2707       sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2708     }
2709 
2710     pFile = sqlite3PagerFile(pBt->pPager);
2711     if( pFile->pMethods ){
2712       sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2713     }
2714   }
2715   if( mutexOpen ){
2716     assert( sqlite3_mutex_held(mutexOpen) );
2717     sqlite3_mutex_leave(mutexOpen);
2718   }
2719   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2720   return rc;
2721 }
2722 
2723 /*
2724 ** Decrement the BtShared.nRef counter.  When it reaches zero,
2725 ** remove the BtShared structure from the sharing list.  Return
2726 ** true if the BtShared.nRef counter reaches zero and return
2727 ** false if it is still positive.
2728 */
2729 static int removeFromSharingList(BtShared *pBt){
2730 #ifndef SQLITE_OMIT_SHARED_CACHE
2731   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2732   BtShared *pList;
2733   int removed = 0;
2734 
2735   assert( sqlite3_mutex_notheld(pBt->mutex) );
2736   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2737   sqlite3_mutex_enter(pMainMtx);
2738   pBt->nRef--;
2739   if( pBt->nRef<=0 ){
2740     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2741       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2742     }else{
2743       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2744       while( ALWAYS(pList) && pList->pNext!=pBt ){
2745         pList=pList->pNext;
2746       }
2747       if( ALWAYS(pList) ){
2748         pList->pNext = pBt->pNext;
2749       }
2750     }
2751     if( SQLITE_THREADSAFE ){
2752       sqlite3_mutex_free(pBt->mutex);
2753     }
2754     removed = 1;
2755   }
2756   sqlite3_mutex_leave(pMainMtx);
2757   return removed;
2758 #else
2759   return 1;
2760 #endif
2761 }
2762 
2763 /*
2764 ** Make sure pBt->pTmpSpace points to an allocation of
2765 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2766 ** pointer.
2767 */
2768 static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
2769   assert( pBt!=0 );
2770   assert( pBt->pTmpSpace==0 );
2771   /* This routine is called only by btreeCursor() when allocating the
2772   ** first write cursor for the BtShared object */
2773   assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
2774   pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2775   if( pBt->pTmpSpace==0 ){
2776     BtCursor *pCur = pBt->pCursor;
2777     pBt->pCursor = pCur->pNext;  /* Unlink the cursor */
2778     memset(pCur, 0, sizeof(*pCur));
2779     return SQLITE_NOMEM_BKPT;
2780   }
2781 
2782   /* One of the uses of pBt->pTmpSpace is to format cells before
2783   ** inserting them into a leaf page (function fillInCell()). If
2784   ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2785   ** by the various routines that manipulate binary cells. Which
2786   ** can mean that fillInCell() only initializes the first 2 or 3
2787   ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2788   ** it into a database page. This is not actually a problem, but it
2789   ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2790   ** data is passed to system call write(). So to avoid this error,
2791   ** zero the first 4 bytes of temp space here.
2792   **
2793   ** Also:  Provide four bytes of initialized space before the
2794   ** beginning of pTmpSpace as an area available to prepend the
2795   ** left-child pointer to the beginning of a cell.
2796   */
2797   memset(pBt->pTmpSpace, 0, 8);
2798   pBt->pTmpSpace += 4;
2799   return SQLITE_OK;
2800 }
2801 
2802 /*
2803 ** Free the pBt->pTmpSpace allocation
2804 */
2805 static void freeTempSpace(BtShared *pBt){
2806   if( pBt->pTmpSpace ){
2807     pBt->pTmpSpace -= 4;
2808     sqlite3PageFree(pBt->pTmpSpace);
2809     pBt->pTmpSpace = 0;
2810   }
2811 }
2812 
2813 /*
2814 ** Close an open database and invalidate all cursors.
2815 */
2816 int sqlite3BtreeClose(Btree *p){
2817   BtShared *pBt = p->pBt;
2818 
2819   /* Close all cursors opened via this handle.  */
2820   assert( sqlite3_mutex_held(p->db->mutex) );
2821   sqlite3BtreeEnter(p);
2822 
2823   /* Verify that no other cursors have this Btree open */
2824 #ifdef SQLITE_DEBUG
2825   {
2826     BtCursor *pCur = pBt->pCursor;
2827     while( pCur ){
2828       BtCursor *pTmp = pCur;
2829       pCur = pCur->pNext;
2830       assert( pTmp->pBtree!=p );
2831 
2832     }
2833   }
2834 #endif
2835 
2836   /* Rollback any active transaction and free the handle structure.
2837   ** The call to sqlite3BtreeRollback() drops any table-locks held by
2838   ** this handle.
2839   */
2840   sqlite3BtreeRollback(p, SQLITE_OK, 0);
2841   sqlite3BtreeLeave(p);
2842 
2843   /* If there are still other outstanding references to the shared-btree
2844   ** structure, return now. The remainder of this procedure cleans
2845   ** up the shared-btree.
2846   */
2847   assert( p->wantToLock==0 && p->locked==0 );
2848   if( !p->sharable || removeFromSharingList(pBt) ){
2849     /* The pBt is no longer on the sharing list, so we can access
2850     ** it without having to hold the mutex.
2851     **
2852     ** Clean out and delete the BtShared object.
2853     */
2854     assert( !pBt->pCursor );
2855     sqlite3PagerClose(pBt->pPager, p->db);
2856     if( pBt->xFreeSchema && pBt->pSchema ){
2857       pBt->xFreeSchema(pBt->pSchema);
2858     }
2859     sqlite3DbFree(0, pBt->pSchema);
2860     freeTempSpace(pBt);
2861     sqlite3_free(pBt);
2862   }
2863 
2864 #ifndef SQLITE_OMIT_SHARED_CACHE
2865   assert( p->wantToLock==0 );
2866   assert( p->locked==0 );
2867   if( p->pPrev ) p->pPrev->pNext = p->pNext;
2868   if( p->pNext ) p->pNext->pPrev = p->pPrev;
2869 #endif
2870 
2871   sqlite3_free(p);
2872   return SQLITE_OK;
2873 }
2874 
2875 /*
2876 ** Change the "soft" limit on the number of pages in the cache.
2877 ** Unused and unmodified pages will be recycled when the number of
2878 ** pages in the cache exceeds this soft limit.  But the size of the
2879 ** cache is allowed to grow larger than this limit if it contains
2880 ** dirty pages or pages still in active use.
2881 */
2882 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2883   BtShared *pBt = p->pBt;
2884   assert( sqlite3_mutex_held(p->db->mutex) );
2885   sqlite3BtreeEnter(p);
2886   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2887   sqlite3BtreeLeave(p);
2888   return SQLITE_OK;
2889 }
2890 
2891 /*
2892 ** Change the "spill" limit on the number of pages in the cache.
2893 ** If the number of pages exceeds this limit during a write transaction,
2894 ** the pager might attempt to "spill" pages to the journal early in
2895 ** order to free up memory.
2896 **
2897 ** The value returned is the current spill size.  If zero is passed
2898 ** as an argument, no changes are made to the spill size setting, so
2899 ** using mxPage of 0 is a way to query the current spill size.
2900 */
2901 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2902   BtShared *pBt = p->pBt;
2903   int res;
2904   assert( sqlite3_mutex_held(p->db->mutex) );
2905   sqlite3BtreeEnter(p);
2906   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2907   sqlite3BtreeLeave(p);
2908   return res;
2909 }
2910 
2911 #if SQLITE_MAX_MMAP_SIZE>0
2912 /*
2913 ** Change the limit on the amount of the database file that may be
2914 ** memory mapped.
2915 */
2916 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2917   BtShared *pBt = p->pBt;
2918   assert( sqlite3_mutex_held(p->db->mutex) );
2919   sqlite3BtreeEnter(p);
2920   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2921   sqlite3BtreeLeave(p);
2922   return SQLITE_OK;
2923 }
2924 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2925 
2926 /*
2927 ** Change the way data is synced to disk in order to increase or decrease
2928 ** how well the database resists damage due to OS crashes and power
2929 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
2930 ** there is a high probability of damage)  Level 2 is the default.  There
2931 ** is a very low but non-zero probability of damage.  Level 3 reduces the
2932 ** probability of damage to near zero but with a write performance reduction.
2933 */
2934 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2935 int sqlite3BtreeSetPagerFlags(
2936   Btree *p,              /* The btree to set the safety level on */
2937   unsigned pgFlags       /* Various PAGER_* flags */
2938 ){
2939   BtShared *pBt = p->pBt;
2940   assert( sqlite3_mutex_held(p->db->mutex) );
2941   sqlite3BtreeEnter(p);
2942   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2943   sqlite3BtreeLeave(p);
2944   return SQLITE_OK;
2945 }
2946 #endif
2947 
2948 /*
2949 ** Change the default pages size and the number of reserved bytes per page.
2950 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2951 ** without changing anything.
2952 **
2953 ** The page size must be a power of 2 between 512 and 65536.  If the page
2954 ** size supplied does not meet this constraint then the page size is not
2955 ** changed.
2956 **
2957 ** Page sizes are constrained to be a power of two so that the region
2958 ** of the database file used for locking (beginning at PENDING_BYTE,
2959 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2960 ** at the beginning of a page.
2961 **
2962 ** If parameter nReserve is less than zero, then the number of reserved
2963 ** bytes per page is left unchanged.
2964 **
2965 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2966 ** and autovacuum mode can no longer be changed.
2967 */
2968 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2969   int rc = SQLITE_OK;
2970   int x;
2971   BtShared *pBt = p->pBt;
2972   assert( nReserve>=0 && nReserve<=255 );
2973   sqlite3BtreeEnter(p);
2974   pBt->nReserveWanted = nReserve;
2975   x = pBt->pageSize - pBt->usableSize;
2976   if( nReserve<x ) nReserve = x;
2977   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2978     sqlite3BtreeLeave(p);
2979     return SQLITE_READONLY;
2980   }
2981   assert( nReserve>=0 && nReserve<=255 );
2982   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2983         ((pageSize-1)&pageSize)==0 ){
2984     assert( (pageSize & 7)==0 );
2985     assert( !pBt->pCursor );
2986     if( nReserve>32 && pageSize==512 ) pageSize = 1024;
2987     pBt->pageSize = (u32)pageSize;
2988     freeTempSpace(pBt);
2989   }
2990   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2991   pBt->usableSize = pBt->pageSize - (u16)nReserve;
2992   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2993   sqlite3BtreeLeave(p);
2994   return rc;
2995 }
2996 
2997 /*
2998 ** Return the currently defined page size
2999 */
3000 int sqlite3BtreeGetPageSize(Btree *p){
3001   return p->pBt->pageSize;
3002 }
3003 
3004 /*
3005 ** This function is similar to sqlite3BtreeGetReserve(), except that it
3006 ** may only be called if it is guaranteed that the b-tree mutex is already
3007 ** held.
3008 **
3009 ** This is useful in one special case in the backup API code where it is
3010 ** known that the shared b-tree mutex is held, but the mutex on the
3011 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3012 ** were to be called, it might collide with some other operation on the
3013 ** database handle that owns *p, causing undefined behavior.
3014 */
3015 int sqlite3BtreeGetReserveNoMutex(Btree *p){
3016   int n;
3017   assert( sqlite3_mutex_held(p->pBt->mutex) );
3018   n = p->pBt->pageSize - p->pBt->usableSize;
3019   return n;
3020 }
3021 
3022 /*
3023 ** Return the number of bytes of space at the end of every page that
3024 ** are intentually left unused.  This is the "reserved" space that is
3025 ** sometimes used by extensions.
3026 **
3027 ** The value returned is the larger of the current reserve size and
3028 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3029 ** The amount of reserve can only grow - never shrink.
3030 */
3031 int sqlite3BtreeGetRequestedReserve(Btree *p){
3032   int n1, n2;
3033   sqlite3BtreeEnter(p);
3034   n1 = (int)p->pBt->nReserveWanted;
3035   n2 = sqlite3BtreeGetReserveNoMutex(p);
3036   sqlite3BtreeLeave(p);
3037   return n1>n2 ? n1 : n2;
3038 }
3039 
3040 
3041 /*
3042 ** Set the maximum page count for a database if mxPage is positive.
3043 ** No changes are made if mxPage is 0 or negative.
3044 ** Regardless of the value of mxPage, return the maximum page count.
3045 */
3046 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3047   Pgno n;
3048   sqlite3BtreeEnter(p);
3049   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3050   sqlite3BtreeLeave(p);
3051   return n;
3052 }
3053 
3054 /*
3055 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3056 **
3057 **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3058 **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3059 **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3060 **    newFlag==(-1)    No changes
3061 **
3062 ** This routine acts as a query if newFlag is less than zero
3063 **
3064 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3065 ** freelist leaf pages are not written back to the database.  Thus in-page
3066 ** deleted content is cleared, but freelist deleted content is not.
3067 **
3068 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3069 ** that freelist leaf pages are written back into the database, increasing
3070 ** the amount of disk I/O.
3071 */
3072 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3073   int b;
3074   if( p==0 ) return 0;
3075   sqlite3BtreeEnter(p);
3076   assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3077   assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3078   if( newFlag>=0 ){
3079     p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3080     p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3081   }
3082   b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3083   sqlite3BtreeLeave(p);
3084   return b;
3085 }
3086 
3087 /*
3088 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3089 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3090 ** is disabled. The default value for the auto-vacuum property is
3091 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3092 */
3093 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3094 #ifdef SQLITE_OMIT_AUTOVACUUM
3095   return SQLITE_READONLY;
3096 #else
3097   BtShared *pBt = p->pBt;
3098   int rc = SQLITE_OK;
3099   u8 av = (u8)autoVacuum;
3100 
3101   sqlite3BtreeEnter(p);
3102   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3103     rc = SQLITE_READONLY;
3104   }else{
3105     pBt->autoVacuum = av ?1:0;
3106     pBt->incrVacuum = av==2 ?1:0;
3107   }
3108   sqlite3BtreeLeave(p);
3109   return rc;
3110 #endif
3111 }
3112 
3113 /*
3114 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3115 ** enabled 1 is returned. Otherwise 0.
3116 */
3117 int sqlite3BtreeGetAutoVacuum(Btree *p){
3118 #ifdef SQLITE_OMIT_AUTOVACUUM
3119   return BTREE_AUTOVACUUM_NONE;
3120 #else
3121   int rc;
3122   sqlite3BtreeEnter(p);
3123   rc = (
3124     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3125     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3126     BTREE_AUTOVACUUM_INCR
3127   );
3128   sqlite3BtreeLeave(p);
3129   return rc;
3130 #endif
3131 }
3132 
3133 /*
3134 ** If the user has not set the safety-level for this database connection
3135 ** using "PRAGMA synchronous", and if the safety-level is not already
3136 ** set to the value passed to this function as the second parameter,
3137 ** set it so.
3138 */
3139 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3140     && !defined(SQLITE_OMIT_WAL)
3141 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3142   sqlite3 *db;
3143   Db *pDb;
3144   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3145     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3146     if( pDb->bSyncSet==0
3147      && pDb->safety_level!=safety_level
3148      && pDb!=&db->aDb[1]
3149     ){
3150       pDb->safety_level = safety_level;
3151       sqlite3PagerSetFlags(pBt->pPager,
3152           pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3153     }
3154   }
3155 }
3156 #else
3157 # define setDefaultSyncFlag(pBt,safety_level)
3158 #endif
3159 
3160 /* Forward declaration */
3161 static int newDatabase(BtShared*);
3162 
3163 
3164 /*
3165 ** Get a reference to pPage1 of the database file.  This will
3166 ** also acquire a readlock on that file.
3167 **
3168 ** SQLITE_OK is returned on success.  If the file is not a
3169 ** well-formed database file, then SQLITE_CORRUPT is returned.
3170 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
3171 ** is returned if we run out of memory.
3172 */
3173 static int lockBtree(BtShared *pBt){
3174   int rc;              /* Result code from subfunctions */
3175   MemPage *pPage1;     /* Page 1 of the database file */
3176   u32 nPage;           /* Number of pages in the database */
3177   u32 nPageFile = 0;   /* Number of pages in the database file */
3178 
3179   assert( sqlite3_mutex_held(pBt->mutex) );
3180   assert( pBt->pPage1==0 );
3181   rc = sqlite3PagerSharedLock(pBt->pPager);
3182   if( rc!=SQLITE_OK ) return rc;
3183   rc = btreeGetPage(pBt, 1, &pPage1, 0);
3184   if( rc!=SQLITE_OK ) return rc;
3185 
3186   /* Do some checking to help insure the file we opened really is
3187   ** a valid database file.
3188   */
3189   nPage = get4byte(28+(u8*)pPage1->aData);
3190   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3191   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3192     nPage = nPageFile;
3193   }
3194   if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3195     nPage = 0;
3196   }
3197   if( nPage>0 ){
3198     u32 pageSize;
3199     u32 usableSize;
3200     u8 *page1 = pPage1->aData;
3201     rc = SQLITE_NOTADB;
3202     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3203     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3204     ** 61 74 20 33 00. */
3205     if( memcmp(page1, zMagicHeader, 16)!=0 ){
3206       goto page1_init_failed;
3207     }
3208 
3209 #ifdef SQLITE_OMIT_WAL
3210     if( page1[18]>1 ){
3211       pBt->btsFlags |= BTS_READ_ONLY;
3212     }
3213     if( page1[19]>1 ){
3214       goto page1_init_failed;
3215     }
3216 #else
3217     if( page1[18]>2 ){
3218       pBt->btsFlags |= BTS_READ_ONLY;
3219     }
3220     if( page1[19]>2 ){
3221       goto page1_init_failed;
3222     }
3223 
3224     /* If the read version is set to 2, this database should be accessed
3225     ** in WAL mode. If the log is not already open, open it now. Then
3226     ** return SQLITE_OK and return without populating BtShared.pPage1.
3227     ** The caller detects this and calls this function again. This is
3228     ** required as the version of page 1 currently in the page1 buffer
3229     ** may not be the latest version - there may be a newer one in the log
3230     ** file.
3231     */
3232     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3233       int isOpen = 0;
3234       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3235       if( rc!=SQLITE_OK ){
3236         goto page1_init_failed;
3237       }else{
3238         setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3239         if( isOpen==0 ){
3240           releasePageOne(pPage1);
3241           return SQLITE_OK;
3242         }
3243       }
3244       rc = SQLITE_NOTADB;
3245     }else{
3246       setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3247     }
3248 #endif
3249 
3250     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3251     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3252     **
3253     ** The original design allowed these amounts to vary, but as of
3254     ** version 3.6.0, we require them to be fixed.
3255     */
3256     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3257       goto page1_init_failed;
3258     }
3259     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3260     ** determined by the 2-byte integer located at an offset of 16 bytes from
3261     ** the beginning of the database file. */
3262     pageSize = (page1[16]<<8) | (page1[17]<<16);
3263     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3264     ** between 512 and 65536 inclusive. */
3265     if( ((pageSize-1)&pageSize)!=0
3266      || pageSize>SQLITE_MAX_PAGE_SIZE
3267      || pageSize<=256
3268     ){
3269       goto page1_init_failed;
3270     }
3271     pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3272     assert( (pageSize & 7)==0 );
3273     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3274     ** integer at offset 20 is the number of bytes of space at the end of
3275     ** each page to reserve for extensions.
3276     **
3277     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3278     ** determined by the one-byte unsigned integer found at an offset of 20
3279     ** into the database file header. */
3280     usableSize = pageSize - page1[20];
3281     if( (u32)pageSize!=pBt->pageSize ){
3282       /* After reading the first page of the database assuming a page size
3283       ** of BtShared.pageSize, we have discovered that the page-size is
3284       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3285       ** zero and return SQLITE_OK. The caller will call this function
3286       ** again with the correct page-size.
3287       */
3288       releasePageOne(pPage1);
3289       pBt->usableSize = usableSize;
3290       pBt->pageSize = pageSize;
3291       freeTempSpace(pBt);
3292       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3293                                    pageSize-usableSize);
3294       return rc;
3295     }
3296     if( nPage>nPageFile ){
3297       if( sqlite3WritableSchema(pBt->db)==0 ){
3298         rc = SQLITE_CORRUPT_BKPT;
3299         goto page1_init_failed;
3300       }else{
3301         nPage = nPageFile;
3302       }
3303     }
3304     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3305     ** be less than 480. In other words, if the page size is 512, then the
3306     ** reserved space size cannot exceed 32. */
3307     if( usableSize<480 ){
3308       goto page1_init_failed;
3309     }
3310     pBt->pageSize = pageSize;
3311     pBt->usableSize = usableSize;
3312 #ifndef SQLITE_OMIT_AUTOVACUUM
3313     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3314     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3315 #endif
3316   }
3317 
3318   /* maxLocal is the maximum amount of payload to store locally for
3319   ** a cell.  Make sure it is small enough so that at least minFanout
3320   ** cells can will fit on one page.  We assume a 10-byte page header.
3321   ** Besides the payload, the cell must store:
3322   **     2-byte pointer to the cell
3323   **     4-byte child pointer
3324   **     9-byte nKey value
3325   **     4-byte nData value
3326   **     4-byte overflow page pointer
3327   ** So a cell consists of a 2-byte pointer, a header which is as much as
3328   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3329   ** page pointer.
3330   */
3331   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3332   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3333   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3334   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3335   if( pBt->maxLocal>127 ){
3336     pBt->max1bytePayload = 127;
3337   }else{
3338     pBt->max1bytePayload = (u8)pBt->maxLocal;
3339   }
3340   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3341   pBt->pPage1 = pPage1;
3342   pBt->nPage = nPage;
3343   return SQLITE_OK;
3344 
3345 page1_init_failed:
3346   releasePageOne(pPage1);
3347   pBt->pPage1 = 0;
3348   return rc;
3349 }
3350 
3351 #ifndef NDEBUG
3352 /*
3353 ** Return the number of cursors open on pBt. This is for use
3354 ** in assert() expressions, so it is only compiled if NDEBUG is not
3355 ** defined.
3356 **
3357 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
3358 ** false then all cursors are counted.
3359 **
3360 ** For the purposes of this routine, a cursor is any cursor that
3361 ** is capable of reading or writing to the database.  Cursors that
3362 ** have been tripped into the CURSOR_FAULT state are not counted.
3363 */
3364 static int countValidCursors(BtShared *pBt, int wrOnly){
3365   BtCursor *pCur;
3366   int r = 0;
3367   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3368     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3369      && pCur->eState!=CURSOR_FAULT ) r++;
3370   }
3371   return r;
3372 }
3373 #endif
3374 
3375 /*
3376 ** If there are no outstanding cursors and we are not in the middle
3377 ** of a transaction but there is a read lock on the database, then
3378 ** this routine unrefs the first page of the database file which
3379 ** has the effect of releasing the read lock.
3380 **
3381 ** If there is a transaction in progress, this routine is a no-op.
3382 */
3383 static void unlockBtreeIfUnused(BtShared *pBt){
3384   assert( sqlite3_mutex_held(pBt->mutex) );
3385   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3386   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3387     MemPage *pPage1 = pBt->pPage1;
3388     assert( pPage1->aData );
3389     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3390     pBt->pPage1 = 0;
3391     releasePageOne(pPage1);
3392   }
3393 }
3394 
3395 /*
3396 ** If pBt points to an empty file then convert that empty file
3397 ** into a new empty database by initializing the first page of
3398 ** the database.
3399 */
3400 static int newDatabase(BtShared *pBt){
3401   MemPage *pP1;
3402   unsigned char *data;
3403   int rc;
3404 
3405   assert( sqlite3_mutex_held(pBt->mutex) );
3406   if( pBt->nPage>0 ){
3407     return SQLITE_OK;
3408   }
3409   pP1 = pBt->pPage1;
3410   assert( pP1!=0 );
3411   data = pP1->aData;
3412   rc = sqlite3PagerWrite(pP1->pDbPage);
3413   if( rc ) return rc;
3414   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3415   assert( sizeof(zMagicHeader)==16 );
3416   data[16] = (u8)((pBt->pageSize>>8)&0xff);
3417   data[17] = (u8)((pBt->pageSize>>16)&0xff);
3418   data[18] = 1;
3419   data[19] = 1;
3420   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3421   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3422   data[21] = 64;
3423   data[22] = 32;
3424   data[23] = 32;
3425   memset(&data[24], 0, 100-24);
3426   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3427   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3428 #ifndef SQLITE_OMIT_AUTOVACUUM
3429   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3430   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3431   put4byte(&data[36 + 4*4], pBt->autoVacuum);
3432   put4byte(&data[36 + 7*4], pBt->incrVacuum);
3433 #endif
3434   pBt->nPage = 1;
3435   data[31] = 1;
3436   return SQLITE_OK;
3437 }
3438 
3439 /*
3440 ** Initialize the first page of the database file (creating a database
3441 ** consisting of a single page and no schema objects). Return SQLITE_OK
3442 ** if successful, or an SQLite error code otherwise.
3443 */
3444 int sqlite3BtreeNewDb(Btree *p){
3445   int rc;
3446   sqlite3BtreeEnter(p);
3447   p->pBt->nPage = 0;
3448   rc = newDatabase(p->pBt);
3449   sqlite3BtreeLeave(p);
3450   return rc;
3451 }
3452 
3453 /*
3454 ** Attempt to start a new transaction. A write-transaction
3455 ** is started if the second argument is nonzero, otherwise a read-
3456 ** transaction.  If the second argument is 2 or more and exclusive
3457 ** transaction is started, meaning that no other process is allowed
3458 ** to access the database.  A preexisting transaction may not be
3459 ** upgraded to exclusive by calling this routine a second time - the
3460 ** exclusivity flag only works for a new transaction.
3461 **
3462 ** A write-transaction must be started before attempting any
3463 ** changes to the database.  None of the following routines
3464 ** will work unless a transaction is started first:
3465 **
3466 **      sqlite3BtreeCreateTable()
3467 **      sqlite3BtreeCreateIndex()
3468 **      sqlite3BtreeClearTable()
3469 **      sqlite3BtreeDropTable()
3470 **      sqlite3BtreeInsert()
3471 **      sqlite3BtreeDelete()
3472 **      sqlite3BtreeUpdateMeta()
3473 **
3474 ** If an initial attempt to acquire the lock fails because of lock contention
3475 ** and the database was previously unlocked, then invoke the busy handler
3476 ** if there is one.  But if there was previously a read-lock, do not
3477 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
3478 ** returned when there is already a read-lock in order to avoid a deadlock.
3479 **
3480 ** Suppose there are two processes A and B.  A has a read lock and B has
3481 ** a reserved lock.  B tries to promote to exclusive but is blocked because
3482 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
3483 ** One or the other of the two processes must give way or there can be
3484 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
3485 ** when A already has a read lock, we encourage A to give up and let B
3486 ** proceed.
3487 */
3488 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3489   BtShared *pBt = p->pBt;
3490   Pager *pPager = pBt->pPager;
3491   int rc = SQLITE_OK;
3492 
3493   sqlite3BtreeEnter(p);
3494   btreeIntegrity(p);
3495 
3496   /* If the btree is already in a write-transaction, or it
3497   ** is already in a read-transaction and a read-transaction
3498   ** is requested, this is a no-op.
3499   */
3500   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3501     goto trans_begun;
3502   }
3503   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3504 
3505   if( (p->db->flags & SQLITE_ResetDatabase)
3506    && sqlite3PagerIsreadonly(pPager)==0
3507   ){
3508     pBt->btsFlags &= ~BTS_READ_ONLY;
3509   }
3510 
3511   /* Write transactions are not possible on a read-only database */
3512   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3513     rc = SQLITE_READONLY;
3514     goto trans_begun;
3515   }
3516 
3517 #ifndef SQLITE_OMIT_SHARED_CACHE
3518   {
3519     sqlite3 *pBlock = 0;
3520     /* If another database handle has already opened a write transaction
3521     ** on this shared-btree structure and a second write transaction is
3522     ** requested, return SQLITE_LOCKED.
3523     */
3524     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3525      || (pBt->btsFlags & BTS_PENDING)!=0
3526     ){
3527       pBlock = pBt->pWriter->db;
3528     }else if( wrflag>1 ){
3529       BtLock *pIter;
3530       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3531         if( pIter->pBtree!=p ){
3532           pBlock = pIter->pBtree->db;
3533           break;
3534         }
3535       }
3536     }
3537     if( pBlock ){
3538       sqlite3ConnectionBlocked(p->db, pBlock);
3539       rc = SQLITE_LOCKED_SHAREDCACHE;
3540       goto trans_begun;
3541     }
3542   }
3543 #endif
3544 
3545   /* Any read-only or read-write transaction implies a read-lock on
3546   ** page 1. So if some other shared-cache client already has a write-lock
3547   ** on page 1, the transaction cannot be opened. */
3548   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3549   if( SQLITE_OK!=rc ) goto trans_begun;
3550 
3551   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3552   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3553   do {
3554     sqlite3PagerWalDb(pPager, p->db);
3555 
3556 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3557     /* If transitioning from no transaction directly to a write transaction,
3558     ** block for the WRITER lock first if possible. */
3559     if( pBt->pPage1==0 && wrflag ){
3560       assert( pBt->inTransaction==TRANS_NONE );
3561       rc = sqlite3PagerWalWriteLock(pPager, 1);
3562       if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3563     }
3564 #endif
3565 
3566     /* Call lockBtree() until either pBt->pPage1 is populated or
3567     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3568     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3569     ** reading page 1 it discovers that the page-size of the database
3570     ** file is not pBt->pageSize. In this case lockBtree() will update
3571     ** pBt->pageSize to the page-size of the file on disk.
3572     */
3573     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3574 
3575     if( rc==SQLITE_OK && wrflag ){
3576       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3577         rc = SQLITE_READONLY;
3578       }else{
3579         rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3580         if( rc==SQLITE_OK ){
3581           rc = newDatabase(pBt);
3582         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3583           /* if there was no transaction opened when this function was
3584           ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3585           ** code to SQLITE_BUSY. */
3586           rc = SQLITE_BUSY;
3587         }
3588       }
3589     }
3590 
3591     if( rc!=SQLITE_OK ){
3592       (void)sqlite3PagerWalWriteLock(pPager, 0);
3593       unlockBtreeIfUnused(pBt);
3594     }
3595   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3596           btreeInvokeBusyHandler(pBt) );
3597   sqlite3PagerWalDb(pPager, 0);
3598 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3599   if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3600 #endif
3601 
3602   if( rc==SQLITE_OK ){
3603     if( p->inTrans==TRANS_NONE ){
3604       pBt->nTransaction++;
3605 #ifndef SQLITE_OMIT_SHARED_CACHE
3606       if( p->sharable ){
3607         assert( p->lock.pBtree==p && p->lock.iTable==1 );
3608         p->lock.eLock = READ_LOCK;
3609         p->lock.pNext = pBt->pLock;
3610         pBt->pLock = &p->lock;
3611       }
3612 #endif
3613     }
3614     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3615     if( p->inTrans>pBt->inTransaction ){
3616       pBt->inTransaction = p->inTrans;
3617     }
3618     if( wrflag ){
3619       MemPage *pPage1 = pBt->pPage1;
3620 #ifndef SQLITE_OMIT_SHARED_CACHE
3621       assert( !pBt->pWriter );
3622       pBt->pWriter = p;
3623       pBt->btsFlags &= ~BTS_EXCLUSIVE;
3624       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3625 #endif
3626 
3627       /* If the db-size header field is incorrect (as it may be if an old
3628       ** client has been writing the database file), update it now. Doing
3629       ** this sooner rather than later means the database size can safely
3630       ** re-read the database size from page 1 if a savepoint or transaction
3631       ** rollback occurs within the transaction.
3632       */
3633       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3634         rc = sqlite3PagerWrite(pPage1->pDbPage);
3635         if( rc==SQLITE_OK ){
3636           put4byte(&pPage1->aData[28], pBt->nPage);
3637         }
3638       }
3639     }
3640   }
3641 
3642 trans_begun:
3643   if( rc==SQLITE_OK ){
3644     if( pSchemaVersion ){
3645       *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3646     }
3647     if( wrflag ){
3648       /* This call makes sure that the pager has the correct number of
3649       ** open savepoints. If the second parameter is greater than 0 and
3650       ** the sub-journal is not already open, then it will be opened here.
3651       */
3652       rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3653     }
3654   }
3655 
3656   btreeIntegrity(p);
3657   sqlite3BtreeLeave(p);
3658   return rc;
3659 }
3660 
3661 #ifndef SQLITE_OMIT_AUTOVACUUM
3662 
3663 /*
3664 ** Set the pointer-map entries for all children of page pPage. Also, if
3665 ** pPage contains cells that point to overflow pages, set the pointer
3666 ** map entries for the overflow pages as well.
3667 */
3668 static int setChildPtrmaps(MemPage *pPage){
3669   int i;                             /* Counter variable */
3670   int nCell;                         /* Number of cells in page pPage */
3671   int rc;                            /* Return code */
3672   BtShared *pBt = pPage->pBt;
3673   Pgno pgno = pPage->pgno;
3674 
3675   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3676   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3677   if( rc!=SQLITE_OK ) return rc;
3678   nCell = pPage->nCell;
3679 
3680   for(i=0; i<nCell; i++){
3681     u8 *pCell = findCell(pPage, i);
3682 
3683     ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3684 
3685     if( !pPage->leaf ){
3686       Pgno childPgno = get4byte(pCell);
3687       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3688     }
3689   }
3690 
3691   if( !pPage->leaf ){
3692     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3693     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3694   }
3695 
3696   return rc;
3697 }
3698 
3699 /*
3700 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
3701 ** that it points to iTo. Parameter eType describes the type of pointer to
3702 ** be modified, as  follows:
3703 **
3704 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
3705 **                   page of pPage.
3706 **
3707 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3708 **                   page pointed to by one of the cells on pPage.
3709 **
3710 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3711 **                   overflow page in the list.
3712 */
3713 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3714   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3715   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3716   if( eType==PTRMAP_OVERFLOW2 ){
3717     /* The pointer is always the first 4 bytes of the page in this case.  */
3718     if( get4byte(pPage->aData)!=iFrom ){
3719       return SQLITE_CORRUPT_PAGE(pPage);
3720     }
3721     put4byte(pPage->aData, iTo);
3722   }else{
3723     int i;
3724     int nCell;
3725     int rc;
3726 
3727     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3728     if( rc ) return rc;
3729     nCell = pPage->nCell;
3730 
3731     for(i=0; i<nCell; i++){
3732       u8 *pCell = findCell(pPage, i);
3733       if( eType==PTRMAP_OVERFLOW1 ){
3734         CellInfo info;
3735         pPage->xParseCell(pPage, pCell, &info);
3736         if( info.nLocal<info.nPayload ){
3737           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3738             return SQLITE_CORRUPT_PAGE(pPage);
3739           }
3740           if( iFrom==get4byte(pCell+info.nSize-4) ){
3741             put4byte(pCell+info.nSize-4, iTo);
3742             break;
3743           }
3744         }
3745       }else{
3746         if( get4byte(pCell)==iFrom ){
3747           put4byte(pCell, iTo);
3748           break;
3749         }
3750       }
3751     }
3752 
3753     if( i==nCell ){
3754       if( eType!=PTRMAP_BTREE ||
3755           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3756         return SQLITE_CORRUPT_PAGE(pPage);
3757       }
3758       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3759     }
3760   }
3761   return SQLITE_OK;
3762 }
3763 
3764 
3765 /*
3766 ** Move the open database page pDbPage to location iFreePage in the
3767 ** database. The pDbPage reference remains valid.
3768 **
3769 ** The isCommit flag indicates that there is no need to remember that
3770 ** the journal needs to be sync()ed before database page pDbPage->pgno
3771 ** can be written to. The caller has already promised not to write to that
3772 ** page.
3773 */
3774 static int relocatePage(
3775   BtShared *pBt,           /* Btree */
3776   MemPage *pDbPage,        /* Open page to move */
3777   u8 eType,                /* Pointer map 'type' entry for pDbPage */
3778   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
3779   Pgno iFreePage,          /* The location to move pDbPage to */
3780   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
3781 ){
3782   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
3783   Pgno iDbPage = pDbPage->pgno;
3784   Pager *pPager = pBt->pPager;
3785   int rc;
3786 
3787   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3788       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3789   assert( sqlite3_mutex_held(pBt->mutex) );
3790   assert( pDbPage->pBt==pBt );
3791   if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3792 
3793   /* Move page iDbPage from its current location to page number iFreePage */
3794   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3795       iDbPage, iFreePage, iPtrPage, eType));
3796   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3797   if( rc!=SQLITE_OK ){
3798     return rc;
3799   }
3800   pDbPage->pgno = iFreePage;
3801 
3802   /* If pDbPage was a btree-page, then it may have child pages and/or cells
3803   ** that point to overflow pages. The pointer map entries for all these
3804   ** pages need to be changed.
3805   **
3806   ** If pDbPage is an overflow page, then the first 4 bytes may store a
3807   ** pointer to a subsequent overflow page. If this is the case, then
3808   ** the pointer map needs to be updated for the subsequent overflow page.
3809   */
3810   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3811     rc = setChildPtrmaps(pDbPage);
3812     if( rc!=SQLITE_OK ){
3813       return rc;
3814     }
3815   }else{
3816     Pgno nextOvfl = get4byte(pDbPage->aData);
3817     if( nextOvfl!=0 ){
3818       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3819       if( rc!=SQLITE_OK ){
3820         return rc;
3821       }
3822     }
3823   }
3824 
3825   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3826   ** that it points at iFreePage. Also fix the pointer map entry for
3827   ** iPtrPage.
3828   */
3829   if( eType!=PTRMAP_ROOTPAGE ){
3830     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3831     if( rc!=SQLITE_OK ){
3832       return rc;
3833     }
3834     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3835     if( rc!=SQLITE_OK ){
3836       releasePage(pPtrPage);
3837       return rc;
3838     }
3839     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3840     releasePage(pPtrPage);
3841     if( rc==SQLITE_OK ){
3842       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3843     }
3844   }
3845   return rc;
3846 }
3847 
3848 /* Forward declaration required by incrVacuumStep(). */
3849 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3850 
3851 /*
3852 ** Perform a single step of an incremental-vacuum. If successful, return
3853 ** SQLITE_OK. If there is no work to do (and therefore no point in
3854 ** calling this function again), return SQLITE_DONE. Or, if an error
3855 ** occurs, return some other error code.
3856 **
3857 ** More specifically, this function attempts to re-organize the database so
3858 ** that the last page of the file currently in use is no longer in use.
3859 **
3860 ** Parameter nFin is the number of pages that this database would contain
3861 ** were this function called until it returns SQLITE_DONE.
3862 **
3863 ** If the bCommit parameter is non-zero, this function assumes that the
3864 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3865 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3866 ** operation, or false for an incremental vacuum.
3867 */
3868 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3869   Pgno nFreeList;           /* Number of pages still on the free-list */
3870   int rc;
3871 
3872   assert( sqlite3_mutex_held(pBt->mutex) );
3873   assert( iLastPg>nFin );
3874 
3875   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3876     u8 eType;
3877     Pgno iPtrPage;
3878 
3879     nFreeList = get4byte(&pBt->pPage1->aData[36]);
3880     if( nFreeList==0 ){
3881       return SQLITE_DONE;
3882     }
3883 
3884     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3885     if( rc!=SQLITE_OK ){
3886       return rc;
3887     }
3888     if( eType==PTRMAP_ROOTPAGE ){
3889       return SQLITE_CORRUPT_BKPT;
3890     }
3891 
3892     if( eType==PTRMAP_FREEPAGE ){
3893       if( bCommit==0 ){
3894         /* Remove the page from the files free-list. This is not required
3895         ** if bCommit is non-zero. In that case, the free-list will be
3896         ** truncated to zero after this function returns, so it doesn't
3897         ** matter if it still contains some garbage entries.
3898         */
3899         Pgno iFreePg;
3900         MemPage *pFreePg;
3901         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3902         if( rc!=SQLITE_OK ){
3903           return rc;
3904         }
3905         assert( iFreePg==iLastPg );
3906         releasePage(pFreePg);
3907       }
3908     } else {
3909       Pgno iFreePg;             /* Index of free page to move pLastPg to */
3910       MemPage *pLastPg;
3911       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
3912       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
3913 
3914       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3915       if( rc!=SQLITE_OK ){
3916         return rc;
3917       }
3918 
3919       /* If bCommit is zero, this loop runs exactly once and page pLastPg
3920       ** is swapped with the first free page pulled off the free list.
3921       **
3922       ** On the other hand, if bCommit is greater than zero, then keep
3923       ** looping until a free-page located within the first nFin pages
3924       ** of the file is found.
3925       */
3926       if( bCommit==0 ){
3927         eMode = BTALLOC_LE;
3928         iNear = nFin;
3929       }
3930       do {
3931         MemPage *pFreePg;
3932         Pgno dbSize = btreePagecount(pBt);
3933         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3934         if( rc!=SQLITE_OK ){
3935           releasePage(pLastPg);
3936           return rc;
3937         }
3938         releasePage(pFreePg);
3939         if( iFreePg>dbSize ){
3940           releasePage(pLastPg);
3941           return SQLITE_CORRUPT_BKPT;
3942         }
3943       }while( bCommit && iFreePg>nFin );
3944       assert( iFreePg<iLastPg );
3945 
3946       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3947       releasePage(pLastPg);
3948       if( rc!=SQLITE_OK ){
3949         return rc;
3950       }
3951     }
3952   }
3953 
3954   if( bCommit==0 ){
3955     do {
3956       iLastPg--;
3957     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3958     pBt->bDoTruncate = 1;
3959     pBt->nPage = iLastPg;
3960   }
3961   return SQLITE_OK;
3962 }
3963 
3964 /*
3965 ** The database opened by the first argument is an auto-vacuum database
3966 ** nOrig pages in size containing nFree free pages. Return the expected
3967 ** size of the database in pages following an auto-vacuum operation.
3968 */
3969 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3970   int nEntry;                     /* Number of entries on one ptrmap page */
3971   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
3972   Pgno nFin;                      /* Return value */
3973 
3974   nEntry = pBt->usableSize/5;
3975   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3976   nFin = nOrig - nFree - nPtrmap;
3977   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3978     nFin--;
3979   }
3980   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3981     nFin--;
3982   }
3983 
3984   return nFin;
3985 }
3986 
3987 /*
3988 ** A write-transaction must be opened before calling this function.
3989 ** It performs a single unit of work towards an incremental vacuum.
3990 **
3991 ** If the incremental vacuum is finished after this function has run,
3992 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3993 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3994 */
3995 int sqlite3BtreeIncrVacuum(Btree *p){
3996   int rc;
3997   BtShared *pBt = p->pBt;
3998 
3999   sqlite3BtreeEnter(p);
4000   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4001   if( !pBt->autoVacuum ){
4002     rc = SQLITE_DONE;
4003   }else{
4004     Pgno nOrig = btreePagecount(pBt);
4005     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4006     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4007 
4008     if( nOrig<nFin || nFree>=nOrig ){
4009       rc = SQLITE_CORRUPT_BKPT;
4010     }else if( nFree>0 ){
4011       rc = saveAllCursors(pBt, 0, 0);
4012       if( rc==SQLITE_OK ){
4013         invalidateAllOverflowCache(pBt);
4014         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4015       }
4016       if( rc==SQLITE_OK ){
4017         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4018         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4019       }
4020     }else{
4021       rc = SQLITE_DONE;
4022     }
4023   }
4024   sqlite3BtreeLeave(p);
4025   return rc;
4026 }
4027 
4028 /*
4029 ** This routine is called prior to sqlite3PagerCommit when a transaction
4030 ** is committed for an auto-vacuum database.
4031 */
4032 static int autoVacuumCommit(Btree *p){
4033   int rc = SQLITE_OK;
4034   Pager *pPager;
4035   BtShared *pBt;
4036   sqlite3 *db;
4037   VVA_ONLY( int nRef );
4038 
4039   assert( p!=0 );
4040   pBt = p->pBt;
4041   pPager = pBt->pPager;
4042   VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
4043 
4044   assert( sqlite3_mutex_held(pBt->mutex) );
4045   invalidateAllOverflowCache(pBt);
4046   assert(pBt->autoVacuum);
4047   if( !pBt->incrVacuum ){
4048     Pgno nFin;         /* Number of pages in database after autovacuuming */
4049     Pgno nFree;        /* Number of pages on the freelist initially */
4050     Pgno nVac;         /* Number of pages to vacuum */
4051     Pgno iFree;        /* The next page to be freed */
4052     Pgno nOrig;        /* Database size before freeing */
4053 
4054     nOrig = btreePagecount(pBt);
4055     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4056       /* It is not possible to create a database for which the final page
4057       ** is either a pointer-map page or the pending-byte page. If one
4058       ** is encountered, this indicates corruption.
4059       */
4060       return SQLITE_CORRUPT_BKPT;
4061     }
4062 
4063     nFree = get4byte(&pBt->pPage1->aData[36]);
4064     db = p->db;
4065     if( db->xAutovacPages ){
4066       int iDb;
4067       for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4068         if( db->aDb[iDb].pBt==p ) break;
4069       }
4070       nVac = db->xAutovacPages(
4071         db->pAutovacPagesArg,
4072         db->aDb[iDb].zDbSName,
4073         nOrig,
4074         nFree,
4075         pBt->pageSize
4076       );
4077       if( nVac>nFree ){
4078         nVac = nFree;
4079       }
4080       if( nVac==0 ){
4081         return SQLITE_OK;
4082       }
4083     }else{
4084       nVac = nFree;
4085     }
4086     nFin = finalDbSize(pBt, nOrig, nVac);
4087     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
4088     if( nFin<nOrig ){
4089       rc = saveAllCursors(pBt, 0, 0);
4090     }
4091     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4092       rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4093     }
4094     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4095       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4096       if( nVac==nFree ){
4097         put4byte(&pBt->pPage1->aData[32], 0);
4098         put4byte(&pBt->pPage1->aData[36], 0);
4099       }
4100       put4byte(&pBt->pPage1->aData[28], nFin);
4101       pBt->bDoTruncate = 1;
4102       pBt->nPage = nFin;
4103     }
4104     if( rc!=SQLITE_OK ){
4105       sqlite3PagerRollback(pPager);
4106     }
4107   }
4108 
4109   assert( nRef>=sqlite3PagerRefcount(pPager) );
4110   return rc;
4111 }
4112 
4113 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4114 # define setChildPtrmaps(x) SQLITE_OK
4115 #endif
4116 
4117 /*
4118 ** This routine does the first phase of a two-phase commit.  This routine
4119 ** causes a rollback journal to be created (if it does not already exist)
4120 ** and populated with enough information so that if a power loss occurs
4121 ** the database can be restored to its original state by playing back
4122 ** the journal.  Then the contents of the journal are flushed out to
4123 ** the disk.  After the journal is safely on oxide, the changes to the
4124 ** database are written into the database file and flushed to oxide.
4125 ** At the end of this call, the rollback journal still exists on the
4126 ** disk and we are still holding all locks, so the transaction has not
4127 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4128 ** commit process.
4129 **
4130 ** This call is a no-op if no write-transaction is currently active on pBt.
4131 **
4132 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4133 ** the name of a super-journal file that should be written into the
4134 ** individual journal file, or is NULL, indicating no super-journal file
4135 ** (single database transaction).
4136 **
4137 ** When this is called, the super-journal should already have been
4138 ** created, populated with this journal pointer and synced to disk.
4139 **
4140 ** Once this is routine has returned, the only thing required to commit
4141 ** the write-transaction for this database file is to delete the journal.
4142 */
4143 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4144   int rc = SQLITE_OK;
4145   if( p->inTrans==TRANS_WRITE ){
4146     BtShared *pBt = p->pBt;
4147     sqlite3BtreeEnter(p);
4148 #ifndef SQLITE_OMIT_AUTOVACUUM
4149     if( pBt->autoVacuum ){
4150       rc = autoVacuumCommit(p);
4151       if( rc!=SQLITE_OK ){
4152         sqlite3BtreeLeave(p);
4153         return rc;
4154       }
4155     }
4156     if( pBt->bDoTruncate ){
4157       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4158     }
4159 #endif
4160     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4161     sqlite3BtreeLeave(p);
4162   }
4163   return rc;
4164 }
4165 
4166 /*
4167 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4168 ** at the conclusion of a transaction.
4169 */
4170 static void btreeEndTransaction(Btree *p){
4171   BtShared *pBt = p->pBt;
4172   sqlite3 *db = p->db;
4173   assert( sqlite3BtreeHoldsMutex(p) );
4174 
4175 #ifndef SQLITE_OMIT_AUTOVACUUM
4176   pBt->bDoTruncate = 0;
4177 #endif
4178   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4179     /* If there are other active statements that belong to this database
4180     ** handle, downgrade to a read-only transaction. The other statements
4181     ** may still be reading from the database.  */
4182     downgradeAllSharedCacheTableLocks(p);
4183     p->inTrans = TRANS_READ;
4184   }else{
4185     /* If the handle had any kind of transaction open, decrement the
4186     ** transaction count of the shared btree. If the transaction count
4187     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4188     ** call below will unlock the pager.  */
4189     if( p->inTrans!=TRANS_NONE ){
4190       clearAllSharedCacheTableLocks(p);
4191       pBt->nTransaction--;
4192       if( 0==pBt->nTransaction ){
4193         pBt->inTransaction = TRANS_NONE;
4194       }
4195     }
4196 
4197     /* Set the current transaction state to TRANS_NONE and unlock the
4198     ** pager if this call closed the only read or write transaction.  */
4199     p->inTrans = TRANS_NONE;
4200     unlockBtreeIfUnused(pBt);
4201   }
4202 
4203   btreeIntegrity(p);
4204 }
4205 
4206 /*
4207 ** Commit the transaction currently in progress.
4208 **
4209 ** This routine implements the second phase of a 2-phase commit.  The
4210 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4211 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
4212 ** routine did all the work of writing information out to disk and flushing the
4213 ** contents so that they are written onto the disk platter.  All this
4214 ** routine has to do is delete or truncate or zero the header in the
4215 ** the rollback journal (which causes the transaction to commit) and
4216 ** drop locks.
4217 **
4218 ** Normally, if an error occurs while the pager layer is attempting to
4219 ** finalize the underlying journal file, this function returns an error and
4220 ** the upper layer will attempt a rollback. However, if the second argument
4221 ** is non-zero then this b-tree transaction is part of a multi-file
4222 ** transaction. In this case, the transaction has already been committed
4223 ** (by deleting a super-journal file) and the caller will ignore this
4224 ** functions return code. So, even if an error occurs in the pager layer,
4225 ** reset the b-tree objects internal state to indicate that the write
4226 ** transaction has been closed. This is quite safe, as the pager will have
4227 ** transitioned to the error state.
4228 **
4229 ** This will release the write lock on the database file.  If there
4230 ** are no active cursors, it also releases the read lock.
4231 */
4232 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4233 
4234   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4235   sqlite3BtreeEnter(p);
4236   btreeIntegrity(p);
4237 
4238   /* If the handle has a write-transaction open, commit the shared-btrees
4239   ** transaction and set the shared state to TRANS_READ.
4240   */
4241   if( p->inTrans==TRANS_WRITE ){
4242     int rc;
4243     BtShared *pBt = p->pBt;
4244     assert( pBt->inTransaction==TRANS_WRITE );
4245     assert( pBt->nTransaction>0 );
4246     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4247     if( rc!=SQLITE_OK && bCleanup==0 ){
4248       sqlite3BtreeLeave(p);
4249       return rc;
4250     }
4251     p->iBDataVersion--;  /* Compensate for pPager->iDataVersion++; */
4252     pBt->inTransaction = TRANS_READ;
4253     btreeClearHasContent(pBt);
4254   }
4255 
4256   btreeEndTransaction(p);
4257   sqlite3BtreeLeave(p);
4258   return SQLITE_OK;
4259 }
4260 
4261 /*
4262 ** Do both phases of a commit.
4263 */
4264 int sqlite3BtreeCommit(Btree *p){
4265   int rc;
4266   sqlite3BtreeEnter(p);
4267   rc = sqlite3BtreeCommitPhaseOne(p, 0);
4268   if( rc==SQLITE_OK ){
4269     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4270   }
4271   sqlite3BtreeLeave(p);
4272   return rc;
4273 }
4274 
4275 /*
4276 ** This routine sets the state to CURSOR_FAULT and the error
4277 ** code to errCode for every cursor on any BtShared that pBtree
4278 ** references.  Or if the writeOnly flag is set to 1, then only
4279 ** trip write cursors and leave read cursors unchanged.
4280 **
4281 ** Every cursor is a candidate to be tripped, including cursors
4282 ** that belong to other database connections that happen to be
4283 ** sharing the cache with pBtree.
4284 **
4285 ** This routine gets called when a rollback occurs. If the writeOnly
4286 ** flag is true, then only write-cursors need be tripped - read-only
4287 ** cursors save their current positions so that they may continue
4288 ** following the rollback. Or, if writeOnly is false, all cursors are
4289 ** tripped. In general, writeOnly is false if the transaction being
4290 ** rolled back modified the database schema. In this case b-tree root
4291 ** pages may be moved or deleted from the database altogether, making
4292 ** it unsafe for read cursors to continue.
4293 **
4294 ** If the writeOnly flag is true and an error is encountered while
4295 ** saving the current position of a read-only cursor, all cursors,
4296 ** including all read-cursors are tripped.
4297 **
4298 ** SQLITE_OK is returned if successful, or if an error occurs while
4299 ** saving a cursor position, an SQLite error code.
4300 */
4301 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4302   BtCursor *p;
4303   int rc = SQLITE_OK;
4304 
4305   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4306   if( pBtree ){
4307     sqlite3BtreeEnter(pBtree);
4308     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4309       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4310         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4311           rc = saveCursorPosition(p);
4312           if( rc!=SQLITE_OK ){
4313             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4314             break;
4315           }
4316         }
4317       }else{
4318         sqlite3BtreeClearCursor(p);
4319         p->eState = CURSOR_FAULT;
4320         p->skipNext = errCode;
4321       }
4322       btreeReleaseAllCursorPages(p);
4323     }
4324     sqlite3BtreeLeave(pBtree);
4325   }
4326   return rc;
4327 }
4328 
4329 /*
4330 ** Set the pBt->nPage field correctly, according to the current
4331 ** state of the database.  Assume pBt->pPage1 is valid.
4332 */
4333 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4334   int nPage = get4byte(&pPage1->aData[28]);
4335   testcase( nPage==0 );
4336   if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4337   testcase( pBt->nPage!=(u32)nPage );
4338   pBt->nPage = nPage;
4339 }
4340 
4341 /*
4342 ** Rollback the transaction in progress.
4343 **
4344 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4345 ** Only write cursors are tripped if writeOnly is true but all cursors are
4346 ** tripped if writeOnly is false.  Any attempt to use
4347 ** a tripped cursor will result in an error.
4348 **
4349 ** This will release the write lock on the database file.  If there
4350 ** are no active cursors, it also releases the read lock.
4351 */
4352 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4353   int rc;
4354   BtShared *pBt = p->pBt;
4355   MemPage *pPage1;
4356 
4357   assert( writeOnly==1 || writeOnly==0 );
4358   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4359   sqlite3BtreeEnter(p);
4360   if( tripCode==SQLITE_OK ){
4361     rc = tripCode = saveAllCursors(pBt, 0, 0);
4362     if( rc ) writeOnly = 0;
4363   }else{
4364     rc = SQLITE_OK;
4365   }
4366   if( tripCode ){
4367     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4368     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4369     if( rc2!=SQLITE_OK ) rc = rc2;
4370   }
4371   btreeIntegrity(p);
4372 
4373   if( p->inTrans==TRANS_WRITE ){
4374     int rc2;
4375 
4376     assert( TRANS_WRITE==pBt->inTransaction );
4377     rc2 = sqlite3PagerRollback(pBt->pPager);
4378     if( rc2!=SQLITE_OK ){
4379       rc = rc2;
4380     }
4381 
4382     /* The rollback may have destroyed the pPage1->aData value.  So
4383     ** call btreeGetPage() on page 1 again to make
4384     ** sure pPage1->aData is set correctly. */
4385     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4386       btreeSetNPage(pBt, pPage1);
4387       releasePageOne(pPage1);
4388     }
4389     assert( countValidCursors(pBt, 1)==0 );
4390     pBt->inTransaction = TRANS_READ;
4391     btreeClearHasContent(pBt);
4392   }
4393 
4394   btreeEndTransaction(p);
4395   sqlite3BtreeLeave(p);
4396   return rc;
4397 }
4398 
4399 /*
4400 ** Start a statement subtransaction. The subtransaction can be rolled
4401 ** back independently of the main transaction. You must start a transaction
4402 ** before starting a subtransaction. The subtransaction is ended automatically
4403 ** if the main transaction commits or rolls back.
4404 **
4405 ** Statement subtransactions are used around individual SQL statements
4406 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4407 ** error occurs within the statement, the effect of that one statement
4408 ** can be rolled back without having to rollback the entire transaction.
4409 **
4410 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4411 ** value passed as the second parameter is the total number of savepoints,
4412 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4413 ** are no active savepoints and no other statement-transactions open,
4414 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4415 ** using the sqlite3BtreeSavepoint() function.
4416 */
4417 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4418   int rc;
4419   BtShared *pBt = p->pBt;
4420   sqlite3BtreeEnter(p);
4421   assert( p->inTrans==TRANS_WRITE );
4422   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4423   assert( iStatement>0 );
4424   assert( iStatement>p->db->nSavepoint );
4425   assert( pBt->inTransaction==TRANS_WRITE );
4426   /* At the pager level, a statement transaction is a savepoint with
4427   ** an index greater than all savepoints created explicitly using
4428   ** SQL statements. It is illegal to open, release or rollback any
4429   ** such savepoints while the statement transaction savepoint is active.
4430   */
4431   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4432   sqlite3BtreeLeave(p);
4433   return rc;
4434 }
4435 
4436 /*
4437 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4438 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4439 ** savepoint identified by parameter iSavepoint, depending on the value
4440 ** of op.
4441 **
4442 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4443 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4444 ** contents of the entire transaction are rolled back. This is different
4445 ** from a normal transaction rollback, as no locks are released and the
4446 ** transaction remains open.
4447 */
4448 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4449   int rc = SQLITE_OK;
4450   if( p && p->inTrans==TRANS_WRITE ){
4451     BtShared *pBt = p->pBt;
4452     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4453     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4454     sqlite3BtreeEnter(p);
4455     if( op==SAVEPOINT_ROLLBACK ){
4456       rc = saveAllCursors(pBt, 0, 0);
4457     }
4458     if( rc==SQLITE_OK ){
4459       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4460     }
4461     if( rc==SQLITE_OK ){
4462       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4463         pBt->nPage = 0;
4464       }
4465       rc = newDatabase(pBt);
4466       btreeSetNPage(pBt, pBt->pPage1);
4467 
4468       /* pBt->nPage might be zero if the database was corrupt when
4469       ** the transaction was started. Otherwise, it must be at least 1.  */
4470       assert( CORRUPT_DB || pBt->nPage>0 );
4471     }
4472     sqlite3BtreeLeave(p);
4473   }
4474   return rc;
4475 }
4476 
4477 /*
4478 ** Create a new cursor for the BTree whose root is on the page
4479 ** iTable. If a read-only cursor is requested, it is assumed that
4480 ** the caller already has at least a read-only transaction open
4481 ** on the database already. If a write-cursor is requested, then
4482 ** the caller is assumed to have an open write transaction.
4483 **
4484 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4485 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4486 ** can be used for reading or for writing if other conditions for writing
4487 ** are also met.  These are the conditions that must be met in order
4488 ** for writing to be allowed:
4489 **
4490 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4491 **
4492 ** 2:  Other database connections that share the same pager cache
4493 **     but which are not in the READ_UNCOMMITTED state may not have
4494 **     cursors open with wrFlag==0 on the same table.  Otherwise
4495 **     the changes made by this write cursor would be visible to
4496 **     the read cursors in the other database connection.
4497 **
4498 ** 3:  The database must be writable (not on read-only media)
4499 **
4500 ** 4:  There must be an active transaction.
4501 **
4502 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4503 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4504 ** this cursor will only be used to seek to and delete entries of an index
4505 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4506 ** this implementation.  But in a hypothetical alternative storage engine
4507 ** in which index entries are automatically deleted when corresponding table
4508 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4509 ** operations on this cursor can be no-ops and all READ operations can
4510 ** return a null row (2-bytes: 0x01 0x00).
4511 **
4512 ** No checking is done to make sure that page iTable really is the
4513 ** root page of a b-tree.  If it is not, then the cursor acquired
4514 ** will not work correctly.
4515 **
4516 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4517 ** on pCur to initialize the memory space prior to invoking this routine.
4518 */
4519 static int btreeCursor(
4520   Btree *p,                              /* The btree */
4521   Pgno iTable,                           /* Root page of table to open */
4522   int wrFlag,                            /* 1 to write. 0 read-only */
4523   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4524   BtCursor *pCur                         /* Space for new cursor */
4525 ){
4526   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4527   BtCursor *pX;                          /* Looping over other all cursors */
4528 
4529   assert( sqlite3BtreeHoldsMutex(p) );
4530   assert( wrFlag==0
4531        || wrFlag==BTREE_WRCSR
4532        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4533   );
4534 
4535   /* The following assert statements verify that if this is a sharable
4536   ** b-tree database, the connection is holding the required table locks,
4537   ** and that no other connection has any open cursor that conflicts with
4538   ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
4539   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4540           || iTable<1 );
4541   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4542 
4543   /* Assert that the caller has opened the required transaction. */
4544   assert( p->inTrans>TRANS_NONE );
4545   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4546   assert( pBt->pPage1 && pBt->pPage1->aData );
4547   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4548 
4549   if( iTable<=1 ){
4550     if( iTable<1 ){
4551       return SQLITE_CORRUPT_BKPT;
4552     }else if( btreePagecount(pBt)==0 ){
4553       assert( wrFlag==0 );
4554       iTable = 0;
4555     }
4556   }
4557 
4558   /* Now that no other errors can occur, finish filling in the BtCursor
4559   ** variables and link the cursor into the BtShared list.  */
4560   pCur->pgnoRoot = iTable;
4561   pCur->iPage = -1;
4562   pCur->pKeyInfo = pKeyInfo;
4563   pCur->pBtree = p;
4564   pCur->pBt = pBt;
4565   pCur->curFlags = 0;
4566   /* If there are two or more cursors on the same btree, then all such
4567   ** cursors *must* have the BTCF_Multiple flag set. */
4568   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4569     if( pX->pgnoRoot==iTable ){
4570       pX->curFlags |= BTCF_Multiple;
4571       pCur->curFlags = BTCF_Multiple;
4572     }
4573   }
4574   pCur->eState = CURSOR_INVALID;
4575   pCur->pNext = pBt->pCursor;
4576   pBt->pCursor = pCur;
4577   if( wrFlag ){
4578     pCur->curFlags |= BTCF_WriteFlag;
4579     pCur->curPagerFlags = 0;
4580     if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
4581   }else{
4582     pCur->curPagerFlags = PAGER_GET_READONLY;
4583   }
4584   return SQLITE_OK;
4585 }
4586 static int btreeCursorWithLock(
4587   Btree *p,                              /* The btree */
4588   Pgno iTable,                           /* Root page of table to open */
4589   int wrFlag,                            /* 1 to write. 0 read-only */
4590   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4591   BtCursor *pCur                         /* Space for new cursor */
4592 ){
4593   int rc;
4594   sqlite3BtreeEnter(p);
4595   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4596   sqlite3BtreeLeave(p);
4597   return rc;
4598 }
4599 int sqlite3BtreeCursor(
4600   Btree *p,                                   /* The btree */
4601   Pgno iTable,                                /* Root page of table to open */
4602   int wrFlag,                                 /* 1 to write. 0 read-only */
4603   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4604   BtCursor *pCur                              /* Write new cursor here */
4605 ){
4606   if( p->sharable ){
4607     return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4608   }else{
4609     return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4610   }
4611 }
4612 
4613 /*
4614 ** Return the size of a BtCursor object in bytes.
4615 **
4616 ** This interfaces is needed so that users of cursors can preallocate
4617 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4618 ** to users so they cannot do the sizeof() themselves - they must call
4619 ** this routine.
4620 */
4621 int sqlite3BtreeCursorSize(void){
4622   return ROUND8(sizeof(BtCursor));
4623 }
4624 
4625 /*
4626 ** Initialize memory that will be converted into a BtCursor object.
4627 **
4628 ** The simple approach here would be to memset() the entire object
4629 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4630 ** do not need to be zeroed and they are large, so we can save a lot
4631 ** of run-time by skipping the initialization of those elements.
4632 */
4633 void sqlite3BtreeCursorZero(BtCursor *p){
4634   memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4635 }
4636 
4637 /*
4638 ** Close a cursor.  The read lock on the database file is released
4639 ** when the last cursor is closed.
4640 */
4641 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4642   Btree *pBtree = pCur->pBtree;
4643   if( pBtree ){
4644     BtShared *pBt = pCur->pBt;
4645     sqlite3BtreeEnter(pBtree);
4646     assert( pBt->pCursor!=0 );
4647     if( pBt->pCursor==pCur ){
4648       pBt->pCursor = pCur->pNext;
4649     }else{
4650       BtCursor *pPrev = pBt->pCursor;
4651       do{
4652         if( pPrev->pNext==pCur ){
4653           pPrev->pNext = pCur->pNext;
4654           break;
4655         }
4656         pPrev = pPrev->pNext;
4657       }while( ALWAYS(pPrev) );
4658     }
4659     btreeReleaseAllCursorPages(pCur);
4660     unlockBtreeIfUnused(pBt);
4661     sqlite3_free(pCur->aOverflow);
4662     sqlite3_free(pCur->pKey);
4663     if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4664       /* Since the BtShared is not sharable, there is no need to
4665       ** worry about the missing sqlite3BtreeLeave() call here.  */
4666       assert( pBtree->sharable==0 );
4667       sqlite3BtreeClose(pBtree);
4668     }else{
4669       sqlite3BtreeLeave(pBtree);
4670     }
4671     pCur->pBtree = 0;
4672   }
4673   return SQLITE_OK;
4674 }
4675 
4676 /*
4677 ** Make sure the BtCursor* given in the argument has a valid
4678 ** BtCursor.info structure.  If it is not already valid, call
4679 ** btreeParseCell() to fill it in.
4680 **
4681 ** BtCursor.info is a cache of the information in the current cell.
4682 ** Using this cache reduces the number of calls to btreeParseCell().
4683 */
4684 #ifndef NDEBUG
4685   static int cellInfoEqual(CellInfo *a, CellInfo *b){
4686     if( a->nKey!=b->nKey ) return 0;
4687     if( a->pPayload!=b->pPayload ) return 0;
4688     if( a->nPayload!=b->nPayload ) return 0;
4689     if( a->nLocal!=b->nLocal ) return 0;
4690     if( a->nSize!=b->nSize ) return 0;
4691     return 1;
4692   }
4693   static void assertCellInfo(BtCursor *pCur){
4694     CellInfo info;
4695     memset(&info, 0, sizeof(info));
4696     btreeParseCell(pCur->pPage, pCur->ix, &info);
4697     assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4698   }
4699 #else
4700   #define assertCellInfo(x)
4701 #endif
4702 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4703   if( pCur->info.nSize==0 ){
4704     pCur->curFlags |= BTCF_ValidNKey;
4705     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4706   }else{
4707     assertCellInfo(pCur);
4708   }
4709 }
4710 
4711 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4712 /*
4713 ** Return true if the given BtCursor is valid.  A valid cursor is one
4714 ** that is currently pointing to a row in a (non-empty) table.
4715 ** This is a verification routine is used only within assert() statements.
4716 */
4717 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4718   return pCur && pCur->eState==CURSOR_VALID;
4719 }
4720 #endif /* NDEBUG */
4721 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4722   assert( pCur!=0 );
4723   return pCur->eState==CURSOR_VALID;
4724 }
4725 
4726 /*
4727 ** Return the value of the integer key or "rowid" for a table btree.
4728 ** This routine is only valid for a cursor that is pointing into a
4729 ** ordinary table btree.  If the cursor points to an index btree or
4730 ** is invalid, the result of this routine is undefined.
4731 */
4732 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4733   assert( cursorHoldsMutex(pCur) );
4734   assert( pCur->eState==CURSOR_VALID );
4735   assert( pCur->curIntKey );
4736   getCellInfo(pCur);
4737   return pCur->info.nKey;
4738 }
4739 
4740 /*
4741 ** Pin or unpin a cursor.
4742 */
4743 void sqlite3BtreeCursorPin(BtCursor *pCur){
4744   assert( (pCur->curFlags & BTCF_Pinned)==0 );
4745   pCur->curFlags |= BTCF_Pinned;
4746 }
4747 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4748   assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4749   pCur->curFlags &= ~BTCF_Pinned;
4750 }
4751 
4752 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4753 /*
4754 ** Return the offset into the database file for the start of the
4755 ** payload to which the cursor is pointing.
4756 */
4757 i64 sqlite3BtreeOffset(BtCursor *pCur){
4758   assert( cursorHoldsMutex(pCur) );
4759   assert( pCur->eState==CURSOR_VALID );
4760   getCellInfo(pCur);
4761   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4762          (i64)(pCur->info.pPayload - pCur->pPage->aData);
4763 }
4764 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4765 
4766 /*
4767 ** Return the number of bytes of payload for the entry that pCur is
4768 ** currently pointing to.  For table btrees, this will be the amount
4769 ** of data.  For index btrees, this will be the size of the key.
4770 **
4771 ** The caller must guarantee that the cursor is pointing to a non-NULL
4772 ** valid entry.  In other words, the calling procedure must guarantee
4773 ** that the cursor has Cursor.eState==CURSOR_VALID.
4774 */
4775 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4776   assert( cursorHoldsMutex(pCur) );
4777   assert( pCur->eState==CURSOR_VALID );
4778   getCellInfo(pCur);
4779   return pCur->info.nPayload;
4780 }
4781 
4782 /*
4783 ** Return an upper bound on the size of any record for the table
4784 ** that the cursor is pointing into.
4785 **
4786 ** This is an optimization.  Everything will still work if this
4787 ** routine always returns 2147483647 (which is the largest record
4788 ** that SQLite can handle) or more.  But returning a smaller value might
4789 ** prevent large memory allocations when trying to interpret a
4790 ** corrupt datrabase.
4791 **
4792 ** The current implementation merely returns the size of the underlying
4793 ** database file.
4794 */
4795 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4796   assert( cursorHoldsMutex(pCur) );
4797   assert( pCur->eState==CURSOR_VALID );
4798   return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4799 }
4800 
4801 /*
4802 ** Given the page number of an overflow page in the database (parameter
4803 ** ovfl), this function finds the page number of the next page in the
4804 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4805 ** pointer-map data instead of reading the content of page ovfl to do so.
4806 **
4807 ** If an error occurs an SQLite error code is returned. Otherwise:
4808 **
4809 ** The page number of the next overflow page in the linked list is
4810 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4811 ** list, *pPgnoNext is set to zero.
4812 **
4813 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4814 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4815 ** reference. It is the responsibility of the caller to call releasePage()
4816 ** on *ppPage to free the reference. In no reference was obtained (because
4817 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4818 ** *ppPage is set to zero.
4819 */
4820 static int getOverflowPage(
4821   BtShared *pBt,               /* The database file */
4822   Pgno ovfl,                   /* Current overflow page number */
4823   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4824   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4825 ){
4826   Pgno next = 0;
4827   MemPage *pPage = 0;
4828   int rc = SQLITE_OK;
4829 
4830   assert( sqlite3_mutex_held(pBt->mutex) );
4831   assert(pPgnoNext);
4832 
4833 #ifndef SQLITE_OMIT_AUTOVACUUM
4834   /* Try to find the next page in the overflow list using the
4835   ** autovacuum pointer-map pages. Guess that the next page in
4836   ** the overflow list is page number (ovfl+1). If that guess turns
4837   ** out to be wrong, fall back to loading the data of page
4838   ** number ovfl to determine the next page number.
4839   */
4840   if( pBt->autoVacuum ){
4841     Pgno pgno;
4842     Pgno iGuess = ovfl+1;
4843     u8 eType;
4844 
4845     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4846       iGuess++;
4847     }
4848 
4849     if( iGuess<=btreePagecount(pBt) ){
4850       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4851       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4852         next = iGuess;
4853         rc = SQLITE_DONE;
4854       }
4855     }
4856   }
4857 #endif
4858 
4859   assert( next==0 || rc==SQLITE_DONE );
4860   if( rc==SQLITE_OK ){
4861     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4862     assert( rc==SQLITE_OK || pPage==0 );
4863     if( rc==SQLITE_OK ){
4864       next = get4byte(pPage->aData);
4865     }
4866   }
4867 
4868   *pPgnoNext = next;
4869   if( ppPage ){
4870     *ppPage = pPage;
4871   }else{
4872     releasePage(pPage);
4873   }
4874   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4875 }
4876 
4877 /*
4878 ** Copy data from a buffer to a page, or from a page to a buffer.
4879 **
4880 ** pPayload is a pointer to data stored on database page pDbPage.
4881 ** If argument eOp is false, then nByte bytes of data are copied
4882 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4883 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4884 ** of data are copied from the buffer pBuf to pPayload.
4885 **
4886 ** SQLITE_OK is returned on success, otherwise an error code.
4887 */
4888 static int copyPayload(
4889   void *pPayload,           /* Pointer to page data */
4890   void *pBuf,               /* Pointer to buffer */
4891   int nByte,                /* Number of bytes to copy */
4892   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4893   DbPage *pDbPage           /* Page containing pPayload */
4894 ){
4895   if( eOp ){
4896     /* Copy data from buffer to page (a write operation) */
4897     int rc = sqlite3PagerWrite(pDbPage);
4898     if( rc!=SQLITE_OK ){
4899       return rc;
4900     }
4901     memcpy(pPayload, pBuf, nByte);
4902   }else{
4903     /* Copy data from page to buffer (a read operation) */
4904     memcpy(pBuf, pPayload, nByte);
4905   }
4906   return SQLITE_OK;
4907 }
4908 
4909 /*
4910 ** This function is used to read or overwrite payload information
4911 ** for the entry that the pCur cursor is pointing to. The eOp
4912 ** argument is interpreted as follows:
4913 **
4914 **   0: The operation is a read. Populate the overflow cache.
4915 **   1: The operation is a write. Populate the overflow cache.
4916 **
4917 ** A total of "amt" bytes are read or written beginning at "offset".
4918 ** Data is read to or from the buffer pBuf.
4919 **
4920 ** The content being read or written might appear on the main page
4921 ** or be scattered out on multiple overflow pages.
4922 **
4923 ** If the current cursor entry uses one or more overflow pages
4924 ** this function may allocate space for and lazily populate
4925 ** the overflow page-list cache array (BtCursor.aOverflow).
4926 ** Subsequent calls use this cache to make seeking to the supplied offset
4927 ** more efficient.
4928 **
4929 ** Once an overflow page-list cache has been allocated, it must be
4930 ** invalidated if some other cursor writes to the same table, or if
4931 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4932 ** mode, the following events may invalidate an overflow page-list cache.
4933 **
4934 **   * An incremental vacuum,
4935 **   * A commit in auto_vacuum="full" mode,
4936 **   * Creating a table (may require moving an overflow page).
4937 */
4938 static int accessPayload(
4939   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4940   u32 offset,          /* Begin reading this far into payload */
4941   u32 amt,             /* Read this many bytes */
4942   unsigned char *pBuf, /* Write the bytes into this buffer */
4943   int eOp              /* zero to read. non-zero to write. */
4944 ){
4945   unsigned char *aPayload;
4946   int rc = SQLITE_OK;
4947   int iIdx = 0;
4948   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
4949   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4950 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4951   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4952 #endif
4953 
4954   assert( pPage );
4955   assert( eOp==0 || eOp==1 );
4956   assert( pCur->eState==CURSOR_VALID );
4957   if( pCur->ix>=pPage->nCell ){
4958     return SQLITE_CORRUPT_PAGE(pPage);
4959   }
4960   assert( cursorHoldsMutex(pCur) );
4961 
4962   getCellInfo(pCur);
4963   aPayload = pCur->info.pPayload;
4964   assert( offset+amt <= pCur->info.nPayload );
4965 
4966   assert( aPayload > pPage->aData );
4967   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4968     /* Trying to read or write past the end of the data is an error.  The
4969     ** conditional above is really:
4970     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4971     ** but is recast into its current form to avoid integer overflow problems
4972     */
4973     return SQLITE_CORRUPT_PAGE(pPage);
4974   }
4975 
4976   /* Check if data must be read/written to/from the btree page itself. */
4977   if( offset<pCur->info.nLocal ){
4978     int a = amt;
4979     if( a+offset>pCur->info.nLocal ){
4980       a = pCur->info.nLocal - offset;
4981     }
4982     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4983     offset = 0;
4984     pBuf += a;
4985     amt -= a;
4986   }else{
4987     offset -= pCur->info.nLocal;
4988   }
4989 
4990 
4991   if( rc==SQLITE_OK && amt>0 ){
4992     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4993     Pgno nextPage;
4994 
4995     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4996 
4997     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4998     **
4999     ** The aOverflow[] array is sized at one entry for each overflow page
5000     ** in the overflow chain. The page number of the first overflow page is
5001     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5002     ** means "not yet known" (the cache is lazily populated).
5003     */
5004     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
5005       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
5006       if( pCur->aOverflow==0
5007        || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
5008       ){
5009         Pgno *aNew = (Pgno*)sqlite3Realloc(
5010             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
5011         );
5012         if( aNew==0 ){
5013           return SQLITE_NOMEM_BKPT;
5014         }else{
5015           pCur->aOverflow = aNew;
5016         }
5017       }
5018       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5019       pCur->curFlags |= BTCF_ValidOvfl;
5020     }else{
5021       /* If the overflow page-list cache has been allocated and the
5022       ** entry for the first required overflow page is valid, skip
5023       ** directly to it.
5024       */
5025       if( pCur->aOverflow[offset/ovflSize] ){
5026         iIdx = (offset/ovflSize);
5027         nextPage = pCur->aOverflow[iIdx];
5028         offset = (offset%ovflSize);
5029       }
5030     }
5031 
5032     assert( rc==SQLITE_OK && amt>0 );
5033     while( nextPage ){
5034       /* If required, populate the overflow page-list cache. */
5035       if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
5036       assert( pCur->aOverflow[iIdx]==0
5037               || pCur->aOverflow[iIdx]==nextPage
5038               || CORRUPT_DB );
5039       pCur->aOverflow[iIdx] = nextPage;
5040 
5041       if( offset>=ovflSize ){
5042         /* The only reason to read this page is to obtain the page
5043         ** number for the next page in the overflow chain. The page
5044         ** data is not required. So first try to lookup the overflow
5045         ** page-list cache, if any, then fall back to the getOverflowPage()
5046         ** function.
5047         */
5048         assert( pCur->curFlags & BTCF_ValidOvfl );
5049         assert( pCur->pBtree->db==pBt->db );
5050         if( pCur->aOverflow[iIdx+1] ){
5051           nextPage = pCur->aOverflow[iIdx+1];
5052         }else{
5053           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
5054         }
5055         offset -= ovflSize;
5056       }else{
5057         /* Need to read this page properly. It contains some of the
5058         ** range of data that is being read (eOp==0) or written (eOp!=0).
5059         */
5060         int a = amt;
5061         if( a + offset > ovflSize ){
5062           a = ovflSize - offset;
5063         }
5064 
5065 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5066         /* If all the following are true:
5067         **
5068         **   1) this is a read operation, and
5069         **   2) data is required from the start of this overflow page, and
5070         **   3) there are no dirty pages in the page-cache
5071         **   4) the database is file-backed, and
5072         **   5) the page is not in the WAL file
5073         **   6) at least 4 bytes have already been read into the output buffer
5074         **
5075         ** then data can be read directly from the database file into the
5076         ** output buffer, bypassing the page-cache altogether. This speeds
5077         ** up loading large records that span many overflow pages.
5078         */
5079         if( eOp==0                                             /* (1) */
5080          && offset==0                                          /* (2) */
5081          && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
5082          && &pBuf[-4]>=pBufStart                               /* (6) */
5083         ){
5084           sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
5085           u8 aSave[4];
5086           u8 *aWrite = &pBuf[-4];
5087           assert( aWrite>=pBufStart );                         /* due to (6) */
5088           memcpy(aSave, aWrite, 4);
5089           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
5090           if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5091           nextPage = get4byte(aWrite);
5092           memcpy(aWrite, aSave, 4);
5093         }else
5094 #endif
5095 
5096         {
5097           DbPage *pDbPage;
5098           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5099               (eOp==0 ? PAGER_GET_READONLY : 0)
5100           );
5101           if( rc==SQLITE_OK ){
5102             aPayload = sqlite3PagerGetData(pDbPage);
5103             nextPage = get4byte(aPayload);
5104             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5105             sqlite3PagerUnref(pDbPage);
5106             offset = 0;
5107           }
5108         }
5109         amt -= a;
5110         if( amt==0 ) return rc;
5111         pBuf += a;
5112       }
5113       if( rc ) break;
5114       iIdx++;
5115     }
5116   }
5117 
5118   if( rc==SQLITE_OK && amt>0 ){
5119     /* Overflow chain ends prematurely */
5120     return SQLITE_CORRUPT_PAGE(pPage);
5121   }
5122   return rc;
5123 }
5124 
5125 /*
5126 ** Read part of the payload for the row at which that cursor pCur is currently
5127 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
5128 ** begins at "offset".
5129 **
5130 ** pCur can be pointing to either a table or an index b-tree.
5131 ** If pointing to a table btree, then the content section is read.  If
5132 ** pCur is pointing to an index b-tree then the key section is read.
5133 **
5134 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5135 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
5136 ** cursor might be invalid or might need to be restored before being read.
5137 **
5138 ** Return SQLITE_OK on success or an error code if anything goes
5139 ** wrong.  An error is returned if "offset+amt" is larger than
5140 ** the available payload.
5141 */
5142 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5143   assert( cursorHoldsMutex(pCur) );
5144   assert( pCur->eState==CURSOR_VALID );
5145   assert( pCur->iPage>=0 && pCur->pPage );
5146   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5147 }
5148 
5149 /*
5150 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5151 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
5152 ** interface.
5153 */
5154 #ifndef SQLITE_OMIT_INCRBLOB
5155 static SQLITE_NOINLINE int accessPayloadChecked(
5156   BtCursor *pCur,
5157   u32 offset,
5158   u32 amt,
5159   void *pBuf
5160 ){
5161   int rc;
5162   if ( pCur->eState==CURSOR_INVALID ){
5163     return SQLITE_ABORT;
5164   }
5165   assert( cursorOwnsBtShared(pCur) );
5166   rc = btreeRestoreCursorPosition(pCur);
5167   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5168 }
5169 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5170   if( pCur->eState==CURSOR_VALID ){
5171     assert( cursorOwnsBtShared(pCur) );
5172     return accessPayload(pCur, offset, amt, pBuf, 0);
5173   }else{
5174     return accessPayloadChecked(pCur, offset, amt, pBuf);
5175   }
5176 }
5177 #endif /* SQLITE_OMIT_INCRBLOB */
5178 
5179 /*
5180 ** Return a pointer to payload information from the entry that the
5181 ** pCur cursor is pointing to.  The pointer is to the beginning of
5182 ** the key if index btrees (pPage->intKey==0) and is the data for
5183 ** table btrees (pPage->intKey==1). The number of bytes of available
5184 ** key/data is written into *pAmt.  If *pAmt==0, then the value
5185 ** returned will not be a valid pointer.
5186 **
5187 ** This routine is an optimization.  It is common for the entire key
5188 ** and data to fit on the local page and for there to be no overflow
5189 ** pages.  When that is so, this routine can be used to access the
5190 ** key and data without making a copy.  If the key and/or data spills
5191 ** onto overflow pages, then accessPayload() must be used to reassemble
5192 ** the key/data and copy it into a preallocated buffer.
5193 **
5194 ** The pointer returned by this routine looks directly into the cached
5195 ** page of the database.  The data might change or move the next time
5196 ** any btree routine is called.
5197 */
5198 static const void *fetchPayload(
5199   BtCursor *pCur,      /* Cursor pointing to entry to read from */
5200   u32 *pAmt            /* Write the number of available bytes here */
5201 ){
5202   int amt;
5203   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5204   assert( pCur->eState==CURSOR_VALID );
5205   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5206   assert( cursorOwnsBtShared(pCur) );
5207   assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5208   assert( pCur->info.nSize>0 );
5209   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5210   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5211   amt = pCur->info.nLocal;
5212   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5213     /* There is too little space on the page for the expected amount
5214     ** of local content. Database must be corrupt. */
5215     assert( CORRUPT_DB );
5216     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5217   }
5218   *pAmt = (u32)amt;
5219   return (void*)pCur->info.pPayload;
5220 }
5221 
5222 
5223 /*
5224 ** For the entry that cursor pCur is point to, return as
5225 ** many bytes of the key or data as are available on the local
5226 ** b-tree page.  Write the number of available bytes into *pAmt.
5227 **
5228 ** The pointer returned is ephemeral.  The key/data may move
5229 ** or be destroyed on the next call to any Btree routine,
5230 ** including calls from other threads against the same cache.
5231 ** Hence, a mutex on the BtShared should be held prior to calling
5232 ** this routine.
5233 **
5234 ** These routines is used to get quick access to key and data
5235 ** in the common case where no overflow pages are used.
5236 */
5237 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5238   return fetchPayload(pCur, pAmt);
5239 }
5240 
5241 
5242 /*
5243 ** Move the cursor down to a new child page.  The newPgno argument is the
5244 ** page number of the child page to move to.
5245 **
5246 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5247 ** the new child page does not match the flags field of the parent (i.e.
5248 ** if an intkey page appears to be the parent of a non-intkey page, or
5249 ** vice-versa).
5250 */
5251 static int moveToChild(BtCursor *pCur, u32 newPgno){
5252   assert( cursorOwnsBtShared(pCur) );
5253   assert( pCur->eState==CURSOR_VALID );
5254   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5255   assert( pCur->iPage>=0 );
5256   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5257     return SQLITE_CORRUPT_BKPT;
5258   }
5259   pCur->info.nSize = 0;
5260   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5261   pCur->aiIdx[pCur->iPage] = pCur->ix;
5262   pCur->apPage[pCur->iPage] = pCur->pPage;
5263   pCur->ix = 0;
5264   pCur->iPage++;
5265   return getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur,
5266                         pCur->curPagerFlags);
5267 }
5268 
5269 #ifdef SQLITE_DEBUG
5270 /*
5271 ** Page pParent is an internal (non-leaf) tree page. This function
5272 ** asserts that page number iChild is the left-child if the iIdx'th
5273 ** cell in page pParent. Or, if iIdx is equal to the total number of
5274 ** cells in pParent, that page number iChild is the right-child of
5275 ** the page.
5276 */
5277 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5278   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
5279                             ** in a corrupt database */
5280   assert( iIdx<=pParent->nCell );
5281   if( iIdx==pParent->nCell ){
5282     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5283   }else{
5284     assert( get4byte(findCell(pParent, iIdx))==iChild );
5285   }
5286 }
5287 #else
5288 #  define assertParentIndex(x,y,z)
5289 #endif
5290 
5291 /*
5292 ** Move the cursor up to the parent page.
5293 **
5294 ** pCur->idx is set to the cell index that contains the pointer
5295 ** to the page we are coming from.  If we are coming from the
5296 ** right-most child page then pCur->idx is set to one more than
5297 ** the largest cell index.
5298 */
5299 static void moveToParent(BtCursor *pCur){
5300   MemPage *pLeaf;
5301   assert( cursorOwnsBtShared(pCur) );
5302   assert( pCur->eState==CURSOR_VALID );
5303   assert( pCur->iPage>0 );
5304   assert( pCur->pPage );
5305   assertParentIndex(
5306     pCur->apPage[pCur->iPage-1],
5307     pCur->aiIdx[pCur->iPage-1],
5308     pCur->pPage->pgno
5309   );
5310   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5311   pCur->info.nSize = 0;
5312   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5313   pCur->ix = pCur->aiIdx[pCur->iPage-1];
5314   pLeaf = pCur->pPage;
5315   pCur->pPage = pCur->apPage[--pCur->iPage];
5316   releasePageNotNull(pLeaf);
5317 }
5318 
5319 /*
5320 ** Move the cursor to point to the root page of its b-tree structure.
5321 **
5322 ** If the table has a virtual root page, then the cursor is moved to point
5323 ** to the virtual root page instead of the actual root page. A table has a
5324 ** virtual root page when the actual root page contains no cells and a
5325 ** single child page. This can only happen with the table rooted at page 1.
5326 **
5327 ** If the b-tree structure is empty, the cursor state is set to
5328 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5329 ** the cursor is set to point to the first cell located on the root
5330 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5331 **
5332 ** If this function returns successfully, it may be assumed that the
5333 ** page-header flags indicate that the [virtual] root-page is the expected
5334 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5335 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5336 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5337 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5338 ** b-tree).
5339 */
5340 static int moveToRoot(BtCursor *pCur){
5341   MemPage *pRoot;
5342   int rc = SQLITE_OK;
5343 
5344   assert( cursorOwnsBtShared(pCur) );
5345   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5346   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
5347   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
5348   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5349   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5350 
5351   if( pCur->iPage>=0 ){
5352     if( pCur->iPage ){
5353       releasePageNotNull(pCur->pPage);
5354       while( --pCur->iPage ){
5355         releasePageNotNull(pCur->apPage[pCur->iPage]);
5356       }
5357       pRoot = pCur->pPage = pCur->apPage[0];
5358       goto skip_init;
5359     }
5360   }else if( pCur->pgnoRoot==0 ){
5361     pCur->eState = CURSOR_INVALID;
5362     return SQLITE_EMPTY;
5363   }else{
5364     assert( pCur->iPage==(-1) );
5365     if( pCur->eState>=CURSOR_REQUIRESEEK ){
5366       if( pCur->eState==CURSOR_FAULT ){
5367         assert( pCur->skipNext!=SQLITE_OK );
5368         return pCur->skipNext;
5369       }
5370       sqlite3BtreeClearCursor(pCur);
5371     }
5372     rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
5373                         0, pCur->curPagerFlags);
5374     if( rc!=SQLITE_OK ){
5375       pCur->eState = CURSOR_INVALID;
5376       return rc;
5377     }
5378     pCur->iPage = 0;
5379     pCur->curIntKey = pCur->pPage->intKey;
5380   }
5381   pRoot = pCur->pPage;
5382   assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
5383 
5384   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5385   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5386   ** NULL, the caller expects a table b-tree. If this is not the case,
5387   ** return an SQLITE_CORRUPT error.
5388   **
5389   ** Earlier versions of SQLite assumed that this test could not fail
5390   ** if the root page was already loaded when this function was called (i.e.
5391   ** if pCur->iPage>=0). But this is not so if the database is corrupted
5392   ** in such a way that page pRoot is linked into a second b-tree table
5393   ** (or the freelist).  */
5394   assert( pRoot->intKey==1 || pRoot->intKey==0 );
5395   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5396     return SQLITE_CORRUPT_PAGE(pCur->pPage);
5397   }
5398 
5399 skip_init:
5400   pCur->ix = 0;
5401   pCur->info.nSize = 0;
5402   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5403 
5404   if( pRoot->nCell>0 ){
5405     pCur->eState = CURSOR_VALID;
5406   }else if( !pRoot->leaf ){
5407     Pgno subpage;
5408     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5409     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5410     pCur->eState = CURSOR_VALID;
5411     rc = moveToChild(pCur, subpage);
5412   }else{
5413     pCur->eState = CURSOR_INVALID;
5414     rc = SQLITE_EMPTY;
5415   }
5416   return rc;
5417 }
5418 
5419 /*
5420 ** Move the cursor down to the left-most leaf entry beneath the
5421 ** entry to which it is currently pointing.
5422 **
5423 ** The left-most leaf is the one with the smallest key - the first
5424 ** in ascending order.
5425 */
5426 static int moveToLeftmost(BtCursor *pCur){
5427   Pgno pgno;
5428   int rc = SQLITE_OK;
5429   MemPage *pPage;
5430 
5431   assert( cursorOwnsBtShared(pCur) );
5432   assert( pCur->eState==CURSOR_VALID );
5433   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5434     assert( pCur->ix<pPage->nCell );
5435     pgno = get4byte(findCell(pPage, pCur->ix));
5436     rc = moveToChild(pCur, pgno);
5437   }
5438   return rc;
5439 }
5440 
5441 /*
5442 ** Move the cursor down to the right-most leaf entry beneath the
5443 ** page to which it is currently pointing.  Notice the difference
5444 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5445 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5446 ** finds the right-most entry beneath the *page*.
5447 **
5448 ** The right-most entry is the one with the largest key - the last
5449 ** key in ascending order.
5450 */
5451 static int moveToRightmost(BtCursor *pCur){
5452   Pgno pgno;
5453   int rc = SQLITE_OK;
5454   MemPage *pPage = 0;
5455 
5456   assert( cursorOwnsBtShared(pCur) );
5457   assert( pCur->eState==CURSOR_VALID );
5458   while( !(pPage = pCur->pPage)->leaf ){
5459     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5460     pCur->ix = pPage->nCell;
5461     rc = moveToChild(pCur, pgno);
5462     if( rc ) return rc;
5463   }
5464   pCur->ix = pPage->nCell-1;
5465   assert( pCur->info.nSize==0 );
5466   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5467   return SQLITE_OK;
5468 }
5469 
5470 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5471 ** on success.  Set *pRes to 0 if the cursor actually points to something
5472 ** or set *pRes to 1 if the table is empty.
5473 */
5474 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5475   int rc;
5476 
5477   assert( cursorOwnsBtShared(pCur) );
5478   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5479   rc = moveToRoot(pCur);
5480   if( rc==SQLITE_OK ){
5481     assert( pCur->pPage->nCell>0 );
5482     *pRes = 0;
5483     rc = moveToLeftmost(pCur);
5484   }else if( rc==SQLITE_EMPTY ){
5485     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5486     *pRes = 1;
5487     rc = SQLITE_OK;
5488   }
5489   return rc;
5490 }
5491 
5492 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5493 ** on success.  Set *pRes to 0 if the cursor actually points to something
5494 ** or set *pRes to 1 if the table is empty.
5495 */
5496 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5497   int rc;
5498 
5499   assert( cursorOwnsBtShared(pCur) );
5500   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5501 
5502   /* If the cursor already points to the last entry, this is a no-op. */
5503   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5504 #ifdef SQLITE_DEBUG
5505     /* This block serves to assert() that the cursor really does point
5506     ** to the last entry in the b-tree. */
5507     int ii;
5508     for(ii=0; ii<pCur->iPage; ii++){
5509       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5510     }
5511     assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5512     testcase( pCur->ix!=pCur->pPage->nCell-1 );
5513     /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5514     assert( pCur->pPage->leaf );
5515 #endif
5516     *pRes = 0;
5517     return SQLITE_OK;
5518   }
5519 
5520   rc = moveToRoot(pCur);
5521   if( rc==SQLITE_OK ){
5522     assert( pCur->eState==CURSOR_VALID );
5523     *pRes = 0;
5524     rc = moveToRightmost(pCur);
5525     if( rc==SQLITE_OK ){
5526       pCur->curFlags |= BTCF_AtLast;
5527     }else{
5528       pCur->curFlags &= ~BTCF_AtLast;
5529     }
5530   }else if( rc==SQLITE_EMPTY ){
5531     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5532     *pRes = 1;
5533     rc = SQLITE_OK;
5534   }
5535   return rc;
5536 }
5537 
5538 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5539 ** table near the key intKey.   Return a success code.
5540 **
5541 ** If an exact match is not found, then the cursor is always
5542 ** left pointing at a leaf page which would hold the entry if it
5543 ** were present.  The cursor might point to an entry that comes
5544 ** before or after the key.
5545 **
5546 ** An integer is written into *pRes which is the result of
5547 ** comparing the key with the entry to which the cursor is
5548 ** pointing.  The meaning of the integer written into
5549 ** *pRes is as follows:
5550 **
5551 **     *pRes<0      The cursor is left pointing at an entry that
5552 **                  is smaller than intKey or if the table is empty
5553 **                  and the cursor is therefore left point to nothing.
5554 **
5555 **     *pRes==0     The cursor is left pointing at an entry that
5556 **                  exactly matches intKey.
5557 **
5558 **     *pRes>0      The cursor is left pointing at an entry that
5559 **                  is larger than intKey.
5560 */
5561 int sqlite3BtreeTableMoveto(
5562   BtCursor *pCur,          /* The cursor to be moved */
5563   i64 intKey,              /* The table key */
5564   int biasRight,           /* If true, bias the search to the high end */
5565   int *pRes                /* Write search results here */
5566 ){
5567   int rc;
5568 
5569   assert( cursorOwnsBtShared(pCur) );
5570   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5571   assert( pRes );
5572   assert( pCur->pKeyInfo==0 );
5573   assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5574 
5575   /* If the cursor is already positioned at the point we are trying
5576   ** to move to, then just return without doing any work */
5577   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5578     if( pCur->info.nKey==intKey ){
5579       *pRes = 0;
5580       return SQLITE_OK;
5581     }
5582     if( pCur->info.nKey<intKey ){
5583       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5584         *pRes = -1;
5585         return SQLITE_OK;
5586       }
5587       /* If the requested key is one more than the previous key, then
5588       ** try to get there using sqlite3BtreeNext() rather than a full
5589       ** binary search.  This is an optimization only.  The correct answer
5590       ** is still obtained without this case, only a little more slowely */
5591       if( pCur->info.nKey+1==intKey ){
5592         *pRes = 0;
5593         rc = sqlite3BtreeNext(pCur, 0);
5594         if( rc==SQLITE_OK ){
5595           getCellInfo(pCur);
5596           if( pCur->info.nKey==intKey ){
5597             return SQLITE_OK;
5598           }
5599         }else if( rc!=SQLITE_DONE ){
5600           return rc;
5601         }
5602       }
5603     }
5604   }
5605 
5606 #ifdef SQLITE_DEBUG
5607   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5608 #endif
5609 
5610   rc = moveToRoot(pCur);
5611   if( rc ){
5612     if( rc==SQLITE_EMPTY ){
5613       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5614       *pRes = -1;
5615       return SQLITE_OK;
5616     }
5617     return rc;
5618   }
5619   assert( pCur->pPage );
5620   assert( pCur->pPage->isInit );
5621   assert( pCur->eState==CURSOR_VALID );
5622   assert( pCur->pPage->nCell > 0 );
5623   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5624   assert( pCur->curIntKey );
5625 
5626   for(;;){
5627     int lwr, upr, idx, c;
5628     Pgno chldPg;
5629     MemPage *pPage = pCur->pPage;
5630     u8 *pCell;                          /* Pointer to current cell in pPage */
5631 
5632     /* pPage->nCell must be greater than zero. If this is the root-page
5633     ** the cursor would have been INVALID above and this for(;;) loop
5634     ** not run. If this is not the root-page, then the moveToChild() routine
5635     ** would have already detected db corruption. Similarly, pPage must
5636     ** be the right kind (index or table) of b-tree page. Otherwise
5637     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5638     assert( pPage->nCell>0 );
5639     assert( pPage->intKey );
5640     lwr = 0;
5641     upr = pPage->nCell-1;
5642     assert( biasRight==0 || biasRight==1 );
5643     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5644     for(;;){
5645       i64 nCellKey;
5646       pCell = findCellPastPtr(pPage, idx);
5647       if( pPage->intKeyLeaf ){
5648         while( 0x80 <= *(pCell++) ){
5649           if( pCell>=pPage->aDataEnd ){
5650             return SQLITE_CORRUPT_PAGE(pPage);
5651           }
5652         }
5653       }
5654       getVarint(pCell, (u64*)&nCellKey);
5655       if( nCellKey<intKey ){
5656         lwr = idx+1;
5657         if( lwr>upr ){ c = -1; break; }
5658       }else if( nCellKey>intKey ){
5659         upr = idx-1;
5660         if( lwr>upr ){ c = +1; break; }
5661       }else{
5662         assert( nCellKey==intKey );
5663         pCur->ix = (u16)idx;
5664         if( !pPage->leaf ){
5665           lwr = idx;
5666           goto moveto_table_next_layer;
5667         }else{
5668           pCur->curFlags |= BTCF_ValidNKey;
5669           pCur->info.nKey = nCellKey;
5670           pCur->info.nSize = 0;
5671           *pRes = 0;
5672           return SQLITE_OK;
5673         }
5674       }
5675       assert( lwr+upr>=0 );
5676       idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5677     }
5678     assert( lwr==upr+1 || !pPage->leaf );
5679     assert( pPage->isInit );
5680     if( pPage->leaf ){
5681       assert( pCur->ix<pCur->pPage->nCell );
5682       pCur->ix = (u16)idx;
5683       *pRes = c;
5684       rc = SQLITE_OK;
5685       goto moveto_table_finish;
5686     }
5687 moveto_table_next_layer:
5688     if( lwr>=pPage->nCell ){
5689       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5690     }else{
5691       chldPg = get4byte(findCell(pPage, lwr));
5692     }
5693     pCur->ix = (u16)lwr;
5694     rc = moveToChild(pCur, chldPg);
5695     if( rc ) break;
5696   }
5697 moveto_table_finish:
5698   pCur->info.nSize = 0;
5699   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5700   return rc;
5701 }
5702 
5703 /*
5704 ** Compare the "idx"-th cell on the page the cursor pCur is currently
5705 ** pointing to to pIdxKey using xRecordCompare.  Return negative or
5706 ** zero if the cell is less than or equal pIdxKey.  Return positive
5707 ** if unknown.
5708 **
5709 **    Return value negative:     Cell at pCur[idx] less than pIdxKey
5710 **
5711 **    Return value is zero:      Cell at pCur[idx] equals pIdxKey
5712 **
5713 **    Return value positive:     Nothing is known about the relationship
5714 **                               of the cell at pCur[idx] and pIdxKey.
5715 **
5716 ** This routine is part of an optimization.  It is always safe to return
5717 ** a positive value as that will cause the optimization to be skipped.
5718 */
5719 static int indexCellCompare(
5720   BtCursor *pCur,
5721   int idx,
5722   UnpackedRecord *pIdxKey,
5723   RecordCompare xRecordCompare
5724 ){
5725   MemPage *pPage = pCur->pPage;
5726   int c;
5727   int nCell;  /* Size of the pCell cell in bytes */
5728   u8 *pCell = findCellPastPtr(pPage, idx);
5729 
5730   nCell = pCell[0];
5731   if( nCell<=pPage->max1bytePayload ){
5732     /* This branch runs if the record-size field of the cell is a
5733     ** single byte varint and the record fits entirely on the main
5734     ** b-tree page.  */
5735     testcase( pCell+nCell+1==pPage->aDataEnd );
5736     c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5737   }else if( !(pCell[1] & 0x80)
5738     && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5739   ){
5740     /* The record-size field is a 2 byte varint and the record
5741     ** fits entirely on the main b-tree page.  */
5742     testcase( pCell+nCell+2==pPage->aDataEnd );
5743     c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5744   }else{
5745     /* If the record extends into overflow pages, do not attempt
5746     ** the optimization. */
5747     c = 99;
5748   }
5749   return c;
5750 }
5751 
5752 /*
5753 ** Return true (non-zero) if pCur is current pointing to the last
5754 ** page of a table.
5755 */
5756 static int cursorOnLastPage(BtCursor *pCur){
5757   int i;
5758   assert( pCur->eState==CURSOR_VALID );
5759   for(i=0; i<pCur->iPage; i++){
5760     MemPage *pPage = pCur->apPage[i];
5761     if( pCur->aiIdx[i]<pPage->nCell ) return 0;
5762   }
5763   return 1;
5764 }
5765 
5766 /* Move the cursor so that it points to an entry in an index table
5767 ** near the key pIdxKey.   Return a success code.
5768 **
5769 ** If an exact match is not found, then the cursor is always
5770 ** left pointing at a leaf page which would hold the entry if it
5771 ** were present.  The cursor might point to an entry that comes
5772 ** before or after the key.
5773 **
5774 ** An integer is written into *pRes which is the result of
5775 ** comparing the key with the entry to which the cursor is
5776 ** pointing.  The meaning of the integer written into
5777 ** *pRes is as follows:
5778 **
5779 **     *pRes<0      The cursor is left pointing at an entry that
5780 **                  is smaller than pIdxKey or if the table is empty
5781 **                  and the cursor is therefore left point to nothing.
5782 **
5783 **     *pRes==0     The cursor is left pointing at an entry that
5784 **                  exactly matches pIdxKey.
5785 **
5786 **     *pRes>0      The cursor is left pointing at an entry that
5787 **                  is larger than pIdxKey.
5788 **
5789 ** The pIdxKey->eqSeen field is set to 1 if there
5790 ** exists an entry in the table that exactly matches pIdxKey.
5791 */
5792 int sqlite3BtreeIndexMoveto(
5793   BtCursor *pCur,          /* The cursor to be moved */
5794   UnpackedRecord *pIdxKey, /* Unpacked index key */
5795   int *pRes                /* Write search results here */
5796 ){
5797   int rc;
5798   RecordCompare xRecordCompare;
5799 
5800   assert( cursorOwnsBtShared(pCur) );
5801   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5802   assert( pRes );
5803   assert( pCur->pKeyInfo!=0 );
5804 
5805 #ifdef SQLITE_DEBUG
5806   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5807 #endif
5808 
5809   xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5810   pIdxKey->errCode = 0;
5811   assert( pIdxKey->default_rc==1
5812        || pIdxKey->default_rc==0
5813        || pIdxKey->default_rc==-1
5814   );
5815 
5816 
5817   /* Check to see if we can skip a lot of work.  Two cases:
5818   **
5819   **    (1) If the cursor is already pointing to the very last cell
5820   **        in the table and the pIdxKey search key is greater than or
5821   **        equal to that last cell, then no movement is required.
5822   **
5823   **    (2) If the cursor is on the last page of the table and the first
5824   **        cell on that last page is less than or equal to the pIdxKey
5825   **        search key, then we can start the search on the current page
5826   **        without needing to go back to root.
5827   */
5828   if( pCur->eState==CURSOR_VALID
5829    && pCur->pPage->leaf
5830    && cursorOnLastPage(pCur)
5831   ){
5832     int c;
5833     if( pCur->ix==pCur->pPage->nCell-1
5834      && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
5835      && pIdxKey->errCode==SQLITE_OK
5836     ){
5837       *pRes = c;
5838       return SQLITE_OK;  /* Cursor already pointing at the correct spot */
5839     }
5840     if( pCur->iPage>0
5841      && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
5842      && pIdxKey->errCode==SQLITE_OK
5843     ){
5844       pCur->curFlags &= ~BTCF_ValidOvfl;
5845       if( !pCur->pPage->isInit ){
5846         return SQLITE_CORRUPT_BKPT;
5847       }
5848       goto bypass_moveto_root;  /* Start search on the current page */
5849     }
5850     pIdxKey->errCode = SQLITE_OK;
5851   }
5852 
5853   rc = moveToRoot(pCur);
5854   if( rc ){
5855     if( rc==SQLITE_EMPTY ){
5856       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5857       *pRes = -1;
5858       return SQLITE_OK;
5859     }
5860     return rc;
5861   }
5862 
5863 bypass_moveto_root:
5864   assert( pCur->pPage );
5865   assert( pCur->pPage->isInit );
5866   assert( pCur->eState==CURSOR_VALID );
5867   assert( pCur->pPage->nCell > 0 );
5868   assert( pCur->curIntKey==0 );
5869   assert( pIdxKey!=0 );
5870   for(;;){
5871     int lwr, upr, idx, c;
5872     Pgno chldPg;
5873     MemPage *pPage = pCur->pPage;
5874     u8 *pCell;                          /* Pointer to current cell in pPage */
5875 
5876     /* pPage->nCell must be greater than zero. If this is the root-page
5877     ** the cursor would have been INVALID above and this for(;;) loop
5878     ** not run. If this is not the root-page, then the moveToChild() routine
5879     ** would have already detected db corruption. Similarly, pPage must
5880     ** be the right kind (index or table) of b-tree page. Otherwise
5881     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5882     assert( pPage->nCell>0 );
5883     assert( pPage->intKey==0 );
5884     lwr = 0;
5885     upr = pPage->nCell-1;
5886     idx = upr>>1; /* idx = (lwr+upr)/2; */
5887     for(;;){
5888       int nCell;  /* Size of the pCell cell in bytes */
5889       pCell = findCellPastPtr(pPage, idx);
5890 
5891       /* The maximum supported page-size is 65536 bytes. This means that
5892       ** the maximum number of record bytes stored on an index B-Tree
5893       ** page is less than 16384 bytes and may be stored as a 2-byte
5894       ** varint. This information is used to attempt to avoid parsing
5895       ** the entire cell by checking for the cases where the record is
5896       ** stored entirely within the b-tree page by inspecting the first
5897       ** 2 bytes of the cell.
5898       */
5899       nCell = pCell[0];
5900       if( nCell<=pPage->max1bytePayload ){
5901         /* This branch runs if the record-size field of the cell is a
5902         ** single byte varint and the record fits entirely on the main
5903         ** b-tree page.  */
5904         testcase( pCell+nCell+1==pPage->aDataEnd );
5905         c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5906       }else if( !(pCell[1] & 0x80)
5907         && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5908       ){
5909         /* The record-size field is a 2 byte varint and the record
5910         ** fits entirely on the main b-tree page.  */
5911         testcase( pCell+nCell+2==pPage->aDataEnd );
5912         c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5913       }else{
5914         /* The record flows over onto one or more overflow pages. In
5915         ** this case the whole cell needs to be parsed, a buffer allocated
5916         ** and accessPayload() used to retrieve the record into the
5917         ** buffer before VdbeRecordCompare() can be called.
5918         **
5919         ** If the record is corrupt, the xRecordCompare routine may read
5920         ** up to two varints past the end of the buffer. An extra 18
5921         ** bytes of padding is allocated at the end of the buffer in
5922         ** case this happens.  */
5923         void *pCellKey;
5924         u8 * const pCellBody = pCell - pPage->childPtrSize;
5925         const int nOverrun = 18;  /* Size of the overrun padding */
5926         pPage->xParseCell(pPage, pCellBody, &pCur->info);
5927         nCell = (int)pCur->info.nKey;
5928         testcase( nCell<0 );   /* True if key size is 2^32 or more */
5929         testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5930         testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5931         testcase( nCell==2 );  /* Minimum legal index key size */
5932         if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5933           rc = SQLITE_CORRUPT_PAGE(pPage);
5934           goto moveto_index_finish;
5935         }
5936         pCellKey = sqlite3Malloc( nCell+nOverrun );
5937         if( pCellKey==0 ){
5938           rc = SQLITE_NOMEM_BKPT;
5939           goto moveto_index_finish;
5940         }
5941         pCur->ix = (u16)idx;
5942         rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5943         memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5944         pCur->curFlags &= ~BTCF_ValidOvfl;
5945         if( rc ){
5946           sqlite3_free(pCellKey);
5947           goto moveto_index_finish;
5948         }
5949         c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5950         sqlite3_free(pCellKey);
5951       }
5952       assert(
5953           (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5954        && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5955       );
5956       if( c<0 ){
5957         lwr = idx+1;
5958       }else if( c>0 ){
5959         upr = idx-1;
5960       }else{
5961         assert( c==0 );
5962         *pRes = 0;
5963         rc = SQLITE_OK;
5964         pCur->ix = (u16)idx;
5965         if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5966         goto moveto_index_finish;
5967       }
5968       if( lwr>upr ) break;
5969       assert( lwr+upr>=0 );
5970       idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5971     }
5972     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5973     assert( pPage->isInit );
5974     if( pPage->leaf ){
5975       assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5976       pCur->ix = (u16)idx;
5977       *pRes = c;
5978       rc = SQLITE_OK;
5979       goto moveto_index_finish;
5980     }
5981     if( lwr>=pPage->nCell ){
5982       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5983     }else{
5984       chldPg = get4byte(findCell(pPage, lwr));
5985     }
5986     pCur->ix = (u16)lwr;
5987     rc = moveToChild(pCur, chldPg);
5988     if( rc ) break;
5989   }
5990 moveto_index_finish:
5991   pCur->info.nSize = 0;
5992   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5993   return rc;
5994 }
5995 
5996 
5997 /*
5998 ** Return TRUE if the cursor is not pointing at an entry of the table.
5999 **
6000 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
6001 ** past the last entry in the table or sqlite3BtreePrev() moves past
6002 ** the first entry.  TRUE is also returned if the table is empty.
6003 */
6004 int sqlite3BtreeEof(BtCursor *pCur){
6005   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6006   ** have been deleted? This API will need to change to return an error code
6007   ** as well as the boolean result value.
6008   */
6009   return (CURSOR_VALID!=pCur->eState);
6010 }
6011 
6012 /*
6013 ** Return an estimate for the number of rows in the table that pCur is
6014 ** pointing to.  Return a negative number if no estimate is currently
6015 ** available.
6016 */
6017 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6018   i64 n;
6019   u8 i;
6020 
6021   assert( cursorOwnsBtShared(pCur) );
6022   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6023 
6024   /* Currently this interface is only called by the OP_IfSmaller
6025   ** opcode, and it that case the cursor will always be valid and
6026   ** will always point to a leaf node. */
6027   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
6028   if( NEVER(pCur->pPage->leaf==0) ) return -1;
6029 
6030   n = pCur->pPage->nCell;
6031   for(i=0; i<pCur->iPage; i++){
6032     n *= pCur->apPage[i]->nCell;
6033   }
6034   return n;
6035 }
6036 
6037 /*
6038 ** Advance the cursor to the next entry in the database.
6039 ** Return value:
6040 **
6041 **    SQLITE_OK        success
6042 **    SQLITE_DONE      cursor is already pointing at the last element
6043 **    otherwise        some kind of error occurred
6044 **
6045 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
6046 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6047 ** to the next cell on the current page.  The (slower) btreeNext() helper
6048 ** routine is called when it is necessary to move to a different page or
6049 ** to restore the cursor.
6050 **
6051 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6052 ** cursor corresponds to an SQL index and this routine could have been
6053 ** skipped if the SQL index had been a unique index.  The F argument
6054 ** is a hint to the implement.  SQLite btree implementation does not use
6055 ** this hint, but COMDB2 does.
6056 */
6057 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
6058   int rc;
6059   int idx;
6060   MemPage *pPage;
6061 
6062   assert( cursorOwnsBtShared(pCur) );
6063   if( pCur->eState!=CURSOR_VALID ){
6064     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6065     rc = restoreCursorPosition(pCur);
6066     if( rc!=SQLITE_OK ){
6067       return rc;
6068     }
6069     if( CURSOR_INVALID==pCur->eState ){
6070       return SQLITE_DONE;
6071     }
6072     if( pCur->eState==CURSOR_SKIPNEXT ){
6073       pCur->eState = CURSOR_VALID;
6074       if( pCur->skipNext>0 ) return SQLITE_OK;
6075     }
6076   }
6077 
6078   pPage = pCur->pPage;
6079   idx = ++pCur->ix;
6080   if( NEVER(!pPage->isInit) || sqlite3FaultSim(412) ){
6081     return SQLITE_CORRUPT_BKPT;
6082   }
6083 
6084   if( idx>=pPage->nCell ){
6085     if( !pPage->leaf ){
6086       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6087       if( rc ) return rc;
6088       return moveToLeftmost(pCur);
6089     }
6090     do{
6091       if( pCur->iPage==0 ){
6092         pCur->eState = CURSOR_INVALID;
6093         return SQLITE_DONE;
6094       }
6095       moveToParent(pCur);
6096       pPage = pCur->pPage;
6097     }while( pCur->ix>=pPage->nCell );
6098     if( pPage->intKey ){
6099       return sqlite3BtreeNext(pCur, 0);
6100     }else{
6101       return SQLITE_OK;
6102     }
6103   }
6104   if( pPage->leaf ){
6105     return SQLITE_OK;
6106   }else{
6107     return moveToLeftmost(pCur);
6108   }
6109 }
6110 int sqlite3BtreeNext(BtCursor *pCur, int flags){
6111   MemPage *pPage;
6112   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
6113   assert( cursorOwnsBtShared(pCur) );
6114   assert( flags==0 || flags==1 );
6115   pCur->info.nSize = 0;
6116   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6117   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
6118   pPage = pCur->pPage;
6119   if( (++pCur->ix)>=pPage->nCell ){
6120     pCur->ix--;
6121     return btreeNext(pCur);
6122   }
6123   if( pPage->leaf ){
6124     return SQLITE_OK;
6125   }else{
6126     return moveToLeftmost(pCur);
6127   }
6128 }
6129 
6130 /*
6131 ** Step the cursor to the back to the previous entry in the database.
6132 ** Return values:
6133 **
6134 **     SQLITE_OK     success
6135 **     SQLITE_DONE   the cursor is already on the first element of the table
6136 **     otherwise     some kind of error occurred
6137 **
6138 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
6139 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
6140 ** to the previous cell on the current page.  The (slower) btreePrevious()
6141 ** helper routine is called when it is necessary to move to a different page
6142 ** or to restore the cursor.
6143 **
6144 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6145 ** the cursor corresponds to an SQL index and this routine could have been
6146 ** skipped if the SQL index had been a unique index.  The F argument is a
6147 ** hint to the implement.  The native SQLite btree implementation does not
6148 ** use this hint, but COMDB2 does.
6149 */
6150 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
6151   int rc;
6152   MemPage *pPage;
6153 
6154   assert( cursorOwnsBtShared(pCur) );
6155   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6156   assert( pCur->info.nSize==0 );
6157   if( pCur->eState!=CURSOR_VALID ){
6158     rc = restoreCursorPosition(pCur);
6159     if( rc!=SQLITE_OK ){
6160       return rc;
6161     }
6162     if( CURSOR_INVALID==pCur->eState ){
6163       return SQLITE_DONE;
6164     }
6165     if( CURSOR_SKIPNEXT==pCur->eState ){
6166       pCur->eState = CURSOR_VALID;
6167       if( pCur->skipNext<0 ) return SQLITE_OK;
6168     }
6169   }
6170 
6171   pPage = pCur->pPage;
6172   assert( pPage->isInit );
6173   if( !pPage->leaf ){
6174     int idx = pCur->ix;
6175     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
6176     if( rc ) return rc;
6177     rc = moveToRightmost(pCur);
6178   }else{
6179     while( pCur->ix==0 ){
6180       if( pCur->iPage==0 ){
6181         pCur->eState = CURSOR_INVALID;
6182         return SQLITE_DONE;
6183       }
6184       moveToParent(pCur);
6185     }
6186     assert( pCur->info.nSize==0 );
6187     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6188 
6189     pCur->ix--;
6190     pPage = pCur->pPage;
6191     if( pPage->intKey && !pPage->leaf ){
6192       rc = sqlite3BtreePrevious(pCur, 0);
6193     }else{
6194       rc = SQLITE_OK;
6195     }
6196   }
6197   return rc;
6198 }
6199 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6200   assert( cursorOwnsBtShared(pCur) );
6201   assert( flags==0 || flags==1 );
6202   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
6203   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6204   pCur->info.nSize = 0;
6205   if( pCur->eState!=CURSOR_VALID
6206    || pCur->ix==0
6207    || pCur->pPage->leaf==0
6208   ){
6209     return btreePrevious(pCur);
6210   }
6211   pCur->ix--;
6212   return SQLITE_OK;
6213 }
6214 
6215 /*
6216 ** Allocate a new page from the database file.
6217 **
6218 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
6219 ** has already been called on the new page.)  The new page has also
6220 ** been referenced and the calling routine is responsible for calling
6221 ** sqlite3PagerUnref() on the new page when it is done.
6222 **
6223 ** SQLITE_OK is returned on success.  Any other return value indicates
6224 ** an error.  *ppPage is set to NULL in the event of an error.
6225 **
6226 ** If the "nearby" parameter is not 0, then an effort is made to
6227 ** locate a page close to the page number "nearby".  This can be used in an
6228 ** attempt to keep related pages close to each other in the database file,
6229 ** which in turn can make database access faster.
6230 **
6231 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6232 ** anywhere on the free-list, then it is guaranteed to be returned.  If
6233 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6234 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
6235 ** are no restrictions on which page is returned.
6236 */
6237 static int allocateBtreePage(
6238   BtShared *pBt,         /* The btree */
6239   MemPage **ppPage,      /* Store pointer to the allocated page here */
6240   Pgno *pPgno,           /* Store the page number here */
6241   Pgno nearby,           /* Search for a page near this one */
6242   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6243 ){
6244   MemPage *pPage1;
6245   int rc;
6246   u32 n;     /* Number of pages on the freelist */
6247   u32 k;     /* Number of leaves on the trunk of the freelist */
6248   MemPage *pTrunk = 0;
6249   MemPage *pPrevTrunk = 0;
6250   Pgno mxPage;     /* Total size of the database file */
6251 
6252   assert( sqlite3_mutex_held(pBt->mutex) );
6253   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6254   pPage1 = pBt->pPage1;
6255   mxPage = btreePagecount(pBt);
6256   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
6257   ** stores stores the total number of pages on the freelist. */
6258   n = get4byte(&pPage1->aData[36]);
6259   testcase( n==mxPage-1 );
6260   if( n>=mxPage ){
6261     return SQLITE_CORRUPT_BKPT;
6262   }
6263   if( n>0 ){
6264     /* There are pages on the freelist.  Reuse one of those pages. */
6265     Pgno iTrunk;
6266     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6267     u32 nSearch = 0;   /* Count of the number of search attempts */
6268 
6269     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6270     ** shows that the page 'nearby' is somewhere on the free-list, then
6271     ** the entire-list will be searched for that page.
6272     */
6273 #ifndef SQLITE_OMIT_AUTOVACUUM
6274     if( eMode==BTALLOC_EXACT ){
6275       if( nearby<=mxPage ){
6276         u8 eType;
6277         assert( nearby>0 );
6278         assert( pBt->autoVacuum );
6279         rc = ptrmapGet(pBt, nearby, &eType, 0);
6280         if( rc ) return rc;
6281         if( eType==PTRMAP_FREEPAGE ){
6282           searchList = 1;
6283         }
6284       }
6285     }else if( eMode==BTALLOC_LE ){
6286       searchList = 1;
6287     }
6288 #endif
6289 
6290     /* Decrement the free-list count by 1. Set iTrunk to the index of the
6291     ** first free-list trunk page. iPrevTrunk is initially 1.
6292     */
6293     rc = sqlite3PagerWrite(pPage1->pDbPage);
6294     if( rc ) return rc;
6295     put4byte(&pPage1->aData[36], n-1);
6296 
6297     /* The code within this loop is run only once if the 'searchList' variable
6298     ** is not true. Otherwise, it runs once for each trunk-page on the
6299     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6300     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6301     */
6302     do {
6303       pPrevTrunk = pTrunk;
6304       if( pPrevTrunk ){
6305         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6306         ** is the page number of the next freelist trunk page in the list or
6307         ** zero if this is the last freelist trunk page. */
6308         iTrunk = get4byte(&pPrevTrunk->aData[0]);
6309       }else{
6310         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6311         ** stores the page number of the first page of the freelist, or zero if
6312         ** the freelist is empty. */
6313         iTrunk = get4byte(&pPage1->aData[32]);
6314       }
6315       testcase( iTrunk==mxPage );
6316       if( iTrunk>mxPage || nSearch++ > n ){
6317         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6318       }else{
6319         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6320       }
6321       if( rc ){
6322         pTrunk = 0;
6323         goto end_allocate_page;
6324       }
6325       assert( pTrunk!=0 );
6326       assert( pTrunk->aData!=0 );
6327       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6328       ** is the number of leaf page pointers to follow. */
6329       k = get4byte(&pTrunk->aData[4]);
6330       if( k==0 && !searchList ){
6331         /* The trunk has no leaves and the list is not being searched.
6332         ** So extract the trunk page itself and use it as the newly
6333         ** allocated page */
6334         assert( pPrevTrunk==0 );
6335         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6336         if( rc ){
6337           goto end_allocate_page;
6338         }
6339         *pPgno = iTrunk;
6340         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6341         *ppPage = pTrunk;
6342         pTrunk = 0;
6343         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6344       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6345         /* Value of k is out of range.  Database corruption */
6346         rc = SQLITE_CORRUPT_PGNO(iTrunk);
6347         goto end_allocate_page;
6348 #ifndef SQLITE_OMIT_AUTOVACUUM
6349       }else if( searchList
6350             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6351       ){
6352         /* The list is being searched and this trunk page is the page
6353         ** to allocate, regardless of whether it has leaves.
6354         */
6355         *pPgno = iTrunk;
6356         *ppPage = pTrunk;
6357         searchList = 0;
6358         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6359         if( rc ){
6360           goto end_allocate_page;
6361         }
6362         if( k==0 ){
6363           if( !pPrevTrunk ){
6364             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6365           }else{
6366             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6367             if( rc!=SQLITE_OK ){
6368               goto end_allocate_page;
6369             }
6370             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6371           }
6372         }else{
6373           /* The trunk page is required by the caller but it contains
6374           ** pointers to free-list leaves. The first leaf becomes a trunk
6375           ** page in this case.
6376           */
6377           MemPage *pNewTrunk;
6378           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6379           if( iNewTrunk>mxPage ){
6380             rc = SQLITE_CORRUPT_PGNO(iTrunk);
6381             goto end_allocate_page;
6382           }
6383           testcase( iNewTrunk==mxPage );
6384           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6385           if( rc!=SQLITE_OK ){
6386             goto end_allocate_page;
6387           }
6388           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6389           if( rc!=SQLITE_OK ){
6390             releasePage(pNewTrunk);
6391             goto end_allocate_page;
6392           }
6393           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6394           put4byte(&pNewTrunk->aData[4], k-1);
6395           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6396           releasePage(pNewTrunk);
6397           if( !pPrevTrunk ){
6398             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6399             put4byte(&pPage1->aData[32], iNewTrunk);
6400           }else{
6401             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6402             if( rc ){
6403               goto end_allocate_page;
6404             }
6405             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6406           }
6407         }
6408         pTrunk = 0;
6409         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6410 #endif
6411       }else if( k>0 ){
6412         /* Extract a leaf from the trunk */
6413         u32 closest;
6414         Pgno iPage;
6415         unsigned char *aData = pTrunk->aData;
6416         if( nearby>0 ){
6417           u32 i;
6418           closest = 0;
6419           if( eMode==BTALLOC_LE ){
6420             for(i=0; i<k; i++){
6421               iPage = get4byte(&aData[8+i*4]);
6422               if( iPage<=nearby ){
6423                 closest = i;
6424                 break;
6425               }
6426             }
6427           }else{
6428             int dist;
6429             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6430             for(i=1; i<k; i++){
6431               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6432               if( d2<dist ){
6433                 closest = i;
6434                 dist = d2;
6435               }
6436             }
6437           }
6438         }else{
6439           closest = 0;
6440         }
6441 
6442         iPage = get4byte(&aData[8+closest*4]);
6443         testcase( iPage==mxPage );
6444         if( iPage>mxPage || iPage<2 ){
6445           rc = SQLITE_CORRUPT_PGNO(iTrunk);
6446           goto end_allocate_page;
6447         }
6448         testcase( iPage==mxPage );
6449         if( !searchList
6450          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6451         ){
6452           int noContent;
6453           *pPgno = iPage;
6454           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6455                  ": %d more free pages\n",
6456                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
6457           rc = sqlite3PagerWrite(pTrunk->pDbPage);
6458           if( rc ) goto end_allocate_page;
6459           if( closest<k-1 ){
6460             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6461           }
6462           put4byte(&aData[4], k-1);
6463           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6464           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6465           if( rc==SQLITE_OK ){
6466             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6467             if( rc!=SQLITE_OK ){
6468               releasePage(*ppPage);
6469               *ppPage = 0;
6470             }
6471           }
6472           searchList = 0;
6473         }
6474       }
6475       releasePage(pPrevTrunk);
6476       pPrevTrunk = 0;
6477     }while( searchList );
6478   }else{
6479     /* There are no pages on the freelist, so append a new page to the
6480     ** database image.
6481     **
6482     ** Normally, new pages allocated by this block can be requested from the
6483     ** pager layer with the 'no-content' flag set. This prevents the pager
6484     ** from trying to read the pages content from disk. However, if the
6485     ** current transaction has already run one or more incremental-vacuum
6486     ** steps, then the page we are about to allocate may contain content
6487     ** that is required in the event of a rollback. In this case, do
6488     ** not set the no-content flag. This causes the pager to load and journal
6489     ** the current page content before overwriting it.
6490     **
6491     ** Note that the pager will not actually attempt to load or journal
6492     ** content for any page that really does lie past the end of the database
6493     ** file on disk. So the effects of disabling the no-content optimization
6494     ** here are confined to those pages that lie between the end of the
6495     ** database image and the end of the database file.
6496     */
6497     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6498 
6499     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6500     if( rc ) return rc;
6501     pBt->nPage++;
6502     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6503 
6504 #ifndef SQLITE_OMIT_AUTOVACUUM
6505     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6506       /* If *pPgno refers to a pointer-map page, allocate two new pages
6507       ** at the end of the file instead of one. The first allocated page
6508       ** becomes a new pointer-map page, the second is used by the caller.
6509       */
6510       MemPage *pPg = 0;
6511       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6512       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6513       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6514       if( rc==SQLITE_OK ){
6515         rc = sqlite3PagerWrite(pPg->pDbPage);
6516         releasePage(pPg);
6517       }
6518       if( rc ) return rc;
6519       pBt->nPage++;
6520       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6521     }
6522 #endif
6523     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6524     *pPgno = pBt->nPage;
6525 
6526     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6527     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6528     if( rc ) return rc;
6529     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6530     if( rc!=SQLITE_OK ){
6531       releasePage(*ppPage);
6532       *ppPage = 0;
6533     }
6534     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6535   }
6536 
6537   assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6538 
6539 end_allocate_page:
6540   releasePage(pTrunk);
6541   releasePage(pPrevTrunk);
6542   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6543   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6544   return rc;
6545 }
6546 
6547 /*
6548 ** This function is used to add page iPage to the database file free-list.
6549 ** It is assumed that the page is not already a part of the free-list.
6550 **
6551 ** The value passed as the second argument to this function is optional.
6552 ** If the caller happens to have a pointer to the MemPage object
6553 ** corresponding to page iPage handy, it may pass it as the second value.
6554 ** Otherwise, it may pass NULL.
6555 **
6556 ** If a pointer to a MemPage object is passed as the second argument,
6557 ** its reference count is not altered by this function.
6558 */
6559 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6560   MemPage *pTrunk = 0;                /* Free-list trunk page */
6561   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
6562   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
6563   MemPage *pPage;                     /* Page being freed. May be NULL. */
6564   int rc;                             /* Return Code */
6565   u32 nFree;                          /* Initial number of pages on free-list */
6566 
6567   assert( sqlite3_mutex_held(pBt->mutex) );
6568   assert( CORRUPT_DB || iPage>1 );
6569   assert( !pMemPage || pMemPage->pgno==iPage );
6570 
6571   if( iPage<2 || iPage>pBt->nPage ){
6572     return SQLITE_CORRUPT_BKPT;
6573   }
6574   if( pMemPage ){
6575     pPage = pMemPage;
6576     sqlite3PagerRef(pPage->pDbPage);
6577   }else{
6578     pPage = btreePageLookup(pBt, iPage);
6579   }
6580 
6581   /* Increment the free page count on pPage1 */
6582   rc = sqlite3PagerWrite(pPage1->pDbPage);
6583   if( rc ) goto freepage_out;
6584   nFree = get4byte(&pPage1->aData[36]);
6585   put4byte(&pPage1->aData[36], nFree+1);
6586 
6587   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6588     /* If the secure_delete option is enabled, then
6589     ** always fully overwrite deleted information with zeros.
6590     */
6591     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6592      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6593     ){
6594       goto freepage_out;
6595     }
6596     memset(pPage->aData, 0, pPage->pBt->pageSize);
6597   }
6598 
6599   /* If the database supports auto-vacuum, write an entry in the pointer-map
6600   ** to indicate that the page is free.
6601   */
6602   if( ISAUTOVACUUM ){
6603     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6604     if( rc ) goto freepage_out;
6605   }
6606 
6607   /* Now manipulate the actual database free-list structure. There are two
6608   ** possibilities. If the free-list is currently empty, or if the first
6609   ** trunk page in the free-list is full, then this page will become a
6610   ** new free-list trunk page. Otherwise, it will become a leaf of the
6611   ** first trunk page in the current free-list. This block tests if it
6612   ** is possible to add the page as a new free-list leaf.
6613   */
6614   if( nFree!=0 ){
6615     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6616 
6617     iTrunk = get4byte(&pPage1->aData[32]);
6618     if( iTrunk>btreePagecount(pBt) ){
6619       rc = SQLITE_CORRUPT_BKPT;
6620       goto freepage_out;
6621     }
6622     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6623     if( rc!=SQLITE_OK ){
6624       goto freepage_out;
6625     }
6626 
6627     nLeaf = get4byte(&pTrunk->aData[4]);
6628     assert( pBt->usableSize>32 );
6629     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6630       rc = SQLITE_CORRUPT_BKPT;
6631       goto freepage_out;
6632     }
6633     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6634       /* In this case there is room on the trunk page to insert the page
6635       ** being freed as a new leaf.
6636       **
6637       ** Note that the trunk page is not really full until it contains
6638       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6639       ** coded.  But due to a coding error in versions of SQLite prior to
6640       ** 3.6.0, databases with freelist trunk pages holding more than
6641       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6642       ** to maintain backwards compatibility with older versions of SQLite,
6643       ** we will continue to restrict the number of entries to usableSize/4 - 8
6644       ** for now.  At some point in the future (once everyone has upgraded
6645       ** to 3.6.0 or later) we should consider fixing the conditional above
6646       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6647       **
6648       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6649       ** avoid using the last six entries in the freelist trunk page array in
6650       ** order that database files created by newer versions of SQLite can be
6651       ** read by older versions of SQLite.
6652       */
6653       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6654       if( rc==SQLITE_OK ){
6655         put4byte(&pTrunk->aData[4], nLeaf+1);
6656         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6657         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6658           sqlite3PagerDontWrite(pPage->pDbPage);
6659         }
6660         rc = btreeSetHasContent(pBt, iPage);
6661       }
6662       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6663       goto freepage_out;
6664     }
6665   }
6666 
6667   /* If control flows to this point, then it was not possible to add the
6668   ** the page being freed as a leaf page of the first trunk in the free-list.
6669   ** Possibly because the free-list is empty, or possibly because the
6670   ** first trunk in the free-list is full. Either way, the page being freed
6671   ** will become the new first trunk page in the free-list.
6672   */
6673   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6674     goto freepage_out;
6675   }
6676   rc = sqlite3PagerWrite(pPage->pDbPage);
6677   if( rc!=SQLITE_OK ){
6678     goto freepage_out;
6679   }
6680   put4byte(pPage->aData, iTrunk);
6681   put4byte(&pPage->aData[4], 0);
6682   put4byte(&pPage1->aData[32], iPage);
6683   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6684 
6685 freepage_out:
6686   if( pPage ){
6687     pPage->isInit = 0;
6688   }
6689   releasePage(pPage);
6690   releasePage(pTrunk);
6691   return rc;
6692 }
6693 static void freePage(MemPage *pPage, int *pRC){
6694   if( (*pRC)==SQLITE_OK ){
6695     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6696   }
6697 }
6698 
6699 /*
6700 ** Free the overflow pages associated with the given Cell.
6701 */
6702 static SQLITE_NOINLINE int clearCellOverflow(
6703   MemPage *pPage,          /* The page that contains the Cell */
6704   unsigned char *pCell,    /* First byte of the Cell */
6705   CellInfo *pInfo          /* Size information about the cell */
6706 ){
6707   BtShared *pBt;
6708   Pgno ovflPgno;
6709   int rc;
6710   int nOvfl;
6711   u32 ovflPageSize;
6712 
6713   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6714   assert( pInfo->nLocal!=pInfo->nPayload );
6715   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6716   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6717   if( pCell + pInfo->nSize > pPage->aDataEnd ){
6718     /* Cell extends past end of page */
6719     return SQLITE_CORRUPT_PAGE(pPage);
6720   }
6721   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6722   pBt = pPage->pBt;
6723   assert( pBt->usableSize > 4 );
6724   ovflPageSize = pBt->usableSize - 4;
6725   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6726   assert( nOvfl>0 ||
6727     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6728   );
6729   while( nOvfl-- ){
6730     Pgno iNext = 0;
6731     MemPage *pOvfl = 0;
6732     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6733       /* 0 is not a legal page number and page 1 cannot be an
6734       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6735       ** file the database must be corrupt. */
6736       return SQLITE_CORRUPT_BKPT;
6737     }
6738     if( nOvfl ){
6739       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6740       if( rc ) return rc;
6741     }
6742 
6743     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6744      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6745     ){
6746       /* There is no reason any cursor should have an outstanding reference
6747       ** to an overflow page belonging to a cell that is being deleted/updated.
6748       ** So if there exists more than one reference to this page, then it
6749       ** must not really be an overflow page and the database must be corrupt.
6750       ** It is helpful to detect this before calling freePage2(), as
6751       ** freePage2() may zero the page contents if secure-delete mode is
6752       ** enabled. If this 'overflow' page happens to be a page that the
6753       ** caller is iterating through or using in some other way, this
6754       ** can be problematic.
6755       */
6756       rc = SQLITE_CORRUPT_BKPT;
6757     }else{
6758       rc = freePage2(pBt, pOvfl, ovflPgno);
6759     }
6760 
6761     if( pOvfl ){
6762       sqlite3PagerUnref(pOvfl->pDbPage);
6763     }
6764     if( rc ) return rc;
6765     ovflPgno = iNext;
6766   }
6767   return SQLITE_OK;
6768 }
6769 
6770 /* Call xParseCell to compute the size of a cell.  If the cell contains
6771 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6772 ** STore the result code (SQLITE_OK or some error code) in rc.
6773 **
6774 ** Implemented as macro to force inlining for performance.
6775 */
6776 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo)   \
6777   pPage->xParseCell(pPage, pCell, &sInfo);          \
6778   if( sInfo.nLocal!=sInfo.nPayload ){               \
6779     rc = clearCellOverflow(pPage, pCell, &sInfo);   \
6780   }else{                                            \
6781     rc = SQLITE_OK;                                 \
6782   }
6783 
6784 
6785 /*
6786 ** Create the byte sequence used to represent a cell on page pPage
6787 ** and write that byte sequence into pCell[].  Overflow pages are
6788 ** allocated and filled in as necessary.  The calling procedure
6789 ** is responsible for making sure sufficient space has been allocated
6790 ** for pCell[].
6791 **
6792 ** Note that pCell does not necessary need to point to the pPage->aData
6793 ** area.  pCell might point to some temporary storage.  The cell will
6794 ** be constructed in this temporary area then copied into pPage->aData
6795 ** later.
6796 */
6797 static int fillInCell(
6798   MemPage *pPage,                /* The page that contains the cell */
6799   unsigned char *pCell,          /* Complete text of the cell */
6800   const BtreePayload *pX,        /* Payload with which to construct the cell */
6801   int *pnSize                    /* Write cell size here */
6802 ){
6803   int nPayload;
6804   const u8 *pSrc;
6805   int nSrc, n, rc, mn;
6806   int spaceLeft;
6807   MemPage *pToRelease;
6808   unsigned char *pPrior;
6809   unsigned char *pPayload;
6810   BtShared *pBt;
6811   Pgno pgnoOvfl;
6812   int nHeader;
6813 
6814   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6815 
6816   /* pPage is not necessarily writeable since pCell might be auxiliary
6817   ** buffer space that is separate from the pPage buffer area */
6818   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6819             || sqlite3PagerIswriteable(pPage->pDbPage) );
6820 
6821   /* Fill in the header. */
6822   nHeader = pPage->childPtrSize;
6823   if( pPage->intKey ){
6824     nPayload = pX->nData + pX->nZero;
6825     pSrc = pX->pData;
6826     nSrc = pX->nData;
6827     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6828     nHeader += putVarint32(&pCell[nHeader], nPayload);
6829     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6830   }else{
6831     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6832     nSrc = nPayload = (int)pX->nKey;
6833     pSrc = pX->pKey;
6834     nHeader += putVarint32(&pCell[nHeader], nPayload);
6835   }
6836 
6837   /* Fill in the payload */
6838   pPayload = &pCell[nHeader];
6839   if( nPayload<=pPage->maxLocal ){
6840     /* This is the common case where everything fits on the btree page
6841     ** and no overflow pages are required. */
6842     n = nHeader + nPayload;
6843     testcase( n==3 );
6844     testcase( n==4 );
6845     if( n<4 ) n = 4;
6846     *pnSize = n;
6847     assert( nSrc<=nPayload );
6848     testcase( nSrc<nPayload );
6849     memcpy(pPayload, pSrc, nSrc);
6850     memset(pPayload+nSrc, 0, nPayload-nSrc);
6851     return SQLITE_OK;
6852   }
6853 
6854   /* If we reach this point, it means that some of the content will need
6855   ** to spill onto overflow pages.
6856   */
6857   mn = pPage->minLocal;
6858   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6859   testcase( n==pPage->maxLocal );
6860   testcase( n==pPage->maxLocal+1 );
6861   if( n > pPage->maxLocal ) n = mn;
6862   spaceLeft = n;
6863   *pnSize = n + nHeader + 4;
6864   pPrior = &pCell[nHeader+n];
6865   pToRelease = 0;
6866   pgnoOvfl = 0;
6867   pBt = pPage->pBt;
6868 
6869   /* At this point variables should be set as follows:
6870   **
6871   **   nPayload           Total payload size in bytes
6872   **   pPayload           Begin writing payload here
6873   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6874   **                      that means content must spill into overflow pages.
6875   **   *pnSize            Size of the local cell (not counting overflow pages)
6876   **   pPrior             Where to write the pgno of the first overflow page
6877   **
6878   ** Use a call to btreeParseCellPtr() to verify that the values above
6879   ** were computed correctly.
6880   */
6881 #ifdef SQLITE_DEBUG
6882   {
6883     CellInfo info;
6884     pPage->xParseCell(pPage, pCell, &info);
6885     assert( nHeader==(int)(info.pPayload - pCell) );
6886     assert( info.nKey==pX->nKey );
6887     assert( *pnSize == info.nSize );
6888     assert( spaceLeft == info.nLocal );
6889   }
6890 #endif
6891 
6892   /* Write the payload into the local Cell and any extra into overflow pages */
6893   while( 1 ){
6894     n = nPayload;
6895     if( n>spaceLeft ) n = spaceLeft;
6896 
6897     /* If pToRelease is not zero than pPayload points into the data area
6898     ** of pToRelease.  Make sure pToRelease is still writeable. */
6899     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6900 
6901     /* If pPayload is part of the data area of pPage, then make sure pPage
6902     ** is still writeable */
6903     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6904             || sqlite3PagerIswriteable(pPage->pDbPage) );
6905 
6906     if( nSrc>=n ){
6907       memcpy(pPayload, pSrc, n);
6908     }else if( nSrc>0 ){
6909       n = nSrc;
6910       memcpy(pPayload, pSrc, n);
6911     }else{
6912       memset(pPayload, 0, n);
6913     }
6914     nPayload -= n;
6915     if( nPayload<=0 ) break;
6916     pPayload += n;
6917     pSrc += n;
6918     nSrc -= n;
6919     spaceLeft -= n;
6920     if( spaceLeft==0 ){
6921       MemPage *pOvfl = 0;
6922 #ifndef SQLITE_OMIT_AUTOVACUUM
6923       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6924       if( pBt->autoVacuum ){
6925         do{
6926           pgnoOvfl++;
6927         } while(
6928           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6929         );
6930       }
6931 #endif
6932       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6933 #ifndef SQLITE_OMIT_AUTOVACUUM
6934       /* If the database supports auto-vacuum, and the second or subsequent
6935       ** overflow page is being allocated, add an entry to the pointer-map
6936       ** for that page now.
6937       **
6938       ** If this is the first overflow page, then write a partial entry
6939       ** to the pointer-map. If we write nothing to this pointer-map slot,
6940       ** then the optimistic overflow chain processing in clearCell()
6941       ** may misinterpret the uninitialized values and delete the
6942       ** wrong pages from the database.
6943       */
6944       if( pBt->autoVacuum && rc==SQLITE_OK ){
6945         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6946         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6947         if( rc ){
6948           releasePage(pOvfl);
6949         }
6950       }
6951 #endif
6952       if( rc ){
6953         releasePage(pToRelease);
6954         return rc;
6955       }
6956 
6957       /* If pToRelease is not zero than pPrior points into the data area
6958       ** of pToRelease.  Make sure pToRelease is still writeable. */
6959       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6960 
6961       /* If pPrior is part of the data area of pPage, then make sure pPage
6962       ** is still writeable */
6963       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6964             || sqlite3PagerIswriteable(pPage->pDbPage) );
6965 
6966       put4byte(pPrior, pgnoOvfl);
6967       releasePage(pToRelease);
6968       pToRelease = pOvfl;
6969       pPrior = pOvfl->aData;
6970       put4byte(pPrior, 0);
6971       pPayload = &pOvfl->aData[4];
6972       spaceLeft = pBt->usableSize - 4;
6973     }
6974   }
6975   releasePage(pToRelease);
6976   return SQLITE_OK;
6977 }
6978 
6979 /*
6980 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6981 ** The cell content is not freed or deallocated.  It is assumed that
6982 ** the cell content has been copied someplace else.  This routine just
6983 ** removes the reference to the cell from pPage.
6984 **
6985 ** "sz" must be the number of bytes in the cell.
6986 */
6987 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6988   u32 pc;         /* Offset to cell content of cell being deleted */
6989   u8 *data;       /* pPage->aData */
6990   u8 *ptr;        /* Used to move bytes around within data[] */
6991   int rc;         /* The return code */
6992   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6993 
6994   if( *pRC ) return;
6995   assert( idx>=0 );
6996   assert( idx<pPage->nCell );
6997   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6998   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6999   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7000   assert( pPage->nFree>=0 );
7001   data = pPage->aData;
7002   ptr = &pPage->aCellIdx[2*idx];
7003   assert( pPage->pBt->usableSize > (u32)(ptr-data) );
7004   pc = get2byte(ptr);
7005   hdr = pPage->hdrOffset;
7006   testcase( pc==(u32)get2byte(&data[hdr+5]) );
7007   testcase( pc+sz==pPage->pBt->usableSize );
7008   if( pc+sz > pPage->pBt->usableSize ){
7009     *pRC = SQLITE_CORRUPT_BKPT;
7010     return;
7011   }
7012   rc = freeSpace(pPage, pc, sz);
7013   if( rc ){
7014     *pRC = rc;
7015     return;
7016   }
7017   pPage->nCell--;
7018   if( pPage->nCell==0 ){
7019     memset(&data[hdr+1], 0, 4);
7020     data[hdr+7] = 0;
7021     put2byte(&data[hdr+5], pPage->pBt->usableSize);
7022     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7023                        - pPage->childPtrSize - 8;
7024   }else{
7025     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7026     put2byte(&data[hdr+3], pPage->nCell);
7027     pPage->nFree += 2;
7028   }
7029 }
7030 
7031 /*
7032 ** Insert a new cell on pPage at cell index "i".  pCell points to the
7033 ** content of the cell.
7034 **
7035 ** If the cell content will fit on the page, then put it there.  If it
7036 ** will not fit, then make a copy of the cell content into pTemp if
7037 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
7038 ** in pPage->apOvfl[] and make it point to the cell content (either
7039 ** in pTemp or the original pCell) and also record its index.
7040 ** Allocating a new entry in pPage->aCell[] implies that
7041 ** pPage->nOverflow is incremented.
7042 **
7043 ** *pRC must be SQLITE_OK when this routine is called.
7044 */
7045 static void insertCell(
7046   MemPage *pPage,   /* Page into which we are copying */
7047   int i,            /* New cell becomes the i-th cell of the page */
7048   u8 *pCell,        /* Content of the new cell */
7049   int sz,           /* Bytes of content in pCell */
7050   u8 *pTemp,        /* Temp storage space for pCell, if needed */
7051   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
7052   int *pRC          /* Read and write return code from here */
7053 ){
7054   int idx = 0;      /* Where to write new cell content in data[] */
7055   int j;            /* Loop counter */
7056   u8 *data;         /* The content of the whole page */
7057   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
7058 
7059   assert( *pRC==SQLITE_OK );
7060   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7061   assert( MX_CELL(pPage->pBt)<=10921 );
7062   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7063   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7064   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7065   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7066   assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7067   assert( pPage->nFree>=0 );
7068   if( pPage->nOverflow || sz+2>pPage->nFree ){
7069     if( pTemp ){
7070       memcpy(pTemp, pCell, sz);
7071       pCell = pTemp;
7072     }
7073     if( iChild ){
7074       put4byte(pCell, iChild);
7075     }
7076     j = pPage->nOverflow++;
7077     /* Comparison against ArraySize-1 since we hold back one extra slot
7078     ** as a contingency.  In other words, never need more than 3 overflow
7079     ** slots but 4 are allocated, just to be safe. */
7080     assert( j < ArraySize(pPage->apOvfl)-1 );
7081     pPage->apOvfl[j] = pCell;
7082     pPage->aiOvfl[j] = (u16)i;
7083 
7084     /* When multiple overflows occur, they are always sequential and in
7085     ** sorted order.  This invariants arise because multiple overflows can
7086     ** only occur when inserting divider cells into the parent page during
7087     ** balancing, and the dividers are adjacent and sorted.
7088     */
7089     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7090     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
7091   }else{
7092     int rc = sqlite3PagerWrite(pPage->pDbPage);
7093     if( rc!=SQLITE_OK ){
7094       *pRC = rc;
7095       return;
7096     }
7097     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7098     data = pPage->aData;
7099     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7100     rc = allocateSpace(pPage, sz, &idx);
7101     if( rc ){ *pRC = rc; return; }
7102     /* The allocateSpace() routine guarantees the following properties
7103     ** if it returns successfully */
7104     assert( idx >= 0 );
7105     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7106     assert( idx+sz <= (int)pPage->pBt->usableSize );
7107     pPage->nFree -= (u16)(2 + sz);
7108     if( iChild ){
7109       /* In a corrupt database where an entry in the cell index section of
7110       ** a btree page has a value of 3 or less, the pCell value might point
7111       ** as many as 4 bytes in front of the start of the aData buffer for
7112       ** the source page.  Make sure this does not cause problems by not
7113       ** reading the first 4 bytes */
7114       memcpy(&data[idx+4], pCell+4, sz-4);
7115       put4byte(&data[idx], iChild);
7116     }else{
7117       memcpy(&data[idx], pCell, sz);
7118     }
7119     pIns = pPage->aCellIdx + i*2;
7120     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7121     put2byte(pIns, idx);
7122     pPage->nCell++;
7123     /* increment the cell count */
7124     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7125     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7126 #ifndef SQLITE_OMIT_AUTOVACUUM
7127     if( pPage->pBt->autoVacuum ){
7128       /* The cell may contain a pointer to an overflow page. If so, write
7129       ** the entry for the overflow page into the pointer map.
7130       */
7131       ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
7132     }
7133 #endif
7134   }
7135 }
7136 
7137 /*
7138 ** The following parameters determine how many adjacent pages get involved
7139 ** in a balancing operation.  NN is the number of neighbors on either side
7140 ** of the page that participate in the balancing operation.  NB is the
7141 ** total number of pages that participate, including the target page and
7142 ** NN neighbors on either side.
7143 **
7144 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
7145 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7146 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7147 ** The value of NN appears to give the best results overall.
7148 **
7149 ** (Later:) The description above makes it seem as if these values are
7150 ** tunable - as if you could change them and recompile and it would all work.
7151 ** But that is unlikely.  NB has been 3 since the inception of SQLite and
7152 ** we have never tested any other value.
7153 */
7154 #define NN 1             /* Number of neighbors on either side of pPage */
7155 #define NB 3             /* (NN*2+1): Total pages involved in the balance */
7156 
7157 /*
7158 ** A CellArray object contains a cache of pointers and sizes for a
7159 ** consecutive sequence of cells that might be held on multiple pages.
7160 **
7161 ** The cells in this array are the divider cell or cells from the pParent
7162 ** page plus up to three child pages.  There are a total of nCell cells.
7163 **
7164 ** pRef is a pointer to one of the pages that contributes cells.  This is
7165 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7166 ** which should be common to all pages that contribute cells to this array.
7167 **
7168 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
7169 ** cell and the size of each cell.  Some of the apCell[] pointers might refer
7170 ** to overflow cells.  In other words, some apCel[] pointers might not point
7171 ** to content area of the pages.
7172 **
7173 ** A szCell[] of zero means the size of that cell has not yet been computed.
7174 **
7175 ** The cells come from as many as four different pages:
7176 **
7177 **             -----------
7178 **             | Parent  |
7179 **             -----------
7180 **            /     |     \
7181 **           /      |      \
7182 **  ---------   ---------   ---------
7183 **  |Child-1|   |Child-2|   |Child-3|
7184 **  ---------   ---------   ---------
7185 **
7186 ** The order of cells is in the array is for an index btree is:
7187 **
7188 **       1.  All cells from Child-1 in order
7189 **       2.  The first divider cell from Parent
7190 **       3.  All cells from Child-2 in order
7191 **       4.  The second divider cell from Parent
7192 **       5.  All cells from Child-3 in order
7193 **
7194 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7195 ** content exists only in leaves and there are no divider cells.
7196 **
7197 ** For an index btree, the apEnd[] array holds pointer to the end of page
7198 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7199 ** respectively. The ixNx[] array holds the number of cells contained in
7200 ** each of these 5 stages, and all stages to the left.  Hence:
7201 **
7202 **    ixNx[0] = Number of cells in Child-1.
7203 **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7204 **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7205 **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7206 **    ixNx[4] = Total number of cells.
7207 **
7208 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7209 ** are used and they point to the leaf pages only, and the ixNx value are:
7210 **
7211 **    ixNx[0] = Number of cells in Child-1.
7212 **    ixNx[1] = Number of cells in Child-1 and Child-2.
7213 **    ixNx[2] = Total number of cells.
7214 **
7215 ** Sometimes when deleting, a child page can have zero cells.  In those
7216 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7217 ** entries, shift down.  The end result is that each ixNx[] entry should
7218 ** be larger than the previous
7219 */
7220 typedef struct CellArray CellArray;
7221 struct CellArray {
7222   int nCell;              /* Number of cells in apCell[] */
7223   MemPage *pRef;          /* Reference page */
7224   u8 **apCell;            /* All cells begin balanced */
7225   u16 *szCell;            /* Local size of all cells in apCell[] */
7226   u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
7227   int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
7228 };
7229 
7230 /*
7231 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7232 ** computed.
7233 */
7234 static void populateCellCache(CellArray *p, int idx, int N){
7235   assert( idx>=0 && idx+N<=p->nCell );
7236   while( N>0 ){
7237     assert( p->apCell[idx]!=0 );
7238     if( p->szCell[idx]==0 ){
7239       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
7240     }else{
7241       assert( CORRUPT_DB ||
7242               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
7243     }
7244     idx++;
7245     N--;
7246   }
7247 }
7248 
7249 /*
7250 ** Return the size of the Nth element of the cell array
7251 */
7252 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7253   assert( N>=0 && N<p->nCell );
7254   assert( p->szCell[N]==0 );
7255   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7256   return p->szCell[N];
7257 }
7258 static u16 cachedCellSize(CellArray *p, int N){
7259   assert( N>=0 && N<p->nCell );
7260   if( p->szCell[N] ) return p->szCell[N];
7261   return computeCellSize(p, N);
7262 }
7263 
7264 /*
7265 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7266 ** szCell[] array contains the size in bytes of each cell. This function
7267 ** replaces the current contents of page pPg with the contents of the cell
7268 ** array.
7269 **
7270 ** Some of the cells in apCell[] may currently be stored in pPg. This
7271 ** function works around problems caused by this by making a copy of any
7272 ** such cells before overwriting the page data.
7273 **
7274 ** The MemPage.nFree field is invalidated by this function. It is the
7275 ** responsibility of the caller to set it correctly.
7276 */
7277 static int rebuildPage(
7278   CellArray *pCArray,             /* Content to be added to page pPg */
7279   int iFirst,                     /* First cell in pCArray to use */
7280   int nCell,                      /* Final number of cells on page */
7281   MemPage *pPg                    /* The page to be reconstructed */
7282 ){
7283   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
7284   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
7285   const int usableSize = pPg->pBt->usableSize;
7286   u8 * const pEnd = &aData[usableSize];
7287   int i = iFirst;                 /* Which cell to copy from pCArray*/
7288   u32 j;                          /* Start of cell content area */
7289   int iEnd = i+nCell;             /* Loop terminator */
7290   u8 *pCellptr = pPg->aCellIdx;
7291   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7292   u8 *pData;
7293   int k;                          /* Current slot in pCArray->apEnd[] */
7294   u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
7295 
7296   assert( i<iEnd );
7297   j = get2byte(&aData[hdr+5]);
7298   if( j>(u32)usableSize ){ j = 0; }
7299   memcpy(&pTmp[j], &aData[j], usableSize - j);
7300 
7301   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7302   pSrcEnd = pCArray->apEnd[k];
7303 
7304   pData = pEnd;
7305   while( 1/*exit by break*/ ){
7306     u8 *pCell = pCArray->apCell[i];
7307     u16 sz = pCArray->szCell[i];
7308     assert( sz>0 );
7309     if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7310       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7311       pCell = &pTmp[pCell - aData];
7312     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7313            && (uptr)(pCell)<(uptr)pSrcEnd
7314     ){
7315       return SQLITE_CORRUPT_BKPT;
7316     }
7317 
7318     pData -= sz;
7319     put2byte(pCellptr, (pData - aData));
7320     pCellptr += 2;
7321     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7322     memmove(pData, pCell, sz);
7323     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7324     i++;
7325     if( i>=iEnd ) break;
7326     if( pCArray->ixNx[k]<=i ){
7327       k++;
7328       pSrcEnd = pCArray->apEnd[k];
7329     }
7330   }
7331 
7332   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7333   pPg->nCell = nCell;
7334   pPg->nOverflow = 0;
7335 
7336   put2byte(&aData[hdr+1], 0);
7337   put2byte(&aData[hdr+3], pPg->nCell);
7338   put2byte(&aData[hdr+5], pData - aData);
7339   aData[hdr+7] = 0x00;
7340   return SQLITE_OK;
7341 }
7342 
7343 /*
7344 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7345 ** This function attempts to add the cells stored in the array to page pPg.
7346 ** If it cannot (because the page needs to be defragmented before the cells
7347 ** will fit), non-zero is returned. Otherwise, if the cells are added
7348 ** successfully, zero is returned.
7349 **
7350 ** Argument pCellptr points to the first entry in the cell-pointer array
7351 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7352 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7353 ** cell in the array. It is the responsibility of the caller to ensure
7354 ** that it is safe to overwrite this part of the cell-pointer array.
7355 **
7356 ** When this function is called, *ppData points to the start of the
7357 ** content area on page pPg. If the size of the content area is extended,
7358 ** *ppData is updated to point to the new start of the content area
7359 ** before returning.
7360 **
7361 ** Finally, argument pBegin points to the byte immediately following the
7362 ** end of the space required by this page for the cell-pointer area (for
7363 ** all cells - not just those inserted by the current call). If the content
7364 ** area must be extended to before this point in order to accomodate all
7365 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7366 */
7367 static int pageInsertArray(
7368   MemPage *pPg,                   /* Page to add cells to */
7369   u8 *pBegin,                     /* End of cell-pointer array */
7370   u8 **ppData,                    /* IN/OUT: Page content-area pointer */
7371   u8 *pCellptr,                   /* Pointer to cell-pointer area */
7372   int iFirst,                     /* Index of first cell to add */
7373   int nCell,                      /* Number of cells to add to pPg */
7374   CellArray *pCArray              /* Array of cells */
7375 ){
7376   int i = iFirst;                 /* Loop counter - cell index to insert */
7377   u8 *aData = pPg->aData;         /* Complete page */
7378   u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
7379   int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
7380   int k;                          /* Current slot in pCArray->apEnd[] */
7381   u8 *pEnd;                       /* Maximum extent of cell data */
7382   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
7383   if( iEnd<=iFirst ) return 0;
7384   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7385   pEnd = pCArray->apEnd[k];
7386   while( 1 /*Exit by break*/ ){
7387     int sz, rc;
7388     u8 *pSlot;
7389     assert( pCArray->szCell[i]!=0 );
7390     sz = pCArray->szCell[i];
7391     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7392       if( (pData - pBegin)<sz ) return 1;
7393       pData -= sz;
7394       pSlot = pData;
7395     }
7396     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7397     ** database.  But they might for a corrupt database.  Hence use memmove()
7398     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7399     assert( (pSlot+sz)<=pCArray->apCell[i]
7400          || pSlot>=(pCArray->apCell[i]+sz)
7401          || CORRUPT_DB );
7402     if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7403      && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7404     ){
7405       assert( CORRUPT_DB );
7406       (void)SQLITE_CORRUPT_BKPT;
7407       return 1;
7408     }
7409     memmove(pSlot, pCArray->apCell[i], sz);
7410     put2byte(pCellptr, (pSlot - aData));
7411     pCellptr += 2;
7412     i++;
7413     if( i>=iEnd ) break;
7414     if( pCArray->ixNx[k]<=i ){
7415       k++;
7416       pEnd = pCArray->apEnd[k];
7417     }
7418   }
7419   *ppData = pData;
7420   return 0;
7421 }
7422 
7423 /*
7424 ** The pCArray object contains pointers to b-tree cells and their sizes.
7425 **
7426 ** This function adds the space associated with each cell in the array
7427 ** that is currently stored within the body of pPg to the pPg free-list.
7428 ** The cell-pointers and other fields of the page are not updated.
7429 **
7430 ** This function returns the total number of cells added to the free-list.
7431 */
7432 static int pageFreeArray(
7433   MemPage *pPg,                   /* Page to edit */
7434   int iFirst,                     /* First cell to delete */
7435   int nCell,                      /* Cells to delete */
7436   CellArray *pCArray              /* Array of cells */
7437 ){
7438   u8 * const aData = pPg->aData;
7439   u8 * const pEnd = &aData[pPg->pBt->usableSize];
7440   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7441   int nRet = 0;
7442   int i;
7443   int iEnd = iFirst + nCell;
7444   u8 *pFree = 0;
7445   int szFree = 0;
7446 
7447   for(i=iFirst; i<iEnd; i++){
7448     u8 *pCell = pCArray->apCell[i];
7449     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7450       int sz;
7451       /* No need to use cachedCellSize() here.  The sizes of all cells that
7452       ** are to be freed have already been computing while deciding which
7453       ** cells need freeing */
7454       sz = pCArray->szCell[i];  assert( sz>0 );
7455       if( pFree!=(pCell + sz) ){
7456         if( pFree ){
7457           assert( pFree>aData && (pFree - aData)<65536 );
7458           freeSpace(pPg, (u16)(pFree - aData), szFree);
7459         }
7460         pFree = pCell;
7461         szFree = sz;
7462         if( pFree+sz>pEnd ){
7463           return 0;
7464         }
7465       }else{
7466         pFree = pCell;
7467         szFree += sz;
7468       }
7469       nRet++;
7470     }
7471   }
7472   if( pFree ){
7473     assert( pFree>aData && (pFree - aData)<65536 );
7474     freeSpace(pPg, (u16)(pFree - aData), szFree);
7475   }
7476   return nRet;
7477 }
7478 
7479 /*
7480 ** pCArray contains pointers to and sizes of all cells in the page being
7481 ** balanced.  The current page, pPg, has pPg->nCell cells starting with
7482 ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
7483 ** starting at apCell[iNew].
7484 **
7485 ** This routine makes the necessary adjustments to pPg so that it contains
7486 ** the correct cells after being balanced.
7487 **
7488 ** The pPg->nFree field is invalid when this function returns. It is the
7489 ** responsibility of the caller to set it correctly.
7490 */
7491 static int editPage(
7492   MemPage *pPg,                   /* Edit this page */
7493   int iOld,                       /* Index of first cell currently on page */
7494   int iNew,                       /* Index of new first cell on page */
7495   int nNew,                       /* Final number of cells on page */
7496   CellArray *pCArray              /* Array of cells and sizes */
7497 ){
7498   u8 * const aData = pPg->aData;
7499   const int hdr = pPg->hdrOffset;
7500   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7501   int nCell = pPg->nCell;       /* Cells stored on pPg */
7502   u8 *pData;
7503   u8 *pCellptr;
7504   int i;
7505   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7506   int iNewEnd = iNew + nNew;
7507 
7508 #ifdef SQLITE_DEBUG
7509   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7510   memcpy(pTmp, aData, pPg->pBt->usableSize);
7511 #endif
7512 
7513   /* Remove cells from the start and end of the page */
7514   assert( nCell>=0 );
7515   if( iOld<iNew ){
7516     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7517     if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7518     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7519     nCell -= nShift;
7520   }
7521   if( iNewEnd < iOldEnd ){
7522     int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7523     assert( nCell>=nTail );
7524     nCell -= nTail;
7525   }
7526 
7527   pData = &aData[get2byteNotZero(&aData[hdr+5])];
7528   if( pData<pBegin ) goto editpage_fail;
7529   if( pData>pPg->aDataEnd ) goto editpage_fail;
7530 
7531   /* Add cells to the start of the page */
7532   if( iNew<iOld ){
7533     int nAdd = MIN(nNew,iOld-iNew);
7534     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7535     assert( nAdd>=0 );
7536     pCellptr = pPg->aCellIdx;
7537     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7538     if( pageInsertArray(
7539           pPg, pBegin, &pData, pCellptr,
7540           iNew, nAdd, pCArray
7541     ) ) goto editpage_fail;
7542     nCell += nAdd;
7543   }
7544 
7545   /* Add any overflow cells */
7546   for(i=0; i<pPg->nOverflow; i++){
7547     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7548     if( iCell>=0 && iCell<nNew ){
7549       pCellptr = &pPg->aCellIdx[iCell * 2];
7550       if( nCell>iCell ){
7551         memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7552       }
7553       nCell++;
7554       cachedCellSize(pCArray, iCell+iNew);
7555       if( pageInsertArray(
7556             pPg, pBegin, &pData, pCellptr,
7557             iCell+iNew, 1, pCArray
7558       ) ) goto editpage_fail;
7559     }
7560   }
7561 
7562   /* Append cells to the end of the page */
7563   assert( nCell>=0 );
7564   pCellptr = &pPg->aCellIdx[nCell*2];
7565   if( pageInsertArray(
7566         pPg, pBegin, &pData, pCellptr,
7567         iNew+nCell, nNew-nCell, pCArray
7568   ) ) goto editpage_fail;
7569 
7570   pPg->nCell = nNew;
7571   pPg->nOverflow = 0;
7572 
7573   put2byte(&aData[hdr+3], pPg->nCell);
7574   put2byte(&aData[hdr+5], pData - aData);
7575 
7576 #ifdef SQLITE_DEBUG
7577   for(i=0; i<nNew && !CORRUPT_DB; i++){
7578     u8 *pCell = pCArray->apCell[i+iNew];
7579     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7580     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7581       pCell = &pTmp[pCell - aData];
7582     }
7583     assert( 0==memcmp(pCell, &aData[iOff],
7584             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7585   }
7586 #endif
7587 
7588   return SQLITE_OK;
7589  editpage_fail:
7590   /* Unable to edit this page. Rebuild it from scratch instead. */
7591   populateCellCache(pCArray, iNew, nNew);
7592   return rebuildPage(pCArray, iNew, nNew, pPg);
7593 }
7594 
7595 
7596 #ifndef SQLITE_OMIT_QUICKBALANCE
7597 /*
7598 ** This version of balance() handles the common special case where
7599 ** a new entry is being inserted on the extreme right-end of the
7600 ** tree, in other words, when the new entry will become the largest
7601 ** entry in the tree.
7602 **
7603 ** Instead of trying to balance the 3 right-most leaf pages, just add
7604 ** a new page to the right-hand side and put the one new entry in
7605 ** that page.  This leaves the right side of the tree somewhat
7606 ** unbalanced.  But odds are that we will be inserting new entries
7607 ** at the end soon afterwards so the nearly empty page will quickly
7608 ** fill up.  On average.
7609 **
7610 ** pPage is the leaf page which is the right-most page in the tree.
7611 ** pParent is its parent.  pPage must have a single overflow entry
7612 ** which is also the right-most entry on the page.
7613 **
7614 ** The pSpace buffer is used to store a temporary copy of the divider
7615 ** cell that will be inserted into pParent. Such a cell consists of a 4
7616 ** byte page number followed by a variable length integer. In other
7617 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7618 ** least 13 bytes in size.
7619 */
7620 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7621   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7622   MemPage *pNew;                       /* Newly allocated page */
7623   int rc;                              /* Return Code */
7624   Pgno pgnoNew;                        /* Page number of pNew */
7625 
7626   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7627   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7628   assert( pPage->nOverflow==1 );
7629 
7630   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
7631   assert( pPage->nFree>=0 );
7632   assert( pParent->nFree>=0 );
7633 
7634   /* Allocate a new page. This page will become the right-sibling of
7635   ** pPage. Make the parent page writable, so that the new divider cell
7636   ** may be inserted. If both these operations are successful, proceed.
7637   */
7638   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7639 
7640   if( rc==SQLITE_OK ){
7641 
7642     u8 *pOut = &pSpace[4];
7643     u8 *pCell = pPage->apOvfl[0];
7644     u16 szCell = pPage->xCellSize(pPage, pCell);
7645     u8 *pStop;
7646     CellArray b;
7647 
7648     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7649     assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7650     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7651     b.nCell = 1;
7652     b.pRef = pPage;
7653     b.apCell = &pCell;
7654     b.szCell = &szCell;
7655     b.apEnd[0] = pPage->aDataEnd;
7656     b.ixNx[0] = 2;
7657     rc = rebuildPage(&b, 0, 1, pNew);
7658     if( NEVER(rc) ){
7659       releasePage(pNew);
7660       return rc;
7661     }
7662     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7663 
7664     /* If this is an auto-vacuum database, update the pointer map
7665     ** with entries for the new page, and any pointer from the
7666     ** cell on the page to an overflow page. If either of these
7667     ** operations fails, the return code is set, but the contents
7668     ** of the parent page are still manipulated by thh code below.
7669     ** That is Ok, at this point the parent page is guaranteed to
7670     ** be marked as dirty. Returning an error code will cause a
7671     ** rollback, undoing any changes made to the parent page.
7672     */
7673     if( ISAUTOVACUUM ){
7674       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7675       if( szCell>pNew->minLocal ){
7676         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7677       }
7678     }
7679 
7680     /* Create a divider cell to insert into pParent. The divider cell
7681     ** consists of a 4-byte page number (the page number of pPage) and
7682     ** a variable length key value (which must be the same value as the
7683     ** largest key on pPage).
7684     **
7685     ** To find the largest key value on pPage, first find the right-most
7686     ** cell on pPage. The first two fields of this cell are the
7687     ** record-length (a variable length integer at most 32-bits in size)
7688     ** and the key value (a variable length integer, may have any value).
7689     ** The first of the while(...) loops below skips over the record-length
7690     ** field. The second while(...) loop copies the key value from the
7691     ** cell on pPage into the pSpace buffer.
7692     */
7693     pCell = findCell(pPage, pPage->nCell-1);
7694     pStop = &pCell[9];
7695     while( (*(pCell++)&0x80) && pCell<pStop );
7696     pStop = &pCell[9];
7697     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7698 
7699     /* Insert the new divider cell into pParent. */
7700     if( rc==SQLITE_OK ){
7701       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7702                    0, pPage->pgno, &rc);
7703     }
7704 
7705     /* Set the right-child pointer of pParent to point to the new page. */
7706     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7707 
7708     /* Release the reference to the new page. */
7709     releasePage(pNew);
7710   }
7711 
7712   return rc;
7713 }
7714 #endif /* SQLITE_OMIT_QUICKBALANCE */
7715 
7716 #if 0
7717 /*
7718 ** This function does not contribute anything to the operation of SQLite.
7719 ** it is sometimes activated temporarily while debugging code responsible
7720 ** for setting pointer-map entries.
7721 */
7722 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7723   int i, j;
7724   for(i=0; i<nPage; i++){
7725     Pgno n;
7726     u8 e;
7727     MemPage *pPage = apPage[i];
7728     BtShared *pBt = pPage->pBt;
7729     assert( pPage->isInit );
7730 
7731     for(j=0; j<pPage->nCell; j++){
7732       CellInfo info;
7733       u8 *z;
7734 
7735       z = findCell(pPage, j);
7736       pPage->xParseCell(pPage, z, &info);
7737       if( info.nLocal<info.nPayload ){
7738         Pgno ovfl = get4byte(&z[info.nSize-4]);
7739         ptrmapGet(pBt, ovfl, &e, &n);
7740         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7741       }
7742       if( !pPage->leaf ){
7743         Pgno child = get4byte(z);
7744         ptrmapGet(pBt, child, &e, &n);
7745         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7746       }
7747     }
7748     if( !pPage->leaf ){
7749       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7750       ptrmapGet(pBt, child, &e, &n);
7751       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7752     }
7753   }
7754   return 1;
7755 }
7756 #endif
7757 
7758 /*
7759 ** This function is used to copy the contents of the b-tree node stored
7760 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7761 ** the pointer-map entries for each child page are updated so that the
7762 ** parent page stored in the pointer map is page pTo. If pFrom contained
7763 ** any cells with overflow page pointers, then the corresponding pointer
7764 ** map entries are also updated so that the parent page is page pTo.
7765 **
7766 ** If pFrom is currently carrying any overflow cells (entries in the
7767 ** MemPage.apOvfl[] array), they are not copied to pTo.
7768 **
7769 ** Before returning, page pTo is reinitialized using btreeInitPage().
7770 **
7771 ** The performance of this function is not critical. It is only used by
7772 ** the balance_shallower() and balance_deeper() procedures, neither of
7773 ** which are called often under normal circumstances.
7774 */
7775 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7776   if( (*pRC)==SQLITE_OK ){
7777     BtShared * const pBt = pFrom->pBt;
7778     u8 * const aFrom = pFrom->aData;
7779     u8 * const aTo = pTo->aData;
7780     int const iFromHdr = pFrom->hdrOffset;
7781     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7782     int rc;
7783     int iData;
7784 
7785 
7786     assert( pFrom->isInit );
7787     assert( pFrom->nFree>=iToHdr );
7788     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7789 
7790     /* Copy the b-tree node content from page pFrom to page pTo. */
7791     iData = get2byte(&aFrom[iFromHdr+5]);
7792     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7793     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7794 
7795     /* Reinitialize page pTo so that the contents of the MemPage structure
7796     ** match the new data. The initialization of pTo can actually fail under
7797     ** fairly obscure circumstances, even though it is a copy of initialized
7798     ** page pFrom.
7799     */
7800     pTo->isInit = 0;
7801     rc = btreeInitPage(pTo);
7802     if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7803     if( rc!=SQLITE_OK ){
7804       *pRC = rc;
7805       return;
7806     }
7807 
7808     /* If this is an auto-vacuum database, update the pointer-map entries
7809     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7810     */
7811     if( ISAUTOVACUUM ){
7812       *pRC = setChildPtrmaps(pTo);
7813     }
7814   }
7815 }
7816 
7817 /*
7818 ** This routine redistributes cells on the iParentIdx'th child of pParent
7819 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7820 ** same amount of free space. Usually a single sibling on either side of the
7821 ** page are used in the balancing, though both siblings might come from one
7822 ** side if the page is the first or last child of its parent. If the page
7823 ** has fewer than 2 siblings (something which can only happen if the page
7824 ** is a root page or a child of a root page) then all available siblings
7825 ** participate in the balancing.
7826 **
7827 ** The number of siblings of the page might be increased or decreased by
7828 ** one or two in an effort to keep pages nearly full but not over full.
7829 **
7830 ** Note that when this routine is called, some of the cells on the page
7831 ** might not actually be stored in MemPage.aData[]. This can happen
7832 ** if the page is overfull. This routine ensures that all cells allocated
7833 ** to the page and its siblings fit into MemPage.aData[] before returning.
7834 **
7835 ** In the course of balancing the page and its siblings, cells may be
7836 ** inserted into or removed from the parent page (pParent). Doing so
7837 ** may cause the parent page to become overfull or underfull. If this
7838 ** happens, it is the responsibility of the caller to invoke the correct
7839 ** balancing routine to fix this problem (see the balance() routine).
7840 **
7841 ** If this routine fails for any reason, it might leave the database
7842 ** in a corrupted state. So if this routine fails, the database should
7843 ** be rolled back.
7844 **
7845 ** The third argument to this function, aOvflSpace, is a pointer to a
7846 ** buffer big enough to hold one page. If while inserting cells into the parent
7847 ** page (pParent) the parent page becomes overfull, this buffer is
7848 ** used to store the parent's overflow cells. Because this function inserts
7849 ** a maximum of four divider cells into the parent page, and the maximum
7850 ** size of a cell stored within an internal node is always less than 1/4
7851 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7852 ** enough for all overflow cells.
7853 **
7854 ** If aOvflSpace is set to a null pointer, this function returns
7855 ** SQLITE_NOMEM.
7856 */
7857 static int balance_nonroot(
7858   MemPage *pParent,               /* Parent page of siblings being balanced */
7859   int iParentIdx,                 /* Index of "the page" in pParent */
7860   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7861   int isRoot,                     /* True if pParent is a root-page */
7862   int bBulk                       /* True if this call is part of a bulk load */
7863 ){
7864   BtShared *pBt;               /* The whole database */
7865   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7866   int nNew = 0;                /* Number of pages in apNew[] */
7867   int nOld;                    /* Number of pages in apOld[] */
7868   int i, j, k;                 /* Loop counters */
7869   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7870   int rc = SQLITE_OK;          /* The return code */
7871   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7872   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7873   int usableSpace;             /* Bytes in pPage beyond the header */
7874   int pageFlags;               /* Value of pPage->aData[0] */
7875   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7876   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7877   int szScratch;               /* Size of scratch memory requested */
7878   MemPage *apOld[NB];          /* pPage and up to two siblings */
7879   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7880   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7881   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7882   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7883   int cntOld[NB+2];            /* Old index in b.apCell[] */
7884   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7885   u8 *aSpace1;                 /* Space for copies of dividers cells */
7886   Pgno pgno;                   /* Temp var to store a page number in */
7887   u8 abDone[NB+2];             /* True after i'th new page is populated */
7888   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7889   CellArray b;                 /* Parsed information on cells being balanced */
7890 
7891   memset(abDone, 0, sizeof(abDone));
7892   memset(&b, 0, sizeof(b));
7893   pBt = pParent->pBt;
7894   assert( sqlite3_mutex_held(pBt->mutex) );
7895   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7896 
7897   /* At this point pParent may have at most one overflow cell. And if
7898   ** this overflow cell is present, it must be the cell with
7899   ** index iParentIdx. This scenario comes about when this function
7900   ** is called (indirectly) from sqlite3BtreeDelete().
7901   */
7902   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7903   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7904 
7905   if( !aOvflSpace ){
7906     return SQLITE_NOMEM_BKPT;
7907   }
7908   assert( pParent->nFree>=0 );
7909 
7910   /* Find the sibling pages to balance. Also locate the cells in pParent
7911   ** that divide the siblings. An attempt is made to find NN siblings on
7912   ** either side of pPage. More siblings are taken from one side, however,
7913   ** if there are fewer than NN siblings on the other side. If pParent
7914   ** has NB or fewer children then all children of pParent are taken.
7915   **
7916   ** This loop also drops the divider cells from the parent page. This
7917   ** way, the remainder of the function does not have to deal with any
7918   ** overflow cells in the parent page, since if any existed they will
7919   ** have already been removed.
7920   */
7921   i = pParent->nOverflow + pParent->nCell;
7922   if( i<2 ){
7923     nxDiv = 0;
7924   }else{
7925     assert( bBulk==0 || bBulk==1 );
7926     if( iParentIdx==0 ){
7927       nxDiv = 0;
7928     }else if( iParentIdx==i ){
7929       nxDiv = i-2+bBulk;
7930     }else{
7931       nxDiv = iParentIdx-1;
7932     }
7933     i = 2-bBulk;
7934   }
7935   nOld = i+1;
7936   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7937     pRight = &pParent->aData[pParent->hdrOffset+8];
7938   }else{
7939     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7940   }
7941   pgno = get4byte(pRight);
7942   while( 1 ){
7943     if( rc==SQLITE_OK ){
7944       rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7945     }
7946     if( rc ){
7947       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7948       goto balance_cleanup;
7949     }
7950     if( apOld[i]->nFree<0 ){
7951       rc = btreeComputeFreeSpace(apOld[i]);
7952       if( rc ){
7953         memset(apOld, 0, (i)*sizeof(MemPage*));
7954         goto balance_cleanup;
7955       }
7956     }
7957     nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
7958     if( (i--)==0 ) break;
7959 
7960     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7961       apDiv[i] = pParent->apOvfl[0];
7962       pgno = get4byte(apDiv[i]);
7963       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7964       pParent->nOverflow = 0;
7965     }else{
7966       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7967       pgno = get4byte(apDiv[i]);
7968       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7969 
7970       /* Drop the cell from the parent page. apDiv[i] still points to
7971       ** the cell within the parent, even though it has been dropped.
7972       ** This is safe because dropping a cell only overwrites the first
7973       ** four bytes of it, and this function does not need the first
7974       ** four bytes of the divider cell. So the pointer is safe to use
7975       ** later on.
7976       **
7977       ** But not if we are in secure-delete mode. In secure-delete mode,
7978       ** the dropCell() routine will overwrite the entire cell with zeroes.
7979       ** In this case, temporarily copy the cell into the aOvflSpace[]
7980       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7981       ** is allocated.  */
7982       if( pBt->btsFlags & BTS_FAST_SECURE ){
7983         int iOff;
7984 
7985         /* If the following if() condition is not true, the db is corrupted.
7986         ** The call to dropCell() below will detect this.  */
7987         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7988         if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7989           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7990           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7991         }
7992       }
7993       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7994     }
7995   }
7996 
7997   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7998   ** alignment */
7999   nMaxCells = (nMaxCells + 3)&~3;
8000 
8001   /*
8002   ** Allocate space for memory structures
8003   */
8004   szScratch =
8005        nMaxCells*sizeof(u8*)                       /* b.apCell */
8006      + nMaxCells*sizeof(u16)                       /* b.szCell */
8007      + pBt->pageSize;                              /* aSpace1 */
8008 
8009   assert( szScratch<=7*(int)pBt->pageSize );
8010   b.apCell = sqlite3StackAllocRaw(0, szScratch );
8011   if( b.apCell==0 ){
8012     rc = SQLITE_NOMEM_BKPT;
8013     goto balance_cleanup;
8014   }
8015   b.szCell = (u16*)&b.apCell[nMaxCells];
8016   aSpace1 = (u8*)&b.szCell[nMaxCells];
8017   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
8018 
8019   /*
8020   ** Load pointers to all cells on sibling pages and the divider cells
8021   ** into the local b.apCell[] array.  Make copies of the divider cells
8022   ** into space obtained from aSpace1[]. The divider cells have already
8023   ** been removed from pParent.
8024   **
8025   ** If the siblings are on leaf pages, then the child pointers of the
8026   ** divider cells are stripped from the cells before they are copied
8027   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
8028   ** child pointers.  If siblings are not leaves, then all cell in
8029   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
8030   ** are alike.
8031   **
8032   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
8033   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
8034   */
8035   b.pRef = apOld[0];
8036   leafCorrection = b.pRef->leaf*4;
8037   leafData = b.pRef->intKeyLeaf;
8038   for(i=0; i<nOld; i++){
8039     MemPage *pOld = apOld[i];
8040     int limit = pOld->nCell;
8041     u8 *aData = pOld->aData;
8042     u16 maskPage = pOld->maskPage;
8043     u8 *piCell = aData + pOld->cellOffset;
8044     u8 *piEnd;
8045     VVA_ONLY( int nCellAtStart = b.nCell; )
8046 
8047     /* Verify that all sibling pages are of the same "type" (table-leaf,
8048     ** table-interior, index-leaf, or index-interior).
8049     */
8050     if( pOld->aData[0]!=apOld[0]->aData[0] ){
8051       rc = SQLITE_CORRUPT_BKPT;
8052       goto balance_cleanup;
8053     }
8054 
8055     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
8056     ** contains overflow cells, include them in the b.apCell[] array
8057     ** in the correct spot.
8058     **
8059     ** Note that when there are multiple overflow cells, it is always the
8060     ** case that they are sequential and adjacent.  This invariant arises
8061     ** because multiple overflows can only occurs when inserting divider
8062     ** cells into a parent on a prior balance, and divider cells are always
8063     ** adjacent and are inserted in order.  There is an assert() tagged
8064     ** with "NOTE 1" in the overflow cell insertion loop to prove this
8065     ** invariant.
8066     **
8067     ** This must be done in advance.  Once the balance starts, the cell
8068     ** offset section of the btree page will be overwritten and we will no
8069     ** long be able to find the cells if a pointer to each cell is not saved
8070     ** first.
8071     */
8072     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
8073     if( pOld->nOverflow>0 ){
8074       if( NEVER(limit<pOld->aiOvfl[0]) ){
8075         rc = SQLITE_CORRUPT_BKPT;
8076         goto balance_cleanup;
8077       }
8078       limit = pOld->aiOvfl[0];
8079       for(j=0; j<limit; j++){
8080         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8081         piCell += 2;
8082         b.nCell++;
8083       }
8084       for(k=0; k<pOld->nOverflow; k++){
8085         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
8086         b.apCell[b.nCell] = pOld->apOvfl[k];
8087         b.nCell++;
8088       }
8089     }
8090     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8091     while( piCell<piEnd ){
8092       assert( b.nCell<nMaxCells );
8093       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8094       piCell += 2;
8095       b.nCell++;
8096     }
8097     assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
8098 
8099     cntOld[i] = b.nCell;
8100     if( i<nOld-1 && !leafData){
8101       u16 sz = (u16)szNew[i];
8102       u8 *pTemp;
8103       assert( b.nCell<nMaxCells );
8104       b.szCell[b.nCell] = sz;
8105       pTemp = &aSpace1[iSpace1];
8106       iSpace1 += sz;
8107       assert( sz<=pBt->maxLocal+23 );
8108       assert( iSpace1 <= (int)pBt->pageSize );
8109       memcpy(pTemp, apDiv[i], sz);
8110       b.apCell[b.nCell] = pTemp+leafCorrection;
8111       assert( leafCorrection==0 || leafCorrection==4 );
8112       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
8113       if( !pOld->leaf ){
8114         assert( leafCorrection==0 );
8115         assert( pOld->hdrOffset==0 || CORRUPT_DB );
8116         /* The right pointer of the child page pOld becomes the left
8117         ** pointer of the divider cell */
8118         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
8119       }else{
8120         assert( leafCorrection==4 );
8121         while( b.szCell[b.nCell]<4 ){
8122           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8123           ** does exist, pad it with 0x00 bytes. */
8124           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8125           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
8126           aSpace1[iSpace1++] = 0x00;
8127           b.szCell[b.nCell]++;
8128         }
8129       }
8130       b.nCell++;
8131     }
8132   }
8133 
8134   /*
8135   ** Figure out the number of pages needed to hold all b.nCell cells.
8136   ** Store this number in "k".  Also compute szNew[] which is the total
8137   ** size of all cells on the i-th page and cntNew[] which is the index
8138   ** in b.apCell[] of the cell that divides page i from page i+1.
8139   ** cntNew[k] should equal b.nCell.
8140   **
8141   ** Values computed by this block:
8142   **
8143   **           k: The total number of sibling pages
8144   **    szNew[i]: Spaced used on the i-th sibling page.
8145   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
8146   **              the right of the i-th sibling page.
8147   ** usableSpace: Number of bytes of space available on each sibling.
8148   **
8149   */
8150   usableSpace = pBt->usableSize - 12 + leafCorrection;
8151   for(i=k=0; i<nOld; i++, k++){
8152     MemPage *p = apOld[i];
8153     b.apEnd[k] = p->aDataEnd;
8154     b.ixNx[k] = cntOld[i];
8155     if( k && b.ixNx[k]==b.ixNx[k-1] ){
8156       k--;  /* Omit b.ixNx[] entry for child pages with no cells */
8157     }
8158     if( !leafData ){
8159       k++;
8160       b.apEnd[k] = pParent->aDataEnd;
8161       b.ixNx[k] = cntOld[i]+1;
8162     }
8163     assert( p->nFree>=0 );
8164     szNew[i] = usableSpace - p->nFree;
8165     for(j=0; j<p->nOverflow; j++){
8166       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8167     }
8168     cntNew[i] = cntOld[i];
8169   }
8170   k = nOld;
8171   for(i=0; i<k; i++){
8172     int sz;
8173     while( szNew[i]>usableSpace ){
8174       if( i+1>=k ){
8175         k = i+2;
8176         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8177         szNew[k-1] = 0;
8178         cntNew[k-1] = b.nCell;
8179       }
8180       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8181       szNew[i] -= sz;
8182       if( !leafData ){
8183         if( cntNew[i]<b.nCell ){
8184           sz = 2 + cachedCellSize(&b, cntNew[i]);
8185         }else{
8186           sz = 0;
8187         }
8188       }
8189       szNew[i+1] += sz;
8190       cntNew[i]--;
8191     }
8192     while( cntNew[i]<b.nCell ){
8193       sz = 2 + cachedCellSize(&b, cntNew[i]);
8194       if( szNew[i]+sz>usableSpace ) break;
8195       szNew[i] += sz;
8196       cntNew[i]++;
8197       if( !leafData ){
8198         if( cntNew[i]<b.nCell ){
8199           sz = 2 + cachedCellSize(&b, cntNew[i]);
8200         }else{
8201           sz = 0;
8202         }
8203       }
8204       szNew[i+1] -= sz;
8205     }
8206     if( cntNew[i]>=b.nCell ){
8207       k = i+1;
8208     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8209       rc = SQLITE_CORRUPT_BKPT;
8210       goto balance_cleanup;
8211     }
8212   }
8213 
8214   /*
8215   ** The packing computed by the previous block is biased toward the siblings
8216   ** on the left side (siblings with smaller keys). The left siblings are
8217   ** always nearly full, while the right-most sibling might be nearly empty.
8218   ** The next block of code attempts to adjust the packing of siblings to
8219   ** get a better balance.
8220   **
8221   ** This adjustment is more than an optimization.  The packing above might
8222   ** be so out of balance as to be illegal.  For example, the right-most
8223   ** sibling might be completely empty.  This adjustment is not optional.
8224   */
8225   for(i=k-1; i>0; i--){
8226     int szRight = szNew[i];  /* Size of sibling on the right */
8227     int szLeft = szNew[i-1]; /* Size of sibling on the left */
8228     int r;              /* Index of right-most cell in left sibling */
8229     int d;              /* Index of first cell to the left of right sibling */
8230 
8231     r = cntNew[i-1] - 1;
8232     d = r + 1 - leafData;
8233     (void)cachedCellSize(&b, d);
8234     do{
8235       assert( d<nMaxCells );
8236       assert( r<nMaxCells );
8237       (void)cachedCellSize(&b, r);
8238       if( szRight!=0
8239        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
8240         break;
8241       }
8242       szRight += b.szCell[d] + 2;
8243       szLeft -= b.szCell[r] + 2;
8244       cntNew[i-1] = r;
8245       r--;
8246       d--;
8247     }while( r>=0 );
8248     szNew[i] = szRight;
8249     szNew[i-1] = szLeft;
8250     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8251       rc = SQLITE_CORRUPT_BKPT;
8252       goto balance_cleanup;
8253     }
8254   }
8255 
8256   /* Sanity check:  For a non-corrupt database file one of the follwing
8257   ** must be true:
8258   **    (1) We found one or more cells (cntNew[0])>0), or
8259   **    (2) pPage is a virtual root page.  A virtual root page is when
8260   **        the real root page is page 1 and we are the only child of
8261   **        that page.
8262   */
8263   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8264   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
8265     apOld[0]->pgno, apOld[0]->nCell,
8266     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8267     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8268   ));
8269 
8270   /*
8271   ** Allocate k new pages.  Reuse old pages where possible.
8272   */
8273   pageFlags = apOld[0]->aData[0];
8274   for(i=0; i<k; i++){
8275     MemPage *pNew;
8276     if( i<nOld ){
8277       pNew = apNew[i] = apOld[i];
8278       apOld[i] = 0;
8279       rc = sqlite3PagerWrite(pNew->pDbPage);
8280       nNew++;
8281       if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8282        && rc==SQLITE_OK
8283       ){
8284         rc = SQLITE_CORRUPT_BKPT;
8285       }
8286       if( rc ) goto balance_cleanup;
8287     }else{
8288       assert( i>0 );
8289       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8290       if( rc ) goto balance_cleanup;
8291       zeroPage(pNew, pageFlags);
8292       apNew[i] = pNew;
8293       nNew++;
8294       cntOld[i] = b.nCell;
8295 
8296       /* Set the pointer-map entry for the new sibling page. */
8297       if( ISAUTOVACUUM ){
8298         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8299         if( rc!=SQLITE_OK ){
8300           goto balance_cleanup;
8301         }
8302       }
8303     }
8304   }
8305 
8306   /*
8307   ** Reassign page numbers so that the new pages are in ascending order.
8308   ** This helps to keep entries in the disk file in order so that a scan
8309   ** of the table is closer to a linear scan through the file. That in turn
8310   ** helps the operating system to deliver pages from the disk more rapidly.
8311   **
8312   ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8313   ** (5), that is not a performance concern.
8314   **
8315   ** When NB==3, this one optimization makes the database about 25% faster
8316   ** for large insertions and deletions.
8317   */
8318   for(i=0; i<nNew; i++){
8319     aPgno[i] = apNew[i]->pgno;
8320     assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8321     assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
8322   }
8323   for(i=0; i<nNew-1; i++){
8324     int iB = i;
8325     for(j=i+1; j<nNew; j++){
8326       if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
8327     }
8328 
8329     /* If apNew[i] has a page number that is bigger than any of the
8330     ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8331     ** entry that has the smallest page number (which we know to be
8332     ** entry apNew[iB]).
8333     */
8334     if( iB!=i ){
8335       Pgno pgnoA = apNew[i]->pgno;
8336       Pgno pgnoB = apNew[iB]->pgno;
8337       Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8338       u16 fgA = apNew[i]->pDbPage->flags;
8339       u16 fgB = apNew[iB]->pDbPage->flags;
8340       sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8341       sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8342       sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8343       apNew[i]->pgno = pgnoB;
8344       apNew[iB]->pgno = pgnoA;
8345     }
8346   }
8347 
8348   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8349          "%d(%d nc=%d) %d(%d nc=%d)\n",
8350     apNew[0]->pgno, szNew[0], cntNew[0],
8351     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8352     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8353     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8354     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8355     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8356     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8357     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8358     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8359   ));
8360 
8361   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8362   assert( nNew>=1 && nNew<=ArraySize(apNew) );
8363   assert( apNew[nNew-1]!=0 );
8364   put4byte(pRight, apNew[nNew-1]->pgno);
8365 
8366   /* If the sibling pages are not leaves, ensure that the right-child pointer
8367   ** of the right-most new sibling page is set to the value that was
8368   ** originally in the same field of the right-most old sibling page. */
8369   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8370     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8371     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8372   }
8373 
8374   /* Make any required updates to pointer map entries associated with
8375   ** cells stored on sibling pages following the balance operation. Pointer
8376   ** map entries associated with divider cells are set by the insertCell()
8377   ** routine. The associated pointer map entries are:
8378   **
8379   **   a) if the cell contains a reference to an overflow chain, the
8380   **      entry associated with the first page in the overflow chain, and
8381   **
8382   **   b) if the sibling pages are not leaves, the child page associated
8383   **      with the cell.
8384   **
8385   ** If the sibling pages are not leaves, then the pointer map entry
8386   ** associated with the right-child of each sibling may also need to be
8387   ** updated. This happens below, after the sibling pages have been
8388   ** populated, not here.
8389   */
8390   if( ISAUTOVACUUM ){
8391     MemPage *pOld;
8392     MemPage *pNew = pOld = apNew[0];
8393     int cntOldNext = pNew->nCell + pNew->nOverflow;
8394     int iNew = 0;
8395     int iOld = 0;
8396 
8397     for(i=0; i<b.nCell; i++){
8398       u8 *pCell = b.apCell[i];
8399       while( i==cntOldNext ){
8400         iOld++;
8401         assert( iOld<nNew || iOld<nOld );
8402         assert( iOld>=0 && iOld<NB );
8403         pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8404         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8405       }
8406       if( i==cntNew[iNew] ){
8407         pNew = apNew[++iNew];
8408         if( !leafData ) continue;
8409       }
8410 
8411       /* Cell pCell is destined for new sibling page pNew. Originally, it
8412       ** was either part of sibling page iOld (possibly an overflow cell),
8413       ** or else the divider cell to the left of sibling page iOld. So,
8414       ** if sibling page iOld had the same page number as pNew, and if
8415       ** pCell really was a part of sibling page iOld (not a divider or
8416       ** overflow cell), we can skip updating the pointer map entries.  */
8417       if( iOld>=nNew
8418        || pNew->pgno!=aPgno[iOld]
8419        || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8420       ){
8421         if( !leafCorrection ){
8422           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8423         }
8424         if( cachedCellSize(&b,i)>pNew->minLocal ){
8425           ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8426         }
8427         if( rc ) goto balance_cleanup;
8428       }
8429     }
8430   }
8431 
8432   /* Insert new divider cells into pParent. */
8433   for(i=0; i<nNew-1; i++){
8434     u8 *pCell;
8435     u8 *pTemp;
8436     int sz;
8437     u8 *pSrcEnd;
8438     MemPage *pNew = apNew[i];
8439     j = cntNew[i];
8440 
8441     assert( j<nMaxCells );
8442     assert( b.apCell[j]!=0 );
8443     pCell = b.apCell[j];
8444     sz = b.szCell[j] + leafCorrection;
8445     pTemp = &aOvflSpace[iOvflSpace];
8446     if( !pNew->leaf ){
8447       memcpy(&pNew->aData[8], pCell, 4);
8448     }else if( leafData ){
8449       /* If the tree is a leaf-data tree, and the siblings are leaves,
8450       ** then there is no divider cell in b.apCell[]. Instead, the divider
8451       ** cell consists of the integer key for the right-most cell of
8452       ** the sibling-page assembled above only.
8453       */
8454       CellInfo info;
8455       j--;
8456       pNew->xParseCell(pNew, b.apCell[j], &info);
8457       pCell = pTemp;
8458       sz = 4 + putVarint(&pCell[4], info.nKey);
8459       pTemp = 0;
8460     }else{
8461       pCell -= 4;
8462       /* Obscure case for non-leaf-data trees: If the cell at pCell was
8463       ** previously stored on a leaf node, and its reported size was 4
8464       ** bytes, then it may actually be smaller than this
8465       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8466       ** any cell). But it is important to pass the correct size to
8467       ** insertCell(), so reparse the cell now.
8468       **
8469       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8470       ** and WITHOUT ROWID tables with exactly one column which is the
8471       ** primary key.
8472       */
8473       if( b.szCell[j]==4 ){
8474         assert(leafCorrection==4);
8475         sz = pParent->xCellSize(pParent, pCell);
8476       }
8477     }
8478     iOvflSpace += sz;
8479     assert( sz<=pBt->maxLocal+23 );
8480     assert( iOvflSpace <= (int)pBt->pageSize );
8481     for(k=0; b.ixNx[k]<=j && ALWAYS(k<NB*2); k++){}
8482     pSrcEnd = b.apEnd[k];
8483     if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8484       rc = SQLITE_CORRUPT_BKPT;
8485       goto balance_cleanup;
8486     }
8487     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8488     if( rc!=SQLITE_OK ) goto balance_cleanup;
8489     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8490   }
8491 
8492   /* Now update the actual sibling pages. The order in which they are updated
8493   ** is important, as this code needs to avoid disrupting any page from which
8494   ** cells may still to be read. In practice, this means:
8495   **
8496   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8497   **      then it is not safe to update page apNew[iPg] until after
8498   **      the left-hand sibling apNew[iPg-1] has been updated.
8499   **
8500   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8501   **      then it is not safe to update page apNew[iPg] until after
8502   **      the right-hand sibling apNew[iPg+1] has been updated.
8503   **
8504   ** If neither of the above apply, the page is safe to update.
8505   **
8506   ** The iPg value in the following loop starts at nNew-1 goes down
8507   ** to 0, then back up to nNew-1 again, thus making two passes over
8508   ** the pages.  On the initial downward pass, only condition (1) above
8509   ** needs to be tested because (2) will always be true from the previous
8510   ** step.  On the upward pass, both conditions are always true, so the
8511   ** upwards pass simply processes pages that were missed on the downward
8512   ** pass.
8513   */
8514   for(i=1-nNew; i<nNew; i++){
8515     int iPg = i<0 ? -i : i;
8516     assert( iPg>=0 && iPg<nNew );
8517     if( abDone[iPg] ) continue;         /* Skip pages already processed */
8518     if( i>=0                            /* On the upwards pass, or... */
8519      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
8520     ){
8521       int iNew;
8522       int iOld;
8523       int nNewCell;
8524 
8525       /* Verify condition (1):  If cells are moving left, update iPg
8526       ** only after iPg-1 has already been updated. */
8527       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8528 
8529       /* Verify condition (2):  If cells are moving right, update iPg
8530       ** only after iPg+1 has already been updated. */
8531       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8532 
8533       if( iPg==0 ){
8534         iNew = iOld = 0;
8535         nNewCell = cntNew[0];
8536       }else{
8537         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8538         iNew = cntNew[iPg-1] + !leafData;
8539         nNewCell = cntNew[iPg] - iNew;
8540       }
8541 
8542       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8543       if( rc ) goto balance_cleanup;
8544       abDone[iPg]++;
8545       apNew[iPg]->nFree = usableSpace-szNew[iPg];
8546       assert( apNew[iPg]->nOverflow==0 );
8547       assert( apNew[iPg]->nCell==nNewCell );
8548     }
8549   }
8550 
8551   /* All pages have been processed exactly once */
8552   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8553 
8554   assert( nOld>0 );
8555   assert( nNew>0 );
8556 
8557   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8558     /* The root page of the b-tree now contains no cells. The only sibling
8559     ** page is the right-child of the parent. Copy the contents of the
8560     ** child page into the parent, decreasing the overall height of the
8561     ** b-tree structure by one. This is described as the "balance-shallower"
8562     ** sub-algorithm in some documentation.
8563     **
8564     ** If this is an auto-vacuum database, the call to copyNodeContent()
8565     ** sets all pointer-map entries corresponding to database image pages
8566     ** for which the pointer is stored within the content being copied.
8567     **
8568     ** It is critical that the child page be defragmented before being
8569     ** copied into the parent, because if the parent is page 1 then it will
8570     ** by smaller than the child due to the database header, and so all the
8571     ** free space needs to be up front.
8572     */
8573     assert( nNew==1 || CORRUPT_DB );
8574     rc = defragmentPage(apNew[0], -1);
8575     testcase( rc!=SQLITE_OK );
8576     assert( apNew[0]->nFree ==
8577         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8578           - apNew[0]->nCell*2)
8579       || rc!=SQLITE_OK
8580     );
8581     copyNodeContent(apNew[0], pParent, &rc);
8582     freePage(apNew[0], &rc);
8583   }else if( ISAUTOVACUUM && !leafCorrection ){
8584     /* Fix the pointer map entries associated with the right-child of each
8585     ** sibling page. All other pointer map entries have already been taken
8586     ** care of.  */
8587     for(i=0; i<nNew; i++){
8588       u32 key = get4byte(&apNew[i]->aData[8]);
8589       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8590     }
8591   }
8592 
8593   assert( pParent->isInit );
8594   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8595           nOld, nNew, b.nCell));
8596 
8597   /* Free any old pages that were not reused as new pages.
8598   */
8599   for(i=nNew; i<nOld; i++){
8600     freePage(apOld[i], &rc);
8601   }
8602 
8603 #if 0
8604   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8605     /* The ptrmapCheckPages() contains assert() statements that verify that
8606     ** all pointer map pages are set correctly. This is helpful while
8607     ** debugging. This is usually disabled because a corrupt database may
8608     ** cause an assert() statement to fail.  */
8609     ptrmapCheckPages(apNew, nNew);
8610     ptrmapCheckPages(&pParent, 1);
8611   }
8612 #endif
8613 
8614   /*
8615   ** Cleanup before returning.
8616   */
8617 balance_cleanup:
8618   sqlite3StackFree(0, b.apCell);
8619   for(i=0; i<nOld; i++){
8620     releasePage(apOld[i]);
8621   }
8622   for(i=0; i<nNew; i++){
8623     releasePage(apNew[i]);
8624   }
8625 
8626   return rc;
8627 }
8628 
8629 
8630 /*
8631 ** This function is called when the root page of a b-tree structure is
8632 ** overfull (has one or more overflow pages).
8633 **
8634 ** A new child page is allocated and the contents of the current root
8635 ** page, including overflow cells, are copied into the child. The root
8636 ** page is then overwritten to make it an empty page with the right-child
8637 ** pointer pointing to the new page.
8638 **
8639 ** Before returning, all pointer-map entries corresponding to pages
8640 ** that the new child-page now contains pointers to are updated. The
8641 ** entry corresponding to the new right-child pointer of the root
8642 ** page is also updated.
8643 **
8644 ** If successful, *ppChild is set to contain a reference to the child
8645 ** page and SQLITE_OK is returned. In this case the caller is required
8646 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8647 ** an error code is returned and *ppChild is set to 0.
8648 */
8649 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8650   int rc;                        /* Return value from subprocedures */
8651   MemPage *pChild = 0;           /* Pointer to a new child page */
8652   Pgno pgnoChild = 0;            /* Page number of the new child page */
8653   BtShared *pBt = pRoot->pBt;    /* The BTree */
8654 
8655   assert( pRoot->nOverflow>0 );
8656   assert( sqlite3_mutex_held(pBt->mutex) );
8657 
8658   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8659   ** page that will become the new right-child of pPage. Copy the contents
8660   ** of the node stored on pRoot into the new child page.
8661   */
8662   rc = sqlite3PagerWrite(pRoot->pDbPage);
8663   if( rc==SQLITE_OK ){
8664     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8665     copyNodeContent(pRoot, pChild, &rc);
8666     if( ISAUTOVACUUM ){
8667       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8668     }
8669   }
8670   if( rc ){
8671     *ppChild = 0;
8672     releasePage(pChild);
8673     return rc;
8674   }
8675   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8676   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8677   assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8678 
8679   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8680 
8681   /* Copy the overflow cells from pRoot to pChild */
8682   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8683          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8684   memcpy(pChild->apOvfl, pRoot->apOvfl,
8685          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8686   pChild->nOverflow = pRoot->nOverflow;
8687 
8688   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8689   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8690   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8691 
8692   *ppChild = pChild;
8693   return SQLITE_OK;
8694 }
8695 
8696 /*
8697 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8698 ** on the same B-tree as pCur.
8699 **
8700 ** This can occur if a database is corrupt with two or more SQL tables
8701 ** pointing to the same b-tree.  If an insert occurs on one SQL table
8702 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8703 ** table linked to the same b-tree.  If the secondary insert causes a
8704 ** rebalance, that can change content out from under the cursor on the
8705 ** first SQL table, violating invariants on the first insert.
8706 */
8707 static int anotherValidCursor(BtCursor *pCur){
8708   BtCursor *pOther;
8709   for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8710     if( pOther!=pCur
8711      && pOther->eState==CURSOR_VALID
8712      && pOther->pPage==pCur->pPage
8713     ){
8714       return SQLITE_CORRUPT_BKPT;
8715     }
8716   }
8717   return SQLITE_OK;
8718 }
8719 
8720 /*
8721 ** The page that pCur currently points to has just been modified in
8722 ** some way. This function figures out if this modification means the
8723 ** tree needs to be balanced, and if so calls the appropriate balancing
8724 ** routine. Balancing routines are:
8725 **
8726 **   balance_quick()
8727 **   balance_deeper()
8728 **   balance_nonroot()
8729 */
8730 static int balance(BtCursor *pCur){
8731   int rc = SQLITE_OK;
8732   u8 aBalanceQuickSpace[13];
8733   u8 *pFree = 0;
8734 
8735   VVA_ONLY( int balance_quick_called = 0 );
8736   VVA_ONLY( int balance_deeper_called = 0 );
8737 
8738   do {
8739     int iPage;
8740     MemPage *pPage = pCur->pPage;
8741 
8742     if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8743     if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
8744       /* No rebalance required as long as:
8745       **   (1) There are no overflow cells
8746       **   (2) The amount of free space on the page is less than 2/3rds of
8747       **       the total usable space on the page. */
8748       break;
8749     }else if( (iPage = pCur->iPage)==0 ){
8750       if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8751         /* The root page of the b-tree is overfull. In this case call the
8752         ** balance_deeper() function to create a new child for the root-page
8753         ** and copy the current contents of the root-page to it. The
8754         ** next iteration of the do-loop will balance the child page.
8755         */
8756         assert( balance_deeper_called==0 );
8757         VVA_ONLY( balance_deeper_called++ );
8758         rc = balance_deeper(pPage, &pCur->apPage[1]);
8759         if( rc==SQLITE_OK ){
8760           pCur->iPage = 1;
8761           pCur->ix = 0;
8762           pCur->aiIdx[0] = 0;
8763           pCur->apPage[0] = pPage;
8764           pCur->pPage = pCur->apPage[1];
8765           assert( pCur->pPage->nOverflow );
8766         }
8767       }else{
8768         break;
8769       }
8770     }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
8771       /* The page being written is not a root page, and there is currently
8772       ** more than one reference to it. This only happens if the page is one
8773       ** of its own ancestor pages. Corruption. */
8774       rc = SQLITE_CORRUPT_BKPT;
8775     }else{
8776       MemPage * const pParent = pCur->apPage[iPage-1];
8777       int const iIdx = pCur->aiIdx[iPage-1];
8778 
8779       rc = sqlite3PagerWrite(pParent->pDbPage);
8780       if( rc==SQLITE_OK && pParent->nFree<0 ){
8781         rc = btreeComputeFreeSpace(pParent);
8782       }
8783       if( rc==SQLITE_OK ){
8784 #ifndef SQLITE_OMIT_QUICKBALANCE
8785         if( pPage->intKeyLeaf
8786          && pPage->nOverflow==1
8787          && pPage->aiOvfl[0]==pPage->nCell
8788          && pParent->pgno!=1
8789          && pParent->nCell==iIdx
8790         ){
8791           /* Call balance_quick() to create a new sibling of pPage on which
8792           ** to store the overflow cell. balance_quick() inserts a new cell
8793           ** into pParent, which may cause pParent overflow. If this
8794           ** happens, the next iteration of the do-loop will balance pParent
8795           ** use either balance_nonroot() or balance_deeper(). Until this
8796           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8797           ** buffer.
8798           **
8799           ** The purpose of the following assert() is to check that only a
8800           ** single call to balance_quick() is made for each call to this
8801           ** function. If this were not verified, a subtle bug involving reuse
8802           ** of the aBalanceQuickSpace[] might sneak in.
8803           */
8804           assert( balance_quick_called==0 );
8805           VVA_ONLY( balance_quick_called++ );
8806           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8807         }else
8808 #endif
8809         {
8810           /* In this case, call balance_nonroot() to redistribute cells
8811           ** between pPage and up to 2 of its sibling pages. This involves
8812           ** modifying the contents of pParent, which may cause pParent to
8813           ** become overfull or underfull. The next iteration of the do-loop
8814           ** will balance the parent page to correct this.
8815           **
8816           ** If the parent page becomes overfull, the overflow cell or cells
8817           ** are stored in the pSpace buffer allocated immediately below.
8818           ** A subsequent iteration of the do-loop will deal with this by
8819           ** calling balance_nonroot() (balance_deeper() may be called first,
8820           ** but it doesn't deal with overflow cells - just moves them to a
8821           ** different page). Once this subsequent call to balance_nonroot()
8822           ** has completed, it is safe to release the pSpace buffer used by
8823           ** the previous call, as the overflow cell data will have been
8824           ** copied either into the body of a database page or into the new
8825           ** pSpace buffer passed to the latter call to balance_nonroot().
8826           */
8827           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8828           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8829                                pCur->hints&BTREE_BULKLOAD);
8830           if( pFree ){
8831             /* If pFree is not NULL, it points to the pSpace buffer used
8832             ** by a previous call to balance_nonroot(). Its contents are
8833             ** now stored either on real database pages or within the
8834             ** new pSpace buffer, so it may be safely freed here. */
8835             sqlite3PageFree(pFree);
8836           }
8837 
8838           /* The pSpace buffer will be freed after the next call to
8839           ** balance_nonroot(), or just before this function returns, whichever
8840           ** comes first. */
8841           pFree = pSpace;
8842         }
8843       }
8844 
8845       pPage->nOverflow = 0;
8846 
8847       /* The next iteration of the do-loop balances the parent page. */
8848       releasePage(pPage);
8849       pCur->iPage--;
8850       assert( pCur->iPage>=0 );
8851       pCur->pPage = pCur->apPage[pCur->iPage];
8852     }
8853   }while( rc==SQLITE_OK );
8854 
8855   if( pFree ){
8856     sqlite3PageFree(pFree);
8857   }
8858   return rc;
8859 }
8860 
8861 /* Overwrite content from pX into pDest.  Only do the write if the
8862 ** content is different from what is already there.
8863 */
8864 static int btreeOverwriteContent(
8865   MemPage *pPage,           /* MemPage on which writing will occur */
8866   u8 *pDest,                /* Pointer to the place to start writing */
8867   const BtreePayload *pX,   /* Source of data to write */
8868   int iOffset,              /* Offset of first byte to write */
8869   int iAmt                  /* Number of bytes to be written */
8870 ){
8871   int nData = pX->nData - iOffset;
8872   if( nData<=0 ){
8873     /* Overwritting with zeros */
8874     int i;
8875     for(i=0; i<iAmt && pDest[i]==0; i++){}
8876     if( i<iAmt ){
8877       int rc = sqlite3PagerWrite(pPage->pDbPage);
8878       if( rc ) return rc;
8879       memset(pDest + i, 0, iAmt - i);
8880     }
8881   }else{
8882     if( nData<iAmt ){
8883       /* Mixed read data and zeros at the end.  Make a recursive call
8884       ** to write the zeros then fall through to write the real data */
8885       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8886                                  iAmt-nData);
8887       if( rc ) return rc;
8888       iAmt = nData;
8889     }
8890     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8891       int rc = sqlite3PagerWrite(pPage->pDbPage);
8892       if( rc ) return rc;
8893       /* In a corrupt database, it is possible for the source and destination
8894       ** buffers to overlap.  This is harmless since the database is already
8895       ** corrupt but it does cause valgrind and ASAN warnings.  So use
8896       ** memmove(). */
8897       memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8898     }
8899   }
8900   return SQLITE_OK;
8901 }
8902 
8903 /*
8904 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8905 ** contained in pX.
8906 */
8907 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8908   int iOffset;                        /* Next byte of pX->pData to write */
8909   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8910   int rc;                             /* Return code */
8911   MemPage *pPage = pCur->pPage;       /* Page being written */
8912   BtShared *pBt;                      /* Btree */
8913   Pgno ovflPgno;                      /* Next overflow page to write */
8914   u32 ovflPageSize;                   /* Size to write on overflow page */
8915 
8916   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8917    || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8918   ){
8919     return SQLITE_CORRUPT_BKPT;
8920   }
8921   /* Overwrite the local portion first */
8922   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8923                              0, pCur->info.nLocal);
8924   if( rc ) return rc;
8925   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8926 
8927   /* Now overwrite the overflow pages */
8928   iOffset = pCur->info.nLocal;
8929   assert( nTotal>=0 );
8930   assert( iOffset>=0 );
8931   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8932   pBt = pPage->pBt;
8933   ovflPageSize = pBt->usableSize - 4;
8934   do{
8935     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8936     if( rc ) return rc;
8937     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
8938       rc = SQLITE_CORRUPT_BKPT;
8939     }else{
8940       if( iOffset+ovflPageSize<(u32)nTotal ){
8941         ovflPgno = get4byte(pPage->aData);
8942       }else{
8943         ovflPageSize = nTotal - iOffset;
8944       }
8945       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8946                                  iOffset, ovflPageSize);
8947     }
8948     sqlite3PagerUnref(pPage->pDbPage);
8949     if( rc ) return rc;
8950     iOffset += ovflPageSize;
8951   }while( iOffset<nTotal );
8952   return SQLITE_OK;
8953 }
8954 
8955 
8956 /*
8957 ** Insert a new record into the BTree.  The content of the new record
8958 ** is described by the pX object.  The pCur cursor is used only to
8959 ** define what table the record should be inserted into, and is left
8960 ** pointing at a random location.
8961 **
8962 ** For a table btree (used for rowid tables), only the pX.nKey value of
8963 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8964 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8965 ** hold the content of the row.
8966 **
8967 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8968 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8969 ** pX.pData,nData,nZero fields must be zero.
8970 **
8971 ** If the seekResult parameter is non-zero, then a successful call to
8972 ** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
8973 ** been performed.  In other words, if seekResult!=0 then the cursor
8974 ** is currently pointing to a cell that will be adjacent to the cell
8975 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8976 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8977 ** that is larger than (pKey,nKey).
8978 **
8979 ** If seekResult==0, that means pCur is pointing at some unknown location.
8980 ** In that case, this routine must seek the cursor to the correct insertion
8981 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8982 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8983 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8984 ** to decode the key.
8985 */
8986 int sqlite3BtreeInsert(
8987   BtCursor *pCur,                /* Insert data into the table of this cursor */
8988   const BtreePayload *pX,        /* Content of the row to be inserted */
8989   int flags,                     /* True if this is likely an append */
8990   int seekResult                 /* Result of prior IndexMoveto() call */
8991 ){
8992   int rc;
8993   int loc = seekResult;          /* -1: before desired location  +1: after */
8994   int szNew = 0;
8995   int idx;
8996   MemPage *pPage;
8997   Btree *p = pCur->pBtree;
8998   BtShared *pBt = p->pBt;
8999   unsigned char *oldCell;
9000   unsigned char *newCell = 0;
9001 
9002   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
9003   assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
9004 
9005   /* Save the positions of any other cursors open on this table.
9006   **
9007   ** In some cases, the call to btreeMoveto() below is a no-op. For
9008   ** example, when inserting data into a table with auto-generated integer
9009   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9010   ** integer key to use. It then calls this function to actually insert the
9011   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
9012   ** that the cursor is already where it needs to be and returns without
9013   ** doing any work. To avoid thwarting these optimizations, it is important
9014   ** not to clear the cursor here.
9015   */
9016   if( pCur->curFlags & BTCF_Multiple ){
9017     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9018     if( rc ) return rc;
9019     if( loc && pCur->iPage<0 ){
9020       /* This can only happen if the schema is corrupt such that there is more
9021       ** than one table or index with the same root page as used by the cursor.
9022       ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9023       ** the schema was loaded. This cannot be asserted though, as a user might
9024       ** set the flag, load the schema, and then unset the flag.  */
9025       return SQLITE_CORRUPT_BKPT;
9026     }
9027   }
9028 
9029   /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9030   ** points to a valid cell.
9031   */
9032   if( pCur->eState>=CURSOR_REQUIRESEEK ){
9033     testcase( pCur->eState==CURSOR_REQUIRESEEK );
9034     testcase( pCur->eState==CURSOR_FAULT );
9035     rc = moveToRoot(pCur);
9036     if( rc && rc!=SQLITE_EMPTY ) return rc;
9037   }
9038 
9039   assert( cursorOwnsBtShared(pCur) );
9040   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
9041               && pBt->inTransaction==TRANS_WRITE
9042               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
9043   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9044 
9045   /* Assert that the caller has been consistent. If this cursor was opened
9046   ** expecting an index b-tree, then the caller should be inserting blob
9047   ** keys with no associated data. If the cursor was opened expecting an
9048   ** intkey table, the caller should be inserting integer keys with a
9049   ** blob of associated data.  */
9050   assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9051 
9052   if( pCur->pKeyInfo==0 ){
9053     assert( pX->pKey==0 );
9054     /* If this is an insert into a table b-tree, invalidate any incrblob
9055     ** cursors open on the row being replaced */
9056     if( p->hasIncrblobCur ){
9057       invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9058     }
9059 
9060     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9061     ** to a row with the same key as the new entry being inserted.
9062     */
9063 #ifdef SQLITE_DEBUG
9064     if( flags & BTREE_SAVEPOSITION ){
9065       assert( pCur->curFlags & BTCF_ValidNKey );
9066       assert( pX->nKey==pCur->info.nKey );
9067       assert( loc==0 );
9068     }
9069 #endif
9070 
9071     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9072     ** that the cursor is not pointing to a row to be overwritten.
9073     ** So do a complete check.
9074     */
9075     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
9076       /* The cursor is pointing to the entry that is to be
9077       ** overwritten */
9078       assert( pX->nData>=0 && pX->nZero>=0 );
9079       if( pCur->info.nSize!=0
9080        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9081       ){
9082         /* New entry is the same size as the old.  Do an overwrite */
9083         return btreeOverwriteCell(pCur, pX);
9084       }
9085       assert( loc==0 );
9086     }else if( loc==0 ){
9087       /* The cursor is *not* pointing to the cell to be overwritten, nor
9088       ** to an adjacent cell.  Move the cursor so that it is pointing either
9089       ** to the cell to be overwritten or an adjacent cell.
9090       */
9091       rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9092                (flags & BTREE_APPEND)!=0, &loc);
9093       if( rc ) return rc;
9094     }
9095   }else{
9096     /* This is an index or a WITHOUT ROWID table */
9097 
9098     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9099     ** to a row with the same key as the new entry being inserted.
9100     */
9101     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9102 
9103     /* If the cursor is not already pointing either to the cell to be
9104     ** overwritten, or if a new cell is being inserted, if the cursor is
9105     ** not pointing to an immediately adjacent cell, then move the cursor
9106     ** so that it does.
9107     */
9108     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9109       if( pX->nMem ){
9110         UnpackedRecord r;
9111         r.pKeyInfo = pCur->pKeyInfo;
9112         r.aMem = pX->aMem;
9113         r.nField = pX->nMem;
9114         r.default_rc = 0;
9115         r.eqSeen = 0;
9116         rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
9117       }else{
9118         rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9119                     (flags & BTREE_APPEND)!=0, &loc);
9120       }
9121       if( rc ) return rc;
9122     }
9123 
9124     /* If the cursor is currently pointing to an entry to be overwritten
9125     ** and the new content is the same as as the old, then use the
9126     ** overwrite optimization.
9127     */
9128     if( loc==0 ){
9129       getCellInfo(pCur);
9130       if( pCur->info.nKey==pX->nKey ){
9131         BtreePayload x2;
9132         x2.pData = pX->pKey;
9133         x2.nData = pX->nKey;
9134         x2.nZero = 0;
9135         return btreeOverwriteCell(pCur, &x2);
9136       }
9137     }
9138   }
9139   assert( pCur->eState==CURSOR_VALID
9140        || (pCur->eState==CURSOR_INVALID && loc) );
9141 
9142   pPage = pCur->pPage;
9143   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
9144   assert( pPage->leaf || !pPage->intKey );
9145   if( pPage->nFree<0 ){
9146     if( NEVER(pCur->eState>CURSOR_INVALID) ){
9147      /* ^^^^^--- due to the moveToRoot() call above */
9148       rc = SQLITE_CORRUPT_BKPT;
9149     }else{
9150       rc = btreeComputeFreeSpace(pPage);
9151     }
9152     if( rc ) return rc;
9153   }
9154 
9155   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
9156           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
9157           loc==0 ? "overwrite" : "new entry"));
9158   assert( pPage->isInit || CORRUPT_DB );
9159   newCell = pBt->pTmpSpace;
9160   assert( newCell!=0 );
9161   if( flags & BTREE_PREFORMAT ){
9162     rc = SQLITE_OK;
9163     szNew = pBt->nPreformatSize;
9164     if( szNew<4 ) szNew = 4;
9165     if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
9166       CellInfo info;
9167       pPage->xParseCell(pPage, newCell, &info);
9168       if( info.nPayload!=info.nLocal ){
9169         Pgno ovfl = get4byte(&newCell[szNew-4]);
9170         ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9171       }
9172     }
9173   }else{
9174     rc = fillInCell(pPage, newCell, pX, &szNew);
9175   }
9176   if( rc ) goto end_insert;
9177   assert( szNew==pPage->xCellSize(pPage, newCell) );
9178   assert( szNew <= MX_CELL_SIZE(pBt) );
9179   idx = pCur->ix;
9180   if( loc==0 ){
9181     CellInfo info;
9182     assert( idx>=0 );
9183     if( idx>=pPage->nCell ){
9184       return SQLITE_CORRUPT_BKPT;
9185     }
9186     rc = sqlite3PagerWrite(pPage->pDbPage);
9187     if( rc ){
9188       goto end_insert;
9189     }
9190     oldCell = findCell(pPage, idx);
9191     if( !pPage->leaf ){
9192       memcpy(newCell, oldCell, 4);
9193     }
9194     BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9195     testcase( pCur->curFlags & BTCF_ValidOvfl );
9196     invalidateOverflowCache(pCur);
9197     if( info.nSize==szNew && info.nLocal==info.nPayload
9198      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
9199     ){
9200       /* Overwrite the old cell with the new if they are the same size.
9201       ** We could also try to do this if the old cell is smaller, then add
9202       ** the leftover space to the free list.  But experiments show that
9203       ** doing that is no faster then skipping this optimization and just
9204       ** calling dropCell() and insertCell().
9205       **
9206       ** This optimization cannot be used on an autovacuum database if the
9207       ** new entry uses overflow pages, as the insertCell() call below is
9208       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
9209       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9210       if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9211         return SQLITE_CORRUPT_BKPT;
9212       }
9213       if( oldCell+szNew > pPage->aDataEnd ){
9214         return SQLITE_CORRUPT_BKPT;
9215       }
9216       memcpy(oldCell, newCell, szNew);
9217       return SQLITE_OK;
9218     }
9219     dropCell(pPage, idx, info.nSize, &rc);
9220     if( rc ) goto end_insert;
9221   }else if( loc<0 && pPage->nCell>0 ){
9222     assert( pPage->leaf );
9223     idx = ++pCur->ix;
9224     pCur->curFlags &= ~BTCF_ValidNKey;
9225   }else{
9226     assert( pPage->leaf );
9227   }
9228   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
9229   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9230   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9231 
9232   /* If no error has occurred and pPage has an overflow cell, call balance()
9233   ** to redistribute the cells within the tree. Since balance() may move
9234   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9235   ** variables.
9236   **
9237   ** Previous versions of SQLite called moveToRoot() to move the cursor
9238   ** back to the root page as balance() used to invalidate the contents
9239   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9240   ** set the cursor state to "invalid". This makes common insert operations
9241   ** slightly faster.
9242   **
9243   ** There is a subtle but important optimization here too. When inserting
9244   ** multiple records into an intkey b-tree using a single cursor (as can
9245   ** happen while processing an "INSERT INTO ... SELECT" statement), it
9246   ** is advantageous to leave the cursor pointing to the last entry in
9247   ** the b-tree if possible. If the cursor is left pointing to the last
9248   ** entry in the table, and the next row inserted has an integer key
9249   ** larger than the largest existing key, it is possible to insert the
9250   ** row without seeking the cursor. This can be a big performance boost.
9251   */
9252   pCur->info.nSize = 0;
9253   if( pPage->nOverflow ){
9254     assert( rc==SQLITE_OK );
9255     pCur->curFlags &= ~(BTCF_ValidNKey);
9256     rc = balance(pCur);
9257 
9258     /* Must make sure nOverflow is reset to zero even if the balance()
9259     ** fails. Internal data structure corruption will result otherwise.
9260     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9261     ** from trying to save the current position of the cursor.  */
9262     pCur->pPage->nOverflow = 0;
9263     pCur->eState = CURSOR_INVALID;
9264     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9265       btreeReleaseAllCursorPages(pCur);
9266       if( pCur->pKeyInfo ){
9267         assert( pCur->pKey==0 );
9268         pCur->pKey = sqlite3Malloc( pX->nKey );
9269         if( pCur->pKey==0 ){
9270           rc = SQLITE_NOMEM;
9271         }else{
9272           memcpy(pCur->pKey, pX->pKey, pX->nKey);
9273         }
9274       }
9275       pCur->eState = CURSOR_REQUIRESEEK;
9276       pCur->nKey = pX->nKey;
9277     }
9278   }
9279   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9280 
9281 end_insert:
9282   return rc;
9283 }
9284 
9285 /*
9286 ** This function is used as part of copying the current row from cursor
9287 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9288 ** parameter iKey is used as the rowid value when the record is copied
9289 ** into pDest. Otherwise, the record is copied verbatim.
9290 **
9291 ** This function does not actually write the new value to cursor pDest.
9292 ** Instead, it creates and populates any required overflow pages and
9293 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9294 ** for the destination database. The size of the cell, in bytes, is left
9295 ** in BtShared.nPreformatSize. The caller completes the insertion by
9296 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9297 **
9298 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9299 */
9300 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9301   int rc = SQLITE_OK;
9302   BtShared *pBt = pDest->pBt;
9303   u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
9304   const u8 *aIn;                /* Pointer to next input buffer */
9305   u32 nIn;                      /* Size of input buffer aIn[] */
9306   u32 nRem;                     /* Bytes of data still to copy */
9307 
9308   getCellInfo(pSrc);
9309   if( pSrc->info.nPayload<0x80 ){
9310     *(aOut++) = pSrc->info.nPayload;
9311   }else{
9312     aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9313   }
9314   if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9315   nIn = pSrc->info.nLocal;
9316   aIn = pSrc->info.pPayload;
9317   if( aIn+nIn>pSrc->pPage->aDataEnd ){
9318     return SQLITE_CORRUPT_BKPT;
9319   }
9320   nRem = pSrc->info.nPayload;
9321   if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9322     memcpy(aOut, aIn, nIn);
9323     pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9324   }else{
9325     Pager *pSrcPager = pSrc->pBt->pPager;
9326     u8 *pPgnoOut = 0;
9327     Pgno ovflIn = 0;
9328     DbPage *pPageIn = 0;
9329     MemPage *pPageOut = 0;
9330     u32 nOut;                     /* Size of output buffer aOut[] */
9331 
9332     nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9333     pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9334     if( nOut<pSrc->info.nPayload ){
9335       pPgnoOut = &aOut[nOut];
9336       pBt->nPreformatSize += 4;
9337     }
9338 
9339     if( nRem>nIn ){
9340       if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9341         return SQLITE_CORRUPT_BKPT;
9342       }
9343       ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9344     }
9345 
9346     do {
9347       nRem -= nOut;
9348       do{
9349         assert( nOut>0 );
9350         if( nIn>0 ){
9351           int nCopy = MIN(nOut, nIn);
9352           memcpy(aOut, aIn, nCopy);
9353           nOut -= nCopy;
9354           nIn -= nCopy;
9355           aOut += nCopy;
9356           aIn += nCopy;
9357         }
9358         if( nOut>0 ){
9359           sqlite3PagerUnref(pPageIn);
9360           pPageIn = 0;
9361           rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9362           if( rc==SQLITE_OK ){
9363             aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9364             ovflIn = get4byte(aIn);
9365             aIn += 4;
9366             nIn = pSrc->pBt->usableSize - 4;
9367           }
9368         }
9369       }while( rc==SQLITE_OK && nOut>0 );
9370 
9371       if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9372         Pgno pgnoNew;
9373         MemPage *pNew = 0;
9374         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9375         put4byte(pPgnoOut, pgnoNew);
9376         if( ISAUTOVACUUM && pPageOut ){
9377           ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9378         }
9379         releasePage(pPageOut);
9380         pPageOut = pNew;
9381         if( pPageOut ){
9382           pPgnoOut = pPageOut->aData;
9383           put4byte(pPgnoOut, 0);
9384           aOut = &pPgnoOut[4];
9385           nOut = MIN(pBt->usableSize - 4, nRem);
9386         }
9387       }
9388     }while( nRem>0 && rc==SQLITE_OK );
9389 
9390     releasePage(pPageOut);
9391     sqlite3PagerUnref(pPageIn);
9392   }
9393 
9394   return rc;
9395 }
9396 
9397 /*
9398 ** Delete the entry that the cursor is pointing to.
9399 **
9400 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9401 ** the cursor is left pointing at an arbitrary location after the delete.
9402 ** But if that bit is set, then the cursor is left in a state such that
9403 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9404 ** as it would have been on if the call to BtreeDelete() had been omitted.
9405 **
9406 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9407 ** associated with a single table entry and its indexes.  Only one of those
9408 ** deletes is considered the "primary" delete.  The primary delete occurs
9409 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
9410 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9411 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9412 ** but which might be used by alternative storage engines.
9413 */
9414 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9415   Btree *p = pCur->pBtree;
9416   BtShared *pBt = p->pBt;
9417   int rc;                    /* Return code */
9418   MemPage *pPage;            /* Page to delete cell from */
9419   unsigned char *pCell;      /* Pointer to cell to delete */
9420   int iCellIdx;              /* Index of cell to delete */
9421   int iCellDepth;            /* Depth of node containing pCell */
9422   CellInfo info;             /* Size of the cell being deleted */
9423   u8 bPreserve;              /* Keep cursor valid.  2 for CURSOR_SKIPNEXT */
9424 
9425   assert( cursorOwnsBtShared(pCur) );
9426   assert( pBt->inTransaction==TRANS_WRITE );
9427   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9428   assert( pCur->curFlags & BTCF_WriteFlag );
9429   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9430   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9431   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9432   if( pCur->eState!=CURSOR_VALID ){
9433     if( pCur->eState>=CURSOR_REQUIRESEEK ){
9434       rc = btreeRestoreCursorPosition(pCur);
9435       assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9436       if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9437     }else{
9438       return SQLITE_CORRUPT_BKPT;
9439     }
9440   }
9441   assert( pCur->eState==CURSOR_VALID );
9442 
9443   iCellDepth = pCur->iPage;
9444   iCellIdx = pCur->ix;
9445   pPage = pCur->pPage;
9446   if( pPage->nCell<=iCellIdx ){
9447     return SQLITE_CORRUPT_BKPT;
9448   }
9449   pCell = findCell(pPage, iCellIdx);
9450   if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9451     return SQLITE_CORRUPT_BKPT;
9452   }
9453 
9454   /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9455   ** be preserved following this delete operation. If the current delete
9456   ** will cause a b-tree rebalance, then this is done by saving the cursor
9457   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9458   ** returning.
9459   **
9460   ** If the current delete will not cause a rebalance, then the cursor
9461   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9462   ** before or after the deleted entry.
9463   **
9464   ** The bPreserve value records which path is required:
9465   **
9466   **    bPreserve==0         Not necessary to save the cursor position
9467   **    bPreserve==1         Use CURSOR_REQUIRESEEK to save the cursor position
9468   **    bPreserve==2         Cursor won't move.  Set CURSOR_SKIPNEXT.
9469   */
9470   bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9471   if( bPreserve ){
9472     if( !pPage->leaf
9473      || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9474                                                    (int)(pBt->usableSize*2/3)
9475      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
9476     ){
9477       /* A b-tree rebalance will be required after deleting this entry.
9478       ** Save the cursor key.  */
9479       rc = saveCursorKey(pCur);
9480       if( rc ) return rc;
9481     }else{
9482       bPreserve = 2;
9483     }
9484   }
9485 
9486   /* If the page containing the entry to delete is not a leaf page, move
9487   ** the cursor to the largest entry in the tree that is smaller than
9488   ** the entry being deleted. This cell will replace the cell being deleted
9489   ** from the internal node. The 'previous' entry is used for this instead
9490   ** of the 'next' entry, as the previous entry is always a part of the
9491   ** sub-tree headed by the child page of the cell being deleted. This makes
9492   ** balancing the tree following the delete operation easier.  */
9493   if( !pPage->leaf ){
9494     rc = sqlite3BtreePrevious(pCur, 0);
9495     assert( rc!=SQLITE_DONE );
9496     if( rc ) return rc;
9497   }
9498 
9499   /* Save the positions of any other cursors open on this table before
9500   ** making any modifications.  */
9501   if( pCur->curFlags & BTCF_Multiple ){
9502     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9503     if( rc ) return rc;
9504   }
9505 
9506   /* If this is a delete operation to remove a row from a table b-tree,
9507   ** invalidate any incrblob cursors open on the row being deleted.  */
9508   if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9509     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9510   }
9511 
9512   /* Make the page containing the entry to be deleted writable. Then free any
9513   ** overflow pages associated with the entry and finally remove the cell
9514   ** itself from within the page.  */
9515   rc = sqlite3PagerWrite(pPage->pDbPage);
9516   if( rc ) return rc;
9517   BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9518   dropCell(pPage, iCellIdx, info.nSize, &rc);
9519   if( rc ) return rc;
9520 
9521   /* If the cell deleted was not located on a leaf page, then the cursor
9522   ** is currently pointing to the largest entry in the sub-tree headed
9523   ** by the child-page of the cell that was just deleted from an internal
9524   ** node. The cell from the leaf node needs to be moved to the internal
9525   ** node to replace the deleted cell.  */
9526   if( !pPage->leaf ){
9527     MemPage *pLeaf = pCur->pPage;
9528     int nCell;
9529     Pgno n;
9530     unsigned char *pTmp;
9531 
9532     if( pLeaf->nFree<0 ){
9533       rc = btreeComputeFreeSpace(pLeaf);
9534       if( rc ) return rc;
9535     }
9536     if( iCellDepth<pCur->iPage-1 ){
9537       n = pCur->apPage[iCellDepth+1]->pgno;
9538     }else{
9539       n = pCur->pPage->pgno;
9540     }
9541     pCell = findCell(pLeaf, pLeaf->nCell-1);
9542     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9543     nCell = pLeaf->xCellSize(pLeaf, pCell);
9544     assert( MX_CELL_SIZE(pBt) >= nCell );
9545     pTmp = pBt->pTmpSpace;
9546     assert( pTmp!=0 );
9547     rc = sqlite3PagerWrite(pLeaf->pDbPage);
9548     if( rc==SQLITE_OK ){
9549       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9550     }
9551     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9552     if( rc ) return rc;
9553   }
9554 
9555   /* Balance the tree. If the entry deleted was located on a leaf page,
9556   ** then the cursor still points to that page. In this case the first
9557   ** call to balance() repairs the tree, and the if(...) condition is
9558   ** never true.
9559   **
9560   ** Otherwise, if the entry deleted was on an internal node page, then
9561   ** pCur is pointing to the leaf page from which a cell was removed to
9562   ** replace the cell deleted from the internal node. This is slightly
9563   ** tricky as the leaf node may be underfull, and the internal node may
9564   ** be either under or overfull. In this case run the balancing algorithm
9565   ** on the leaf node first. If the balance proceeds far enough up the
9566   ** tree that we can be sure that any problem in the internal node has
9567   ** been corrected, so be it. Otherwise, after balancing the leaf node,
9568   ** walk the cursor up the tree to the internal node and balance it as
9569   ** well.  */
9570   assert( pCur->pPage->nOverflow==0 );
9571   assert( pCur->pPage->nFree>=0 );
9572   if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
9573     /* Optimization: If the free space is less than 2/3rds of the page,
9574     ** then balance() will always be a no-op.  No need to invoke it. */
9575     rc = SQLITE_OK;
9576   }else{
9577     rc = balance(pCur);
9578   }
9579   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9580     releasePageNotNull(pCur->pPage);
9581     pCur->iPage--;
9582     while( pCur->iPage>iCellDepth ){
9583       releasePage(pCur->apPage[pCur->iPage--]);
9584     }
9585     pCur->pPage = pCur->apPage[pCur->iPage];
9586     rc = balance(pCur);
9587   }
9588 
9589   if( rc==SQLITE_OK ){
9590     if( bPreserve>1 ){
9591       assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
9592       assert( pPage==pCur->pPage || CORRUPT_DB );
9593       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9594       pCur->eState = CURSOR_SKIPNEXT;
9595       if( iCellIdx>=pPage->nCell ){
9596         pCur->skipNext = -1;
9597         pCur->ix = pPage->nCell-1;
9598       }else{
9599         pCur->skipNext = 1;
9600       }
9601     }else{
9602       rc = moveToRoot(pCur);
9603       if( bPreserve ){
9604         btreeReleaseAllCursorPages(pCur);
9605         pCur->eState = CURSOR_REQUIRESEEK;
9606       }
9607       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9608     }
9609   }
9610   return rc;
9611 }
9612 
9613 /*
9614 ** Create a new BTree table.  Write into *piTable the page
9615 ** number for the root page of the new table.
9616 **
9617 ** The type of type is determined by the flags parameter.  Only the
9618 ** following values of flags are currently in use.  Other values for
9619 ** flags might not work:
9620 **
9621 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
9622 **     BTREE_ZERODATA                  Used for SQL indices
9623 */
9624 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9625   BtShared *pBt = p->pBt;
9626   MemPage *pRoot;
9627   Pgno pgnoRoot;
9628   int rc;
9629   int ptfFlags;          /* Page-type flage for the root page of new table */
9630 
9631   assert( sqlite3BtreeHoldsMutex(p) );
9632   assert( pBt->inTransaction==TRANS_WRITE );
9633   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9634 
9635 #ifdef SQLITE_OMIT_AUTOVACUUM
9636   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9637   if( rc ){
9638     return rc;
9639   }
9640 #else
9641   if( pBt->autoVacuum ){
9642     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
9643     MemPage *pPageMove; /* The page to move to. */
9644 
9645     /* Creating a new table may probably require moving an existing database
9646     ** to make room for the new tables root page. In case this page turns
9647     ** out to be an overflow page, delete all overflow page-map caches
9648     ** held by open cursors.
9649     */
9650     invalidateAllOverflowCache(pBt);
9651 
9652     /* Read the value of meta[3] from the database to determine where the
9653     ** root page of the new table should go. meta[3] is the largest root-page
9654     ** created so far, so the new root-page is (meta[3]+1).
9655     */
9656     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9657     if( pgnoRoot>btreePagecount(pBt) ){
9658       return SQLITE_CORRUPT_BKPT;
9659     }
9660     pgnoRoot++;
9661 
9662     /* The new root-page may not be allocated on a pointer-map page, or the
9663     ** PENDING_BYTE page.
9664     */
9665     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9666         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9667       pgnoRoot++;
9668     }
9669     assert( pgnoRoot>=3 );
9670 
9671     /* Allocate a page. The page that currently resides at pgnoRoot will
9672     ** be moved to the allocated page (unless the allocated page happens
9673     ** to reside at pgnoRoot).
9674     */
9675     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9676     if( rc!=SQLITE_OK ){
9677       return rc;
9678     }
9679 
9680     if( pgnoMove!=pgnoRoot ){
9681       /* pgnoRoot is the page that will be used for the root-page of
9682       ** the new table (assuming an error did not occur). But we were
9683       ** allocated pgnoMove. If required (i.e. if it was not allocated
9684       ** by extending the file), the current page at position pgnoMove
9685       ** is already journaled.
9686       */
9687       u8 eType = 0;
9688       Pgno iPtrPage = 0;
9689 
9690       /* Save the positions of any open cursors. This is required in
9691       ** case they are holding a reference to an xFetch reference
9692       ** corresponding to page pgnoRoot.  */
9693       rc = saveAllCursors(pBt, 0, 0);
9694       releasePage(pPageMove);
9695       if( rc!=SQLITE_OK ){
9696         return rc;
9697       }
9698 
9699       /* Move the page currently at pgnoRoot to pgnoMove. */
9700       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9701       if( rc!=SQLITE_OK ){
9702         return rc;
9703       }
9704       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9705       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9706         rc = SQLITE_CORRUPT_BKPT;
9707       }
9708       if( rc!=SQLITE_OK ){
9709         releasePage(pRoot);
9710         return rc;
9711       }
9712       assert( eType!=PTRMAP_ROOTPAGE );
9713       assert( eType!=PTRMAP_FREEPAGE );
9714       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9715       releasePage(pRoot);
9716 
9717       /* Obtain the page at pgnoRoot */
9718       if( rc!=SQLITE_OK ){
9719         return rc;
9720       }
9721       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9722       if( rc!=SQLITE_OK ){
9723         return rc;
9724       }
9725       rc = sqlite3PagerWrite(pRoot->pDbPage);
9726       if( rc!=SQLITE_OK ){
9727         releasePage(pRoot);
9728         return rc;
9729       }
9730     }else{
9731       pRoot = pPageMove;
9732     }
9733 
9734     /* Update the pointer-map and meta-data with the new root-page number. */
9735     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9736     if( rc ){
9737       releasePage(pRoot);
9738       return rc;
9739     }
9740 
9741     /* When the new root page was allocated, page 1 was made writable in
9742     ** order either to increase the database filesize, or to decrement the
9743     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9744     */
9745     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9746     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9747     if( NEVER(rc) ){
9748       releasePage(pRoot);
9749       return rc;
9750     }
9751 
9752   }else{
9753     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9754     if( rc ) return rc;
9755   }
9756 #endif
9757   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9758   if( createTabFlags & BTREE_INTKEY ){
9759     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9760   }else{
9761     ptfFlags = PTF_ZERODATA | PTF_LEAF;
9762   }
9763   zeroPage(pRoot, ptfFlags);
9764   sqlite3PagerUnref(pRoot->pDbPage);
9765   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9766   *piTable = pgnoRoot;
9767   return SQLITE_OK;
9768 }
9769 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9770   int rc;
9771   sqlite3BtreeEnter(p);
9772   rc = btreeCreateTable(p, piTable, flags);
9773   sqlite3BtreeLeave(p);
9774   return rc;
9775 }
9776 
9777 /*
9778 ** Erase the given database page and all its children.  Return
9779 ** the page to the freelist.
9780 */
9781 static int clearDatabasePage(
9782   BtShared *pBt,           /* The BTree that contains the table */
9783   Pgno pgno,               /* Page number to clear */
9784   int freePageFlag,        /* Deallocate page if true */
9785   i64 *pnChange            /* Add number of Cells freed to this counter */
9786 ){
9787   MemPage *pPage;
9788   int rc;
9789   unsigned char *pCell;
9790   int i;
9791   int hdr;
9792   CellInfo info;
9793 
9794   assert( sqlite3_mutex_held(pBt->mutex) );
9795   if( pgno>btreePagecount(pBt) ){
9796     return SQLITE_CORRUPT_BKPT;
9797   }
9798   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9799   if( rc ) return rc;
9800   if( (pBt->openFlags & BTREE_SINGLE)==0
9801    && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
9802   ){
9803     rc = SQLITE_CORRUPT_BKPT;
9804     goto cleardatabasepage_out;
9805   }
9806   hdr = pPage->hdrOffset;
9807   for(i=0; i<pPage->nCell; i++){
9808     pCell = findCell(pPage, i);
9809     if( !pPage->leaf ){
9810       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9811       if( rc ) goto cleardatabasepage_out;
9812     }
9813     BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9814     if( rc ) goto cleardatabasepage_out;
9815   }
9816   if( !pPage->leaf ){
9817     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9818     if( rc ) goto cleardatabasepage_out;
9819     if( pPage->intKey ) pnChange = 0;
9820   }
9821   if( pnChange ){
9822     testcase( !pPage->intKey );
9823     *pnChange += pPage->nCell;
9824   }
9825   if( freePageFlag ){
9826     freePage(pPage, &rc);
9827   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9828     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9829   }
9830 
9831 cleardatabasepage_out:
9832   releasePage(pPage);
9833   return rc;
9834 }
9835 
9836 /*
9837 ** Delete all information from a single table in the database.  iTable is
9838 ** the page number of the root of the table.  After this routine returns,
9839 ** the root page is empty, but still exists.
9840 **
9841 ** This routine will fail with SQLITE_LOCKED if there are any open
9842 ** read cursors on the table.  Open write cursors are moved to the
9843 ** root of the table.
9844 **
9845 ** If pnChange is not NULL, then the integer value pointed to by pnChange
9846 ** is incremented by the number of entries in the table.
9847 */
9848 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
9849   int rc;
9850   BtShared *pBt = p->pBt;
9851   sqlite3BtreeEnter(p);
9852   assert( p->inTrans==TRANS_WRITE );
9853 
9854   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9855 
9856   if( SQLITE_OK==rc ){
9857     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9858     ** is the root of a table b-tree - if it is not, the following call is
9859     ** a no-op).  */
9860     if( p->hasIncrblobCur ){
9861       invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9862     }
9863     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9864   }
9865   sqlite3BtreeLeave(p);
9866   return rc;
9867 }
9868 
9869 /*
9870 ** Delete all information from the single table that pCur is open on.
9871 **
9872 ** This routine only work for pCur on an ephemeral table.
9873 */
9874 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9875   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9876 }
9877 
9878 /*
9879 ** Erase all information in a table and add the root of the table to
9880 ** the freelist.  Except, the root of the principle table (the one on
9881 ** page 1) is never added to the freelist.
9882 **
9883 ** This routine will fail with SQLITE_LOCKED if there are any open
9884 ** cursors on the table.
9885 **
9886 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9887 ** root page in the database file, then the last root page
9888 ** in the database file is moved into the slot formerly occupied by
9889 ** iTable and that last slot formerly occupied by the last root page
9890 ** is added to the freelist instead of iTable.  In this say, all
9891 ** root pages are kept at the beginning of the database file, which
9892 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9893 ** page number that used to be the last root page in the file before
9894 ** the move.  If no page gets moved, *piMoved is set to 0.
9895 ** The last root page is recorded in meta[3] and the value of
9896 ** meta[3] is updated by this procedure.
9897 */
9898 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9899   int rc;
9900   MemPage *pPage = 0;
9901   BtShared *pBt = p->pBt;
9902 
9903   assert( sqlite3BtreeHoldsMutex(p) );
9904   assert( p->inTrans==TRANS_WRITE );
9905   assert( iTable>=2 );
9906   if( iTable>btreePagecount(pBt) ){
9907     return SQLITE_CORRUPT_BKPT;
9908   }
9909 
9910   rc = sqlite3BtreeClearTable(p, iTable, 0);
9911   if( rc ) return rc;
9912   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9913   if( NEVER(rc) ){
9914     releasePage(pPage);
9915     return rc;
9916   }
9917 
9918   *piMoved = 0;
9919 
9920 #ifdef SQLITE_OMIT_AUTOVACUUM
9921   freePage(pPage, &rc);
9922   releasePage(pPage);
9923 #else
9924   if( pBt->autoVacuum ){
9925     Pgno maxRootPgno;
9926     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9927 
9928     if( iTable==maxRootPgno ){
9929       /* If the table being dropped is the table with the largest root-page
9930       ** number in the database, put the root page on the free list.
9931       */
9932       freePage(pPage, &rc);
9933       releasePage(pPage);
9934       if( rc!=SQLITE_OK ){
9935         return rc;
9936       }
9937     }else{
9938       /* The table being dropped does not have the largest root-page
9939       ** number in the database. So move the page that does into the
9940       ** gap left by the deleted root-page.
9941       */
9942       MemPage *pMove;
9943       releasePage(pPage);
9944       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9945       if( rc!=SQLITE_OK ){
9946         return rc;
9947       }
9948       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9949       releasePage(pMove);
9950       if( rc!=SQLITE_OK ){
9951         return rc;
9952       }
9953       pMove = 0;
9954       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9955       freePage(pMove, &rc);
9956       releasePage(pMove);
9957       if( rc!=SQLITE_OK ){
9958         return rc;
9959       }
9960       *piMoved = maxRootPgno;
9961     }
9962 
9963     /* Set the new 'max-root-page' value in the database header. This
9964     ** is the old value less one, less one more if that happens to
9965     ** be a root-page number, less one again if that is the
9966     ** PENDING_BYTE_PAGE.
9967     */
9968     maxRootPgno--;
9969     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9970            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9971       maxRootPgno--;
9972     }
9973     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9974 
9975     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9976   }else{
9977     freePage(pPage, &rc);
9978     releasePage(pPage);
9979   }
9980 #endif
9981   return rc;
9982 }
9983 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9984   int rc;
9985   sqlite3BtreeEnter(p);
9986   rc = btreeDropTable(p, iTable, piMoved);
9987   sqlite3BtreeLeave(p);
9988   return rc;
9989 }
9990 
9991 
9992 /*
9993 ** This function may only be called if the b-tree connection already
9994 ** has a read or write transaction open on the database.
9995 **
9996 ** Read the meta-information out of a database file.  Meta[0]
9997 ** is the number of free pages currently in the database.  Meta[1]
9998 ** through meta[15] are available for use by higher layers.  Meta[0]
9999 ** is read-only, the others are read/write.
10000 **
10001 ** The schema layer numbers meta values differently.  At the schema
10002 ** layer (and the SetCookie and ReadCookie opcodes) the number of
10003 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
10004 **
10005 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
10006 ** of reading the value out of the header, it instead loads the "DataVersion"
10007 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
10008 ** database file.  It is a number computed by the pager.  But its access
10009 ** pattern is the same as header meta values, and so it is convenient to
10010 ** read it from this routine.
10011 */
10012 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
10013   BtShared *pBt = p->pBt;
10014 
10015   sqlite3BtreeEnter(p);
10016   assert( p->inTrans>TRANS_NONE );
10017   assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
10018   assert( pBt->pPage1 );
10019   assert( idx>=0 && idx<=15 );
10020 
10021   if( idx==BTREE_DATA_VERSION ){
10022     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
10023   }else{
10024     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10025   }
10026 
10027   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10028   ** database, mark the database as read-only.  */
10029 #ifdef SQLITE_OMIT_AUTOVACUUM
10030   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10031     pBt->btsFlags |= BTS_READ_ONLY;
10032   }
10033 #endif
10034 
10035   sqlite3BtreeLeave(p);
10036 }
10037 
10038 /*
10039 ** Write meta-information back into the database.  Meta[0] is
10040 ** read-only and may not be written.
10041 */
10042 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10043   BtShared *pBt = p->pBt;
10044   unsigned char *pP1;
10045   int rc;
10046   assert( idx>=1 && idx<=15 );
10047   sqlite3BtreeEnter(p);
10048   assert( p->inTrans==TRANS_WRITE );
10049   assert( pBt->pPage1!=0 );
10050   pP1 = pBt->pPage1->aData;
10051   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10052   if( rc==SQLITE_OK ){
10053     put4byte(&pP1[36 + idx*4], iMeta);
10054 #ifndef SQLITE_OMIT_AUTOVACUUM
10055     if( idx==BTREE_INCR_VACUUM ){
10056       assert( pBt->autoVacuum || iMeta==0 );
10057       assert( iMeta==0 || iMeta==1 );
10058       pBt->incrVacuum = (u8)iMeta;
10059     }
10060 #endif
10061   }
10062   sqlite3BtreeLeave(p);
10063   return rc;
10064 }
10065 
10066 /*
10067 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
10068 ** number of entries in the b-tree and write the result to *pnEntry.
10069 **
10070 ** SQLITE_OK is returned if the operation is successfully executed.
10071 ** Otherwise, if an error is encountered (i.e. an IO error or database
10072 ** corruption) an SQLite error code is returned.
10073 */
10074 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
10075   i64 nEntry = 0;                      /* Value to return in *pnEntry */
10076   int rc;                              /* Return code */
10077 
10078   rc = moveToRoot(pCur);
10079   if( rc==SQLITE_EMPTY ){
10080     *pnEntry = 0;
10081     return SQLITE_OK;
10082   }
10083 
10084   /* Unless an error occurs, the following loop runs one iteration for each
10085   ** page in the B-Tree structure (not including overflow pages).
10086   */
10087   while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
10088     int iIdx;                          /* Index of child node in parent */
10089     MemPage *pPage;                    /* Current page of the b-tree */
10090 
10091     /* If this is a leaf page or the tree is not an int-key tree, then
10092     ** this page contains countable entries. Increment the entry counter
10093     ** accordingly.
10094     */
10095     pPage = pCur->pPage;
10096     if( pPage->leaf || !pPage->intKey ){
10097       nEntry += pPage->nCell;
10098     }
10099 
10100     /* pPage is a leaf node. This loop navigates the cursor so that it
10101     ** points to the first interior cell that it points to the parent of
10102     ** the next page in the tree that has not yet been visited. The
10103     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10104     ** of the page, or to the number of cells in the page if the next page
10105     ** to visit is the right-child of its parent.
10106     **
10107     ** If all pages in the tree have been visited, return SQLITE_OK to the
10108     ** caller.
10109     */
10110     if( pPage->leaf ){
10111       do {
10112         if( pCur->iPage==0 ){
10113           /* All pages of the b-tree have been visited. Return successfully. */
10114           *pnEntry = nEntry;
10115           return moveToRoot(pCur);
10116         }
10117         moveToParent(pCur);
10118       }while ( pCur->ix>=pCur->pPage->nCell );
10119 
10120       pCur->ix++;
10121       pPage = pCur->pPage;
10122     }
10123 
10124     /* Descend to the child node of the cell that the cursor currently
10125     ** points at. This is the right-child if (iIdx==pPage->nCell).
10126     */
10127     iIdx = pCur->ix;
10128     if( iIdx==pPage->nCell ){
10129       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10130     }else{
10131       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10132     }
10133   }
10134 
10135   /* An error has occurred. Return an error code. */
10136   return rc;
10137 }
10138 
10139 /*
10140 ** Return the pager associated with a BTree.  This routine is used for
10141 ** testing and debugging only.
10142 */
10143 Pager *sqlite3BtreePager(Btree *p){
10144   return p->pBt->pPager;
10145 }
10146 
10147 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10148 /*
10149 ** Append a message to the error message string.
10150 */
10151 static void checkAppendMsg(
10152   IntegrityCk *pCheck,
10153   const char *zFormat,
10154   ...
10155 ){
10156   va_list ap;
10157   if( !pCheck->mxErr ) return;
10158   pCheck->mxErr--;
10159   pCheck->nErr++;
10160   va_start(ap, zFormat);
10161   if( pCheck->errMsg.nChar ){
10162     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
10163   }
10164   if( pCheck->zPfx ){
10165     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
10166   }
10167   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
10168   va_end(ap);
10169   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
10170     pCheck->bOomFault = 1;
10171   }
10172 }
10173 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10174 
10175 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10176 
10177 /*
10178 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10179 ** corresponds to page iPg is already set.
10180 */
10181 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10182   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10183   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10184 }
10185 
10186 /*
10187 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10188 */
10189 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10190   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10191   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10192 }
10193 
10194 
10195 /*
10196 ** Add 1 to the reference count for page iPage.  If this is the second
10197 ** reference to the page, add an error message to pCheck->zErrMsg.
10198 ** Return 1 if there are 2 or more references to the page and 0 if
10199 ** if this is the first reference to the page.
10200 **
10201 ** Also check that the page number is in bounds.
10202 */
10203 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10204   if( iPage>pCheck->nPage || iPage==0 ){
10205     checkAppendMsg(pCheck, "invalid page number %d", iPage);
10206     return 1;
10207   }
10208   if( getPageReferenced(pCheck, iPage) ){
10209     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
10210     return 1;
10211   }
10212   if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
10213   setPageReferenced(pCheck, iPage);
10214   return 0;
10215 }
10216 
10217 #ifndef SQLITE_OMIT_AUTOVACUUM
10218 /*
10219 ** Check that the entry in the pointer-map for page iChild maps to
10220 ** page iParent, pointer type ptrType. If not, append an error message
10221 ** to pCheck.
10222 */
10223 static void checkPtrmap(
10224   IntegrityCk *pCheck,   /* Integrity check context */
10225   Pgno iChild,           /* Child page number */
10226   u8 eType,              /* Expected pointer map type */
10227   Pgno iParent           /* Expected pointer map parent page number */
10228 ){
10229   int rc;
10230   u8 ePtrmapType;
10231   Pgno iPtrmapParent;
10232 
10233   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10234   if( rc!=SQLITE_OK ){
10235     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
10236     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
10237     return;
10238   }
10239 
10240   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10241     checkAppendMsg(pCheck,
10242       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
10243       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10244   }
10245 }
10246 #endif
10247 
10248 /*
10249 ** Check the integrity of the freelist or of an overflow page list.
10250 ** Verify that the number of pages on the list is N.
10251 */
10252 static void checkList(
10253   IntegrityCk *pCheck,  /* Integrity checking context */
10254   int isFreeList,       /* True for a freelist.  False for overflow page list */
10255   Pgno iPage,           /* Page number for first page in the list */
10256   u32 N                 /* Expected number of pages in the list */
10257 ){
10258   int i;
10259   u32 expected = N;
10260   int nErrAtStart = pCheck->nErr;
10261   while( iPage!=0 && pCheck->mxErr ){
10262     DbPage *pOvflPage;
10263     unsigned char *pOvflData;
10264     if( checkRef(pCheck, iPage) ) break;
10265     N--;
10266     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10267       checkAppendMsg(pCheck, "failed to get page %d", iPage);
10268       break;
10269     }
10270     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10271     if( isFreeList ){
10272       u32 n = (u32)get4byte(&pOvflData[4]);
10273 #ifndef SQLITE_OMIT_AUTOVACUUM
10274       if( pCheck->pBt->autoVacuum ){
10275         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10276       }
10277 #endif
10278       if( n>pCheck->pBt->usableSize/4-2 ){
10279         checkAppendMsg(pCheck,
10280            "freelist leaf count too big on page %d", iPage);
10281         N--;
10282       }else{
10283         for(i=0; i<(int)n; i++){
10284           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10285 #ifndef SQLITE_OMIT_AUTOVACUUM
10286           if( pCheck->pBt->autoVacuum ){
10287             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10288           }
10289 #endif
10290           checkRef(pCheck, iFreePage);
10291         }
10292         N -= n;
10293       }
10294     }
10295 #ifndef SQLITE_OMIT_AUTOVACUUM
10296     else{
10297       /* If this database supports auto-vacuum and iPage is not the last
10298       ** page in this overflow list, check that the pointer-map entry for
10299       ** the following page matches iPage.
10300       */
10301       if( pCheck->pBt->autoVacuum && N>0 ){
10302         i = get4byte(pOvflData);
10303         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10304       }
10305     }
10306 #endif
10307     iPage = get4byte(pOvflData);
10308     sqlite3PagerUnref(pOvflPage);
10309   }
10310   if( N && nErrAtStart==pCheck->nErr ){
10311     checkAppendMsg(pCheck,
10312       "%s is %d but should be %d",
10313       isFreeList ? "size" : "overflow list length",
10314       expected-N, expected);
10315   }
10316 }
10317 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10318 
10319 /*
10320 ** An implementation of a min-heap.
10321 **
10322 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
10323 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
10324 ** and aHeap[N*2+1].
10325 **
10326 ** The heap property is this:  Every node is less than or equal to both
10327 ** of its daughter nodes.  A consequence of the heap property is that the
10328 ** root node aHeap[1] is always the minimum value currently in the heap.
10329 **
10330 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10331 ** the heap, preserving the heap property.  The btreeHeapPull() routine
10332 ** removes the root element from the heap (the minimum value in the heap)
10333 ** and then moves other nodes around as necessary to preserve the heap
10334 ** property.
10335 **
10336 ** This heap is used for cell overlap and coverage testing.  Each u32
10337 ** entry represents the span of a cell or freeblock on a btree page.
10338 ** The upper 16 bits are the index of the first byte of a range and the
10339 ** lower 16 bits are the index of the last byte of that range.
10340 */
10341 static void btreeHeapInsert(u32 *aHeap, u32 x){
10342   u32 j, i = ++aHeap[0];
10343   aHeap[i] = x;
10344   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10345     x = aHeap[j];
10346     aHeap[j] = aHeap[i];
10347     aHeap[i] = x;
10348     i = j;
10349   }
10350 }
10351 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10352   u32 j, i, x;
10353   if( (x = aHeap[0])==0 ) return 0;
10354   *pOut = aHeap[1];
10355   aHeap[1] = aHeap[x];
10356   aHeap[x] = 0xffffffff;
10357   aHeap[0]--;
10358   i = 1;
10359   while( (j = i*2)<=aHeap[0] ){
10360     if( aHeap[j]>aHeap[j+1] ) j++;
10361     if( aHeap[i]<aHeap[j] ) break;
10362     x = aHeap[i];
10363     aHeap[i] = aHeap[j];
10364     aHeap[j] = x;
10365     i = j;
10366   }
10367   return 1;
10368 }
10369 
10370 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10371 /*
10372 ** Do various sanity checks on a single page of a tree.  Return
10373 ** the tree depth.  Root pages return 0.  Parents of root pages
10374 ** return 1, and so forth.
10375 **
10376 ** These checks are done:
10377 **
10378 **      1.  Make sure that cells and freeblocks do not overlap
10379 **          but combine to completely cover the page.
10380 **      2.  Make sure integer cell keys are in order.
10381 **      3.  Check the integrity of overflow pages.
10382 **      4.  Recursively call checkTreePage on all children.
10383 **      5.  Verify that the depth of all children is the same.
10384 */
10385 static int checkTreePage(
10386   IntegrityCk *pCheck,  /* Context for the sanity check */
10387   Pgno iPage,           /* Page number of the page to check */
10388   i64 *piMinKey,        /* Write minimum integer primary key here */
10389   i64 maxKey            /* Error if integer primary key greater than this */
10390 ){
10391   MemPage *pPage = 0;      /* The page being analyzed */
10392   int i;                   /* Loop counter */
10393   int rc;                  /* Result code from subroutine call */
10394   int depth = -1, d2;      /* Depth of a subtree */
10395   int pgno;                /* Page number */
10396   int nFrag;               /* Number of fragmented bytes on the page */
10397   int hdr;                 /* Offset to the page header */
10398   int cellStart;           /* Offset to the start of the cell pointer array */
10399   int nCell;               /* Number of cells */
10400   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10401   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
10402                            ** False if IPK must be strictly less than maxKey */
10403   u8 *data;                /* Page content */
10404   u8 *pCell;               /* Cell content */
10405   u8 *pCellIdx;            /* Next element of the cell pointer array */
10406   BtShared *pBt;           /* The BtShared object that owns pPage */
10407   u32 pc;                  /* Address of a cell */
10408   u32 usableSize;          /* Usable size of the page */
10409   u32 contentOffset;       /* Offset to the start of the cell content area */
10410   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
10411   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
10412   const char *saved_zPfx = pCheck->zPfx;
10413   int saved_v1 = pCheck->v1;
10414   int saved_v2 = pCheck->v2;
10415   u8 savedIsInit = 0;
10416 
10417   /* Check that the page exists
10418   */
10419   pBt = pCheck->pBt;
10420   usableSize = pBt->usableSize;
10421   if( iPage==0 ) return 0;
10422   if( checkRef(pCheck, iPage) ) return 0;
10423   pCheck->zPfx = "Page %u: ";
10424   pCheck->v1 = iPage;
10425   if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10426     checkAppendMsg(pCheck,
10427        "unable to get the page. error code=%d", rc);
10428     goto end_of_check;
10429   }
10430 
10431   /* Clear MemPage.isInit to make sure the corruption detection code in
10432   ** btreeInitPage() is executed.  */
10433   savedIsInit = pPage->isInit;
10434   pPage->isInit = 0;
10435   if( (rc = btreeInitPage(pPage))!=0 ){
10436     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
10437     checkAppendMsg(pCheck,
10438                    "btreeInitPage() returns error code %d", rc);
10439     goto end_of_check;
10440   }
10441   if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10442     assert( rc==SQLITE_CORRUPT );
10443     checkAppendMsg(pCheck, "free space corruption", rc);
10444     goto end_of_check;
10445   }
10446   data = pPage->aData;
10447   hdr = pPage->hdrOffset;
10448 
10449   /* Set up for cell analysis */
10450   pCheck->zPfx = "On tree page %u cell %d: ";
10451   contentOffset = get2byteNotZero(&data[hdr+5]);
10452   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
10453 
10454   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10455   ** number of cells on the page. */
10456   nCell = get2byte(&data[hdr+3]);
10457   assert( pPage->nCell==nCell );
10458 
10459   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10460   ** immediately follows the b-tree page header. */
10461   cellStart = hdr + 12 - 4*pPage->leaf;
10462   assert( pPage->aCellIdx==&data[cellStart] );
10463   pCellIdx = &data[cellStart + 2*(nCell-1)];
10464 
10465   if( !pPage->leaf ){
10466     /* Analyze the right-child page of internal pages */
10467     pgno = get4byte(&data[hdr+8]);
10468 #ifndef SQLITE_OMIT_AUTOVACUUM
10469     if( pBt->autoVacuum ){
10470       pCheck->zPfx = "On page %u at right child: ";
10471       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10472     }
10473 #endif
10474     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10475     keyCanBeEqual = 0;
10476   }else{
10477     /* For leaf pages, the coverage check will occur in the same loop
10478     ** as the other cell checks, so initialize the heap.  */
10479     heap = pCheck->heap;
10480     heap[0] = 0;
10481   }
10482 
10483   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10484   ** integer offsets to the cell contents. */
10485   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10486     CellInfo info;
10487 
10488     /* Check cell size */
10489     pCheck->v2 = i;
10490     assert( pCellIdx==&data[cellStart + i*2] );
10491     pc = get2byteAligned(pCellIdx);
10492     pCellIdx -= 2;
10493     if( pc<contentOffset || pc>usableSize-4 ){
10494       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10495                              pc, contentOffset, usableSize-4);
10496       doCoverageCheck = 0;
10497       continue;
10498     }
10499     pCell = &data[pc];
10500     pPage->xParseCell(pPage, pCell, &info);
10501     if( pc+info.nSize>usableSize ){
10502       checkAppendMsg(pCheck, "Extends off end of page");
10503       doCoverageCheck = 0;
10504       continue;
10505     }
10506 
10507     /* Check for integer primary key out of range */
10508     if( pPage->intKey ){
10509       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10510         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10511       }
10512       maxKey = info.nKey;
10513       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
10514     }
10515 
10516     /* Check the content overflow list */
10517     if( info.nPayload>info.nLocal ){
10518       u32 nPage;       /* Number of pages on the overflow chain */
10519       Pgno pgnoOvfl;   /* First page of the overflow chain */
10520       assert( pc + info.nSize - 4 <= usableSize );
10521       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10522       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10523 #ifndef SQLITE_OMIT_AUTOVACUUM
10524       if( pBt->autoVacuum ){
10525         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10526       }
10527 #endif
10528       checkList(pCheck, 0, pgnoOvfl, nPage);
10529     }
10530 
10531     if( !pPage->leaf ){
10532       /* Check sanity of left child page for internal pages */
10533       pgno = get4byte(pCell);
10534 #ifndef SQLITE_OMIT_AUTOVACUUM
10535       if( pBt->autoVacuum ){
10536         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10537       }
10538 #endif
10539       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10540       keyCanBeEqual = 0;
10541       if( d2!=depth ){
10542         checkAppendMsg(pCheck, "Child page depth differs");
10543         depth = d2;
10544       }
10545     }else{
10546       /* Populate the coverage-checking heap for leaf pages */
10547       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10548     }
10549   }
10550   *piMinKey = maxKey;
10551 
10552   /* Check for complete coverage of the page
10553   */
10554   pCheck->zPfx = 0;
10555   if( doCoverageCheck && pCheck->mxErr>0 ){
10556     /* For leaf pages, the min-heap has already been initialized and the
10557     ** cells have already been inserted.  But for internal pages, that has
10558     ** not yet been done, so do it now */
10559     if( !pPage->leaf ){
10560       heap = pCheck->heap;
10561       heap[0] = 0;
10562       for(i=nCell-1; i>=0; i--){
10563         u32 size;
10564         pc = get2byteAligned(&data[cellStart+i*2]);
10565         size = pPage->xCellSize(pPage, &data[pc]);
10566         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10567       }
10568     }
10569     /* Add the freeblocks to the min-heap
10570     **
10571     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10572     ** is the offset of the first freeblock, or zero if there are no
10573     ** freeblocks on the page.
10574     */
10575     i = get2byte(&data[hdr+1]);
10576     while( i>0 ){
10577       int size, j;
10578       assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10579       size = get2byte(&data[i+2]);
10580       assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10581       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10582       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10583       ** big-endian integer which is the offset in the b-tree page of the next
10584       ** freeblock in the chain, or zero if the freeblock is the last on the
10585       ** chain. */
10586       j = get2byte(&data[i]);
10587       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10588       ** increasing offset. */
10589       assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
10590       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10591       i = j;
10592     }
10593     /* Analyze the min-heap looking for overlap between cells and/or
10594     ** freeblocks, and counting the number of untracked bytes in nFrag.
10595     **
10596     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
10597     ** There is an implied first entry the covers the page header, the cell
10598     ** pointer index, and the gap between the cell pointer index and the start
10599     ** of cell content.
10600     **
10601     ** The loop below pulls entries from the min-heap in order and compares
10602     ** the start_address against the previous end_address.  If there is an
10603     ** overlap, that means bytes are used multiple times.  If there is a gap,
10604     ** that gap is added to the fragmentation count.
10605     */
10606     nFrag = 0;
10607     prev = contentOffset - 1;   /* Implied first min-heap entry */
10608     while( btreeHeapPull(heap,&x) ){
10609       if( (prev&0xffff)>=(x>>16) ){
10610         checkAppendMsg(pCheck,
10611           "Multiple uses for byte %u of page %u", x>>16, iPage);
10612         break;
10613       }else{
10614         nFrag += (x>>16) - (prev&0xffff) - 1;
10615         prev = x;
10616       }
10617     }
10618     nFrag += usableSize - (prev&0xffff) - 1;
10619     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10620     ** is stored in the fifth field of the b-tree page header.
10621     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10622     ** number of fragmented free bytes within the cell content area.
10623     */
10624     if( heap[0]==0 && nFrag!=data[hdr+7] ){
10625       checkAppendMsg(pCheck,
10626           "Fragmentation of %d bytes reported as %d on page %u",
10627           nFrag, data[hdr+7], iPage);
10628     }
10629   }
10630 
10631 end_of_check:
10632   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10633   releasePage(pPage);
10634   pCheck->zPfx = saved_zPfx;
10635   pCheck->v1 = saved_v1;
10636   pCheck->v2 = saved_v2;
10637   return depth+1;
10638 }
10639 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10640 
10641 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10642 /*
10643 ** This routine does a complete check of the given BTree file.  aRoot[] is
10644 ** an array of pages numbers were each page number is the root page of
10645 ** a table.  nRoot is the number of entries in aRoot.
10646 **
10647 ** A read-only or read-write transaction must be opened before calling
10648 ** this function.
10649 **
10650 ** Write the number of error seen in *pnErr.  Except for some memory
10651 ** allocation errors,  an error message held in memory obtained from
10652 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
10653 ** returned.  If a memory allocation error occurs, NULL is returned.
10654 **
10655 ** If the first entry in aRoot[] is 0, that indicates that the list of
10656 ** root pages is incomplete.  This is a "partial integrity-check".  This
10657 ** happens when performing an integrity check on a single table.  The
10658 ** zero is skipped, of course.  But in addition, the freelist checks
10659 ** and the checks to make sure every page is referenced are also skipped,
10660 ** since obviously it is not possible to know which pages are covered by
10661 ** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
10662 ** checks are still performed.
10663 */
10664 char *sqlite3BtreeIntegrityCheck(
10665   sqlite3 *db,  /* Database connection that is running the check */
10666   Btree *p,     /* The btree to be checked */
10667   Pgno *aRoot,  /* An array of root pages numbers for individual trees */
10668   int nRoot,    /* Number of entries in aRoot[] */
10669   int mxErr,    /* Stop reporting errors after this many */
10670   int *pnErr    /* Write number of errors seen to this variable */
10671 ){
10672   Pgno i;
10673   IntegrityCk sCheck;
10674   BtShared *pBt = p->pBt;
10675   u64 savedDbFlags = pBt->db->flags;
10676   char zErr[100];
10677   int bPartial = 0;            /* True if not checking all btrees */
10678   int bCkFreelist = 1;         /* True to scan the freelist */
10679   VVA_ONLY( int nRef );
10680   assert( nRoot>0 );
10681 
10682   /* aRoot[0]==0 means this is a partial check */
10683   if( aRoot[0]==0 ){
10684     assert( nRoot>1 );
10685     bPartial = 1;
10686     if( aRoot[1]!=1 ) bCkFreelist = 0;
10687   }
10688 
10689   sqlite3BtreeEnter(p);
10690   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10691   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10692   assert( nRef>=0 );
10693   sCheck.db = db;
10694   sCheck.pBt = pBt;
10695   sCheck.pPager = pBt->pPager;
10696   sCheck.nPage = btreePagecount(sCheck.pBt);
10697   sCheck.mxErr = mxErr;
10698   sCheck.nErr = 0;
10699   sCheck.bOomFault = 0;
10700   sCheck.zPfx = 0;
10701   sCheck.v1 = 0;
10702   sCheck.v2 = 0;
10703   sCheck.aPgRef = 0;
10704   sCheck.heap = 0;
10705   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10706   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10707   if( sCheck.nPage==0 ){
10708     goto integrity_ck_cleanup;
10709   }
10710 
10711   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10712   if( !sCheck.aPgRef ){
10713     sCheck.bOomFault = 1;
10714     goto integrity_ck_cleanup;
10715   }
10716   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10717   if( sCheck.heap==0 ){
10718     sCheck.bOomFault = 1;
10719     goto integrity_ck_cleanup;
10720   }
10721 
10722   i = PENDING_BYTE_PAGE(pBt);
10723   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10724 
10725   /* Check the integrity of the freelist
10726   */
10727   if( bCkFreelist ){
10728     sCheck.zPfx = "Main freelist: ";
10729     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10730               get4byte(&pBt->pPage1->aData[36]));
10731     sCheck.zPfx = 0;
10732   }
10733 
10734   /* Check all the tables.
10735   */
10736 #ifndef SQLITE_OMIT_AUTOVACUUM
10737   if( !bPartial ){
10738     if( pBt->autoVacuum ){
10739       Pgno mx = 0;
10740       Pgno mxInHdr;
10741       for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10742       mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10743       if( mx!=mxInHdr ){
10744         checkAppendMsg(&sCheck,
10745           "max rootpage (%d) disagrees with header (%d)",
10746           mx, mxInHdr
10747         );
10748       }
10749     }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10750       checkAppendMsg(&sCheck,
10751         "incremental_vacuum enabled with a max rootpage of zero"
10752       );
10753     }
10754   }
10755 #endif
10756   testcase( pBt->db->flags & SQLITE_CellSizeCk );
10757   pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10758   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10759     i64 notUsed;
10760     if( aRoot[i]==0 ) continue;
10761 #ifndef SQLITE_OMIT_AUTOVACUUM
10762     if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10763       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10764     }
10765 #endif
10766     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10767   }
10768   pBt->db->flags = savedDbFlags;
10769 
10770   /* Make sure every page in the file is referenced
10771   */
10772   if( !bPartial ){
10773     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10774 #ifdef SQLITE_OMIT_AUTOVACUUM
10775       if( getPageReferenced(&sCheck, i)==0 ){
10776         checkAppendMsg(&sCheck, "Page %d is never used", i);
10777       }
10778 #else
10779       /* If the database supports auto-vacuum, make sure no tables contain
10780       ** references to pointer-map pages.
10781       */
10782       if( getPageReferenced(&sCheck, i)==0 &&
10783          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10784         checkAppendMsg(&sCheck, "Page %d is never used", i);
10785       }
10786       if( getPageReferenced(&sCheck, i)!=0 &&
10787          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10788         checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10789       }
10790 #endif
10791     }
10792   }
10793 
10794   /* Clean  up and report errors.
10795   */
10796 integrity_ck_cleanup:
10797   sqlite3PageFree(sCheck.heap);
10798   sqlite3_free(sCheck.aPgRef);
10799   if( sCheck.bOomFault ){
10800     sqlite3_str_reset(&sCheck.errMsg);
10801     sCheck.nErr++;
10802   }
10803   *pnErr = sCheck.nErr;
10804   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10805   /* Make sure this analysis did not leave any unref() pages. */
10806   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10807   sqlite3BtreeLeave(p);
10808   return sqlite3StrAccumFinish(&sCheck.errMsg);
10809 }
10810 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10811 
10812 /*
10813 ** Return the full pathname of the underlying database file.  Return
10814 ** an empty string if the database is in-memory or a TEMP database.
10815 **
10816 ** The pager filename is invariant as long as the pager is
10817 ** open so it is safe to access without the BtShared mutex.
10818 */
10819 const char *sqlite3BtreeGetFilename(Btree *p){
10820   assert( p->pBt->pPager!=0 );
10821   return sqlite3PagerFilename(p->pBt->pPager, 1);
10822 }
10823 
10824 /*
10825 ** Return the pathname of the journal file for this database. The return
10826 ** value of this routine is the same regardless of whether the journal file
10827 ** has been created or not.
10828 **
10829 ** The pager journal filename is invariant as long as the pager is
10830 ** open so it is safe to access without the BtShared mutex.
10831 */
10832 const char *sqlite3BtreeGetJournalname(Btree *p){
10833   assert( p->pBt->pPager!=0 );
10834   return sqlite3PagerJournalname(p->pBt->pPager);
10835 }
10836 
10837 /*
10838 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10839 ** to describe the current transaction state of Btree p.
10840 */
10841 int sqlite3BtreeTxnState(Btree *p){
10842   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10843   return p ? p->inTrans : 0;
10844 }
10845 
10846 #ifndef SQLITE_OMIT_WAL
10847 /*
10848 ** Run a checkpoint on the Btree passed as the first argument.
10849 **
10850 ** Return SQLITE_LOCKED if this or any other connection has an open
10851 ** transaction on the shared-cache the argument Btree is connected to.
10852 **
10853 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10854 */
10855 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10856   int rc = SQLITE_OK;
10857   if( p ){
10858     BtShared *pBt = p->pBt;
10859     sqlite3BtreeEnter(p);
10860     if( pBt->inTransaction!=TRANS_NONE ){
10861       rc = SQLITE_LOCKED;
10862     }else{
10863       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10864     }
10865     sqlite3BtreeLeave(p);
10866   }
10867   return rc;
10868 }
10869 #endif
10870 
10871 /*
10872 ** Return true if there is currently a backup running on Btree p.
10873 */
10874 int sqlite3BtreeIsInBackup(Btree *p){
10875   assert( p );
10876   assert( sqlite3_mutex_held(p->db->mutex) );
10877   return p->nBackup!=0;
10878 }
10879 
10880 /*
10881 ** This function returns a pointer to a blob of memory associated with
10882 ** a single shared-btree. The memory is used by client code for its own
10883 ** purposes (for example, to store a high-level schema associated with
10884 ** the shared-btree). The btree layer manages reference counting issues.
10885 **
10886 ** The first time this is called on a shared-btree, nBytes bytes of memory
10887 ** are allocated, zeroed, and returned to the caller. For each subsequent
10888 ** call the nBytes parameter is ignored and a pointer to the same blob
10889 ** of memory returned.
10890 **
10891 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10892 ** allocated, a null pointer is returned. If the blob has already been
10893 ** allocated, it is returned as normal.
10894 **
10895 ** Just before the shared-btree is closed, the function passed as the
10896 ** xFree argument when the memory allocation was made is invoked on the
10897 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10898 ** on the memory, the btree layer does that.
10899 */
10900 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10901   BtShared *pBt = p->pBt;
10902   sqlite3BtreeEnter(p);
10903   if( !pBt->pSchema && nBytes ){
10904     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10905     pBt->xFreeSchema = xFree;
10906   }
10907   sqlite3BtreeLeave(p);
10908   return pBt->pSchema;
10909 }
10910 
10911 /*
10912 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10913 ** btree as the argument handle holds an exclusive lock on the
10914 ** sqlite_schema table. Otherwise SQLITE_OK.
10915 */
10916 int sqlite3BtreeSchemaLocked(Btree *p){
10917   int rc;
10918   assert( sqlite3_mutex_held(p->db->mutex) );
10919   sqlite3BtreeEnter(p);
10920   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10921   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10922   sqlite3BtreeLeave(p);
10923   return rc;
10924 }
10925 
10926 
10927 #ifndef SQLITE_OMIT_SHARED_CACHE
10928 /*
10929 ** Obtain a lock on the table whose root page is iTab.  The
10930 ** lock is a write lock if isWritelock is true or a read lock
10931 ** if it is false.
10932 */
10933 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10934   int rc = SQLITE_OK;
10935   assert( p->inTrans!=TRANS_NONE );
10936   if( p->sharable ){
10937     u8 lockType = READ_LOCK + isWriteLock;
10938     assert( READ_LOCK+1==WRITE_LOCK );
10939     assert( isWriteLock==0 || isWriteLock==1 );
10940 
10941     sqlite3BtreeEnter(p);
10942     rc = querySharedCacheTableLock(p, iTab, lockType);
10943     if( rc==SQLITE_OK ){
10944       rc = setSharedCacheTableLock(p, iTab, lockType);
10945     }
10946     sqlite3BtreeLeave(p);
10947   }
10948   return rc;
10949 }
10950 #endif
10951 
10952 #ifndef SQLITE_OMIT_INCRBLOB
10953 /*
10954 ** Argument pCsr must be a cursor opened for writing on an
10955 ** INTKEY table currently pointing at a valid table entry.
10956 ** This function modifies the data stored as part of that entry.
10957 **
10958 ** Only the data content may only be modified, it is not possible to
10959 ** change the length of the data stored. If this function is called with
10960 ** parameters that attempt to write past the end of the existing data,
10961 ** no modifications are made and SQLITE_CORRUPT is returned.
10962 */
10963 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10964   int rc;
10965   assert( cursorOwnsBtShared(pCsr) );
10966   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10967   assert( pCsr->curFlags & BTCF_Incrblob );
10968 
10969   rc = restoreCursorPosition(pCsr);
10970   if( rc!=SQLITE_OK ){
10971     return rc;
10972   }
10973   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10974   if( pCsr->eState!=CURSOR_VALID ){
10975     return SQLITE_ABORT;
10976   }
10977 
10978   /* Save the positions of all other cursors open on this table. This is
10979   ** required in case any of them are holding references to an xFetch
10980   ** version of the b-tree page modified by the accessPayload call below.
10981   **
10982   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10983   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10984   ** saveAllCursors can only return SQLITE_OK.
10985   */
10986   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10987   assert( rc==SQLITE_OK );
10988 
10989   /* Check some assumptions:
10990   **   (a) the cursor is open for writing,
10991   **   (b) there is a read/write transaction open,
10992   **   (c) the connection holds a write-lock on the table (if required),
10993   **   (d) there are no conflicting read-locks, and
10994   **   (e) the cursor points at a valid row of an intKey table.
10995   */
10996   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10997     return SQLITE_READONLY;
10998   }
10999   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11000               && pCsr->pBt->inTransaction==TRANS_WRITE );
11001   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11002   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
11003   assert( pCsr->pPage->intKey );
11004 
11005   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
11006 }
11007 
11008 /*
11009 ** Mark this cursor as an incremental blob cursor.
11010 */
11011 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
11012   pCur->curFlags |= BTCF_Incrblob;
11013   pCur->pBtree->hasIncrblobCur = 1;
11014 }
11015 #endif
11016 
11017 /*
11018 ** Set both the "read version" (single byte at byte offset 18) and
11019 ** "write version" (single byte at byte offset 19) fields in the database
11020 ** header to iVersion.
11021 */
11022 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11023   BtShared *pBt = pBtree->pBt;
11024   int rc;                         /* Return code */
11025 
11026   assert( iVersion==1 || iVersion==2 );
11027 
11028   /* If setting the version fields to 1, do not automatically open the
11029   ** WAL connection, even if the version fields are currently set to 2.
11030   */
11031   pBt->btsFlags &= ~BTS_NO_WAL;
11032   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
11033 
11034   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
11035   if( rc==SQLITE_OK ){
11036     u8 *aData = pBt->pPage1->aData;
11037     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
11038       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
11039       if( rc==SQLITE_OK ){
11040         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11041         if( rc==SQLITE_OK ){
11042           aData[18] = (u8)iVersion;
11043           aData[19] = (u8)iVersion;
11044         }
11045       }
11046     }
11047   }
11048 
11049   pBt->btsFlags &= ~BTS_NO_WAL;
11050   return rc;
11051 }
11052 
11053 /*
11054 ** Return true if the cursor has a hint specified.  This routine is
11055 ** only used from within assert() statements
11056 */
11057 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11058   return (pCsr->hints & mask)!=0;
11059 }
11060 
11061 /*
11062 ** Return true if the given Btree is read-only.
11063 */
11064 int sqlite3BtreeIsReadonly(Btree *p){
11065   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11066 }
11067 
11068 /*
11069 ** Return the size of the header added to each page by this module.
11070 */
11071 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
11072 
11073 #if !defined(SQLITE_OMIT_SHARED_CACHE)
11074 /*
11075 ** Return true if the Btree passed as the only argument is sharable.
11076 */
11077 int sqlite3BtreeSharable(Btree *p){
11078   return p->sharable;
11079 }
11080 
11081 /*
11082 ** Return the number of connections to the BtShared object accessed by
11083 ** the Btree handle passed as the only argument. For private caches
11084 ** this is always 1. For shared caches it may be 1 or greater.
11085 */
11086 int sqlite3BtreeConnectionCount(Btree *p){
11087   testcase( p->sharable );
11088   return p->pBt->nRef;
11089 }
11090 #endif
11091