xref: /sqlite-3.40.0/src/btree.c (revision bb0c5428)
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file implements an external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
15 */
16 #include "btreeInt.h"
17 
18 /*
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
21 */
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
23 
24 /*
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
27 */
28 #if 0
29 int sqlite3BtreeTrace=1;  /* True to enable tracing */
30 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
34 
35 /*
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
38 **
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page.  If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
43 */
44 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
45 
46 /*
47 ** Values passed as the 5th argument to allocateBtreePage()
48 */
49 #define BTALLOC_ANY   0           /* Allocate any page */
50 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
51 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
52 
53 /*
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
56 **
57 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58 */
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
64 
65 #ifndef SQLITE_OMIT_SHARED_CACHE
66 /*
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache.  This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
71 **
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
73 */
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
80 
81 #ifndef SQLITE_OMIT_SHARED_CACHE
82 /*
83 ** Enable or disable the shared pager and schema features.
84 **
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
88 */
89 int sqlite3_enable_shared_cache(int enable){
90   sqlite3GlobalConfig.sharedCacheEnabled = enable;
91   return SQLITE_OK;
92 }
93 #endif
94 
95 
96 
97 #ifdef SQLITE_OMIT_SHARED_CACHE
98   /*
99   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100   ** and clearAllSharedCacheTableLocks()
101   ** manipulate entries in the BtShared.pLock linked list used to store
102   ** shared-cache table level locks. If the library is compiled with the
103   ** shared-cache feature disabled, then there is only ever one user
104   ** of each BtShared structure and so this locking is not necessary.
105   ** So define the lock related functions as no-ops.
106   */
107   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109   #define clearAllSharedCacheTableLocks(a)
110   #define downgradeAllSharedCacheTableLocks(a)
111   #define hasSharedCacheTableLock(a,b,c,d) 1
112   #define hasReadConflicts(a, b) 0
113 #endif
114 
115 #ifdef SQLITE_DEBUG
116 /*
117 ** Return and reset the seek counter for a Btree object.
118 */
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120   u64 n =  pBt->nSeek;
121   pBt->nSeek = 0;
122   return n;
123 }
124 #endif
125 
126 /*
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
129 **
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
134 */
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137   char *zMsg;
138   sqlite3BeginBenignMalloc();
139   zMsg = sqlite3_mprintf("database corruption page %d of %s",
140       (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
141   );
142   sqlite3EndBenignMalloc();
143   if( zMsg ){
144     sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
145   }
146   sqlite3_free(zMsg);
147   return SQLITE_CORRUPT_BKPT;
148 }
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
153 
154 #ifndef SQLITE_OMIT_SHARED_CACHE
155 
156 #ifdef SQLITE_DEBUG
157 /*
158 **** This function is only used as part of an assert() statement. ***
159 **
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot.   Return 1 if it does and 0 if not.
162 **
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
165 **
166 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
167 **
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
174 **
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
178 */
179 static int hasSharedCacheTableLock(
180   Btree *pBtree,         /* Handle that must hold lock */
181   Pgno iRoot,            /* Root page of b-tree */
182   int isIndex,           /* True if iRoot is the root of an index b-tree */
183   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
184 ){
185   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186   Pgno iTab = 0;
187   BtLock *pLock;
188 
189   /* If this database is not shareable, or if the client is reading
190   ** and has the read-uncommitted flag set, then no lock is required.
191   ** Return true immediately.
192   */
193   if( (pBtree->sharable==0)
194    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
195   ){
196     return 1;
197   }
198 
199   /* If the client is reading  or writing an index and the schema is
200   ** not loaded, then it is too difficult to actually check to see if
201   ** the correct locks are held.  So do not bother - just return true.
202   ** This case does not come up very often anyhow.
203   */
204   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205     return 1;
206   }
207 
208   /* Figure out the root-page that the lock should be held on. For table
209   ** b-trees, this is just the root page of the b-tree being read or
210   ** written. For index b-trees, it is the root page of the associated
211   ** table.  */
212   if( isIndex ){
213     HashElem *p;
214     int bSeen = 0;
215     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216       Index *pIdx = (Index *)sqliteHashData(p);
217       if( pIdx->tnum==(int)iRoot ){
218         if( bSeen ){
219           /* Two or more indexes share the same root page.  There must
220           ** be imposter tables.  So just return true.  The assert is not
221           ** useful in that case. */
222           return 1;
223         }
224         iTab = pIdx->pTable->tnum;
225         bSeen = 1;
226       }
227     }
228   }else{
229     iTab = iRoot;
230   }
231 
232   /* Search for the required lock. Either a write-lock on root-page iTab, a
233   ** write-lock on the schema table, or (if the client is reading) a
234   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
235   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236     if( pLock->pBtree==pBtree
237      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238      && pLock->eLock>=eLockType
239     ){
240       return 1;
241     }
242   }
243 
244   /* Failed to find the required lock. */
245   return 0;
246 }
247 #endif /* SQLITE_DEBUG */
248 
249 #ifdef SQLITE_DEBUG
250 /*
251 **** This function may be used as part of assert() statements only. ****
252 **
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
256 **
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table.  Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
262 **
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
265 **
266 **    assert( !hasReadConflicts(pBtree, iRoot) );
267 */
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269   BtCursor *p;
270   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271     if( p->pgnoRoot==iRoot
272      && p->pBtree!=pBtree
273      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
274     ){
275       return 1;
276     }
277   }
278   return 0;
279 }
280 #endif    /* #ifdef SQLITE_DEBUG */
281 
282 /*
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
287 */
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289   BtShared *pBt = p->pBt;
290   BtLock *pIter;
291 
292   assert( sqlite3BtreeHoldsMutex(p) );
293   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294   assert( p->db!=0 );
295   assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
296 
297   /* If requesting a write-lock, then the Btree must have an open write
298   ** transaction on this file. And, obviously, for this to be so there
299   ** must be an open write transaction on the file itself.
300   */
301   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
303 
304   /* This routine is a no-op if the shared-cache is not enabled */
305   if( !p->sharable ){
306     return SQLITE_OK;
307   }
308 
309   /* If some other connection is holding an exclusive lock, the
310   ** requested lock may not be obtained.
311   */
312   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314     return SQLITE_LOCKED_SHAREDCACHE;
315   }
316 
317   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318     /* The condition (pIter->eLock!=eLock) in the following if(...)
319     ** statement is a simplification of:
320     **
321     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
322     **
323     ** since we know that if eLock==WRITE_LOCK, then no other connection
324     ** may hold a WRITE_LOCK on any table in this file (since there can
325     ** only be a single writer).
326     */
327     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331       if( eLock==WRITE_LOCK ){
332         assert( p==pBt->pWriter );
333         pBt->btsFlags |= BTS_PENDING;
334       }
335       return SQLITE_LOCKED_SHAREDCACHE;
336     }
337   }
338   return SQLITE_OK;
339 }
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
341 
342 #ifndef SQLITE_OMIT_SHARED_CACHE
343 /*
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
347 **
348 ** This function assumes the following:
349 **
350 **   (a) The specified Btree object p is connected to a sharable
351 **       database (one with the BtShared.sharable flag set), and
352 **
353 **   (b) No other Btree objects hold a lock that conflicts
354 **       with the requested lock (i.e. querySharedCacheTableLock() has
355 **       already been called and returned SQLITE_OK).
356 **
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
359 */
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361   BtShared *pBt = p->pBt;
362   BtLock *pLock = 0;
363   BtLock *pIter;
364 
365   assert( sqlite3BtreeHoldsMutex(p) );
366   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367   assert( p->db!=0 );
368 
369   /* A connection with the read-uncommitted flag set will never try to
370   ** obtain a read-lock using this function. The only read-lock obtained
371   ** by a connection in read-uncommitted mode is on the sqlite_schema
372   ** table, and that lock is obtained in BtreeBeginTrans().  */
373   assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
374 
375   /* This function should only be called on a sharable b-tree after it
376   ** has been determined that no other b-tree holds a conflicting lock.  */
377   assert( p->sharable );
378   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
379 
380   /* First search the list for an existing lock on this table. */
381   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382     if( pIter->iTable==iTable && pIter->pBtree==p ){
383       pLock = pIter;
384       break;
385     }
386   }
387 
388   /* If the above search did not find a BtLock struct associating Btree p
389   ** with table iTable, allocate one and link it into the list.
390   */
391   if( !pLock ){
392     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393     if( !pLock ){
394       return SQLITE_NOMEM_BKPT;
395     }
396     pLock->iTable = iTable;
397     pLock->pBtree = p;
398     pLock->pNext = pBt->pLock;
399     pBt->pLock = pLock;
400   }
401 
402   /* Set the BtLock.eLock variable to the maximum of the current lock
403   ** and the requested lock. This means if a write-lock was already held
404   ** and a read-lock requested, we don't incorrectly downgrade the lock.
405   */
406   assert( WRITE_LOCK>READ_LOCK );
407   if( eLock>pLock->eLock ){
408     pLock->eLock = eLock;
409   }
410 
411   return SQLITE_OK;
412 }
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
414 
415 #ifndef SQLITE_OMIT_SHARED_CACHE
416 /*
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
419 **
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
423 */
424 static void clearAllSharedCacheTableLocks(Btree *p){
425   BtShared *pBt = p->pBt;
426   BtLock **ppIter = &pBt->pLock;
427 
428   assert( sqlite3BtreeHoldsMutex(p) );
429   assert( p->sharable || 0==*ppIter );
430   assert( p->inTrans>0 );
431 
432   while( *ppIter ){
433     BtLock *pLock = *ppIter;
434     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435     assert( pLock->pBtree->inTrans>=pLock->eLock );
436     if( pLock->pBtree==p ){
437       *ppIter = pLock->pNext;
438       assert( pLock->iTable!=1 || pLock==&p->lock );
439       if( pLock->iTable!=1 ){
440         sqlite3_free(pLock);
441       }
442     }else{
443       ppIter = &pLock->pNext;
444     }
445   }
446 
447   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448   if( pBt->pWriter==p ){
449     pBt->pWriter = 0;
450     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451   }else if( pBt->nTransaction==2 ){
452     /* This function is called when Btree p is concluding its
453     ** transaction. If there currently exists a writer, and p is not
454     ** that writer, then the number of locks held by connections other
455     ** than the writer must be about to drop to zero. In this case
456     ** set the BTS_PENDING flag to 0.
457     **
458     ** If there is not currently a writer, then BTS_PENDING must
459     ** be zero already. So this next line is harmless in that case.
460     */
461     pBt->btsFlags &= ~BTS_PENDING;
462   }
463 }
464 
465 /*
466 ** This function changes all write-locks held by Btree p into read-locks.
467 */
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469   BtShared *pBt = p->pBt;
470   if( pBt->pWriter==p ){
471     BtLock *pLock;
472     pBt->pWriter = 0;
473     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476       pLock->eLock = READ_LOCK;
477     }
478   }
479 }
480 
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
482 
483 static void releasePage(MemPage *pPage);         /* Forward reference */
484 static void releasePageOne(MemPage *pPage);      /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
486 
487 /*
488 ***** This routine is used inside of assert() only ****
489 **
490 ** Verify that the cursor holds the mutex on its BtShared
491 */
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494   return sqlite3_mutex_held(p->pBt->mutex);
495 }
496 
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed.  This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
504 */
505 static int cursorOwnsBtShared(BtCursor *p){
506   assert( cursorHoldsMutex(p) );
507   return (p->pBtree->db==p->pBt->db);
508 }
509 #endif
510 
511 /*
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
514 */
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
516 
517 /*
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
520 */
521 static void invalidateAllOverflowCache(BtShared *pBt){
522   BtCursor *p;
523   assert( sqlite3_mutex_held(pBt->mutex) );
524   for(p=pBt->pCursor; p; p=p->pNext){
525     invalidateOverflowCache(p);
526   }
527 }
528 
529 #ifndef SQLITE_OMIT_INCRBLOB
530 /*
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
534 **
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
538 **
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
542 */
543 static void invalidateIncrblobCursors(
544   Btree *pBtree,          /* The database file to check */
545   Pgno pgnoRoot,          /* The table that might be changing */
546   i64 iRow,               /* The rowid that might be changing */
547   int isClearTable        /* True if all rows are being deleted */
548 ){
549   BtCursor *p;
550   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 BtreeMovetoUnpacked() to do the work.
811 */
812 static int btreeMoveto(
813   BtCursor *pCur,     /* Cursor open on the btree to be searched */
814   const void *pKey,   /* Packed key if the btree is an index */
815   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
816   int bias,           /* Bias search to the high end */
817   int *pRes           /* Write search results here */
818 ){
819   int rc;                    /* Status code */
820   UnpackedRecord *pIdxKey;   /* Unpacked index key */
821 
822   if( pKey ){
823     KeyInfo *pKeyInfo = pCur->pKeyInfo;
824     assert( nKey==(i64)(int)nKey );
825     pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826     if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827     sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828     if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829       rc = SQLITE_CORRUPT_BKPT;
830     }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 to avoid a function call.
1229   */
1230   iKey = *pIter;
1231   if( iKey>=0x80 ){
1232     u8 *pEnd = &pIter[7];
1233     iKey &= 0x7f;
1234     while(1){
1235       iKey = (iKey<<7) | (*++pIter & 0x7f);
1236       if( (*pIter)<0x80 ) break;
1237       if( pIter>=pEnd ){
1238         iKey = (iKey<<8) | *++pIter;
1239         break;
1240       }
1241     }
1242   }
1243   pIter++;
1244 
1245   pInfo->nKey = *(i64*)&iKey;
1246   pInfo->nPayload = nPayload;
1247   pInfo->pPayload = pIter;
1248   testcase( nPayload==pPage->maxLocal );
1249   testcase( nPayload==pPage->maxLocal+1 );
1250   if( nPayload<=pPage->maxLocal ){
1251     /* This is the (easy) common case where the entire payload fits
1252     ** on the local page.  No overflow is required.
1253     */
1254     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1255     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1256     pInfo->nLocal = (u16)nPayload;
1257   }else{
1258     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1259   }
1260 }
1261 static void btreeParseCellPtrIndex(
1262   MemPage *pPage,         /* Page containing the cell */
1263   u8 *pCell,              /* Pointer to the cell text. */
1264   CellInfo *pInfo         /* Fill in this structure */
1265 ){
1266   u8 *pIter;              /* For scanning through pCell */
1267   u32 nPayload;           /* Number of bytes of cell payload */
1268 
1269   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1270   assert( pPage->leaf==0 || pPage->leaf==1 );
1271   assert( pPage->intKeyLeaf==0 );
1272   pIter = pCell + pPage->childPtrSize;
1273   nPayload = *pIter;
1274   if( nPayload>=0x80 ){
1275     u8 *pEnd = &pIter[8];
1276     nPayload &= 0x7f;
1277     do{
1278       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1279     }while( *(pIter)>=0x80 && pIter<pEnd );
1280   }
1281   pIter++;
1282   pInfo->nKey = nPayload;
1283   pInfo->nPayload = nPayload;
1284   pInfo->pPayload = pIter;
1285   testcase( nPayload==pPage->maxLocal );
1286   testcase( nPayload==pPage->maxLocal+1 );
1287   if( nPayload<=pPage->maxLocal ){
1288     /* This is the (easy) common case where the entire payload fits
1289     ** on the local page.  No overflow is required.
1290     */
1291     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1292     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1293     pInfo->nLocal = (u16)nPayload;
1294   }else{
1295     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1296   }
1297 }
1298 static void btreeParseCell(
1299   MemPage *pPage,         /* Page containing the cell */
1300   int iCell,              /* The cell index.  First cell is 0 */
1301   CellInfo *pInfo         /* Fill in this structure */
1302 ){
1303   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1304 }
1305 
1306 /*
1307 ** The following routines are implementations of the MemPage.xCellSize
1308 ** method.
1309 **
1310 ** Compute the total number of bytes that a Cell needs in the cell
1311 ** data area of the btree-page.  The return number includes the cell
1312 ** data header and the local payload, but not any overflow page or
1313 ** the space used by the cell pointer.
1314 **
1315 ** cellSizePtrNoPayload()    =>   table internal nodes
1316 ** cellSizePtr()             =>   all index nodes & table leaf nodes
1317 */
1318 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1319   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1320   u8 *pEnd;                                /* End mark for a varint */
1321   u32 nSize;                               /* Size value to return */
1322 
1323 #ifdef SQLITE_DEBUG
1324   /* The value returned by this function should always be the same as
1325   ** the (CellInfo.nSize) value found by doing a full parse of the
1326   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1327   ** this function verifies that this invariant is not violated. */
1328   CellInfo debuginfo;
1329   pPage->xParseCell(pPage, pCell, &debuginfo);
1330 #endif
1331 
1332   nSize = *pIter;
1333   if( nSize>=0x80 ){
1334     pEnd = &pIter[8];
1335     nSize &= 0x7f;
1336     do{
1337       nSize = (nSize<<7) | (*++pIter & 0x7f);
1338     }while( *(pIter)>=0x80 && pIter<pEnd );
1339   }
1340   pIter++;
1341   if( pPage->intKey ){
1342     /* pIter now points at the 64-bit integer key value, a variable length
1343     ** integer. The following block moves pIter to point at the first byte
1344     ** past the end of the key value. */
1345     pEnd = &pIter[9];
1346     while( (*pIter++)&0x80 && pIter<pEnd );
1347   }
1348   testcase( nSize==pPage->maxLocal );
1349   testcase( nSize==pPage->maxLocal+1 );
1350   if( nSize<=pPage->maxLocal ){
1351     nSize += (u32)(pIter - pCell);
1352     if( nSize<4 ) nSize = 4;
1353   }else{
1354     int minLocal = pPage->minLocal;
1355     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1356     testcase( nSize==pPage->maxLocal );
1357     testcase( nSize==pPage->maxLocal+1 );
1358     if( nSize>pPage->maxLocal ){
1359       nSize = minLocal;
1360     }
1361     nSize += 4 + (u16)(pIter - pCell);
1362   }
1363   assert( nSize==debuginfo.nSize || CORRUPT_DB );
1364   return (u16)nSize;
1365 }
1366 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1367   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1368   u8 *pEnd;              /* End mark for a varint */
1369 
1370 #ifdef SQLITE_DEBUG
1371   /* The value returned by this function should always be the same as
1372   ** the (CellInfo.nSize) value found by doing a full parse of the
1373   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1374   ** this function verifies that this invariant is not violated. */
1375   CellInfo debuginfo;
1376   pPage->xParseCell(pPage, pCell, &debuginfo);
1377 #else
1378   UNUSED_PARAMETER(pPage);
1379 #endif
1380 
1381   assert( pPage->childPtrSize==4 );
1382   pEnd = pIter + 9;
1383   while( (*pIter++)&0x80 && pIter<pEnd );
1384   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1385   return (u16)(pIter - pCell);
1386 }
1387 
1388 
1389 #ifdef SQLITE_DEBUG
1390 /* This variation on cellSizePtr() is used inside of assert() statements
1391 ** only. */
1392 static u16 cellSize(MemPage *pPage, int iCell){
1393   return pPage->xCellSize(pPage, findCell(pPage, iCell));
1394 }
1395 #endif
1396 
1397 #ifndef SQLITE_OMIT_AUTOVACUUM
1398 /*
1399 ** The cell pCell is currently part of page pSrc but will ultimately be part
1400 ** of pPage.  (pSrc and pPager are often the same.)  If pCell contains a
1401 ** pointer to an overflow page, insert an entry into the pointer-map for
1402 ** the overflow page that will be valid after pCell has been moved to pPage.
1403 */
1404 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1405   CellInfo info;
1406   if( *pRC ) return;
1407   assert( pCell!=0 );
1408   pPage->xParseCell(pPage, pCell, &info);
1409   if( info.nLocal<info.nPayload ){
1410     Pgno ovfl;
1411     if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1412       testcase( pSrc!=pPage );
1413       *pRC = SQLITE_CORRUPT_BKPT;
1414       return;
1415     }
1416     ovfl = get4byte(&pCell[info.nSize-4]);
1417     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1418   }
1419 }
1420 #endif
1421 
1422 
1423 /*
1424 ** Defragment the page given. This routine reorganizes cells within the
1425 ** page so that there are no free-blocks on the free-block list.
1426 **
1427 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1428 ** present in the page after this routine returns.
1429 **
1430 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1431 ** b-tree page so that there are no freeblocks or fragment bytes, all
1432 ** unused bytes are contained in the unallocated space region, and all
1433 ** cells are packed tightly at the end of the page.
1434 */
1435 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1436   int i;                     /* Loop counter */
1437   int pc;                    /* Address of the i-th cell */
1438   int hdr;                   /* Offset to the page header */
1439   int size;                  /* Size of a cell */
1440   int usableSize;            /* Number of usable bytes on a page */
1441   int cellOffset;            /* Offset to the cell pointer array */
1442   int cbrk;                  /* Offset to the cell content area */
1443   int nCell;                 /* Number of cells on the page */
1444   unsigned char *data;       /* The page data */
1445   unsigned char *temp;       /* Temp area for cell content */
1446   unsigned char *src;        /* Source of content */
1447   int iCellFirst;            /* First allowable cell index */
1448   int iCellLast;             /* Last possible cell index */
1449   int iCellStart;            /* First cell offset in input */
1450 
1451   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1452   assert( pPage->pBt!=0 );
1453   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1454   assert( pPage->nOverflow==0 );
1455   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1456   temp = 0;
1457   src = data = pPage->aData;
1458   hdr = pPage->hdrOffset;
1459   cellOffset = pPage->cellOffset;
1460   nCell = pPage->nCell;
1461   assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1462   iCellFirst = cellOffset + 2*nCell;
1463   usableSize = pPage->pBt->usableSize;
1464 
1465   /* This block handles pages with two or fewer free blocks and nMaxFrag
1466   ** or fewer fragmented bytes. In this case it is faster to move the
1467   ** two (or one) blocks of cells using memmove() and add the required
1468   ** offsets to each pointer in the cell-pointer array than it is to
1469   ** reconstruct the entire page.  */
1470   if( (int)data[hdr+7]<=nMaxFrag ){
1471     int iFree = get2byte(&data[hdr+1]);
1472     if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1473     if( iFree ){
1474       int iFree2 = get2byte(&data[iFree]);
1475       if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1476       if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1477         u8 *pEnd = &data[cellOffset + nCell*2];
1478         u8 *pAddr;
1479         int sz2 = 0;
1480         int sz = get2byte(&data[iFree+2]);
1481         int top = get2byte(&data[hdr+5]);
1482         if( top>=iFree ){
1483           return SQLITE_CORRUPT_PAGE(pPage);
1484         }
1485         if( iFree2 ){
1486           if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1487           sz2 = get2byte(&data[iFree2+2]);
1488           if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1489           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1490           sz += sz2;
1491         }else if( NEVER(iFree+sz>usableSize) ){
1492           return SQLITE_CORRUPT_PAGE(pPage);
1493         }
1494 
1495         cbrk = top+sz;
1496         assert( cbrk+(iFree-top) <= usableSize );
1497         memmove(&data[cbrk], &data[top], iFree-top);
1498         for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1499           pc = get2byte(pAddr);
1500           if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1501           else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1502         }
1503         goto defragment_out;
1504       }
1505     }
1506   }
1507 
1508   cbrk = usableSize;
1509   iCellLast = usableSize - 4;
1510   iCellStart = get2byte(&data[hdr+5]);
1511   for(i=0; i<nCell; i++){
1512     u8 *pAddr;     /* The i-th cell pointer */
1513     pAddr = &data[cellOffset + i*2];
1514     pc = get2byte(pAddr);
1515     testcase( pc==iCellFirst );
1516     testcase( pc==iCellLast );
1517     /* These conditions have already been verified in btreeInitPage()
1518     ** if PRAGMA cell_size_check=ON.
1519     */
1520     if( pc<iCellStart || pc>iCellLast ){
1521       return SQLITE_CORRUPT_PAGE(pPage);
1522     }
1523     assert( pc>=iCellStart && pc<=iCellLast );
1524     size = pPage->xCellSize(pPage, &src[pc]);
1525     cbrk -= size;
1526     if( cbrk<iCellStart || pc+size>usableSize ){
1527       return SQLITE_CORRUPT_PAGE(pPage);
1528     }
1529     assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1530     testcase( cbrk+size==usableSize );
1531     testcase( pc+size==usableSize );
1532     put2byte(pAddr, cbrk);
1533     if( temp==0 ){
1534       if( cbrk==pc ) continue;
1535       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1536       memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1537       src = temp;
1538     }
1539     memcpy(&data[cbrk], &src[pc], size);
1540   }
1541   data[hdr+7] = 0;
1542 
1543  defragment_out:
1544   assert( pPage->nFree>=0 );
1545   if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1546     return SQLITE_CORRUPT_PAGE(pPage);
1547   }
1548   assert( cbrk>=iCellFirst );
1549   put2byte(&data[hdr+5], cbrk);
1550   data[hdr+1] = 0;
1551   data[hdr+2] = 0;
1552   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1553   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1554   return SQLITE_OK;
1555 }
1556 
1557 /*
1558 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1559 ** size. If one can be found, return a pointer to the space and remove it
1560 ** from the free-list.
1561 **
1562 ** If no suitable space can be found on the free-list, return NULL.
1563 **
1564 ** This function may detect corruption within pPg.  If corruption is
1565 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1566 **
1567 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1568 ** will be ignored if adding the extra space to the fragmentation count
1569 ** causes the fragmentation count to exceed 60.
1570 */
1571 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1572   const int hdr = pPg->hdrOffset;            /* Offset to page header */
1573   u8 * const aData = pPg->aData;             /* Page data */
1574   int iAddr = hdr + 1;                       /* Address of ptr to pc */
1575   int pc = get2byte(&aData[iAddr]);          /* Address of a free slot */
1576   int x;                                     /* Excess size of the slot */
1577   int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */
1578   int size;                                  /* Size of the free slot */
1579 
1580   assert( pc>0 );
1581   while( pc<=maxPC ){
1582     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1583     ** freeblock form a big-endian integer which is the size of the freeblock
1584     ** in bytes, including the 4-byte header. */
1585     size = get2byte(&aData[pc+2]);
1586     if( (x = size - nByte)>=0 ){
1587       testcase( x==4 );
1588       testcase( x==3 );
1589       if( x<4 ){
1590         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1591         ** number of bytes in fragments may not exceed 60. */
1592         if( aData[hdr+7]>57 ) return 0;
1593 
1594         /* Remove the slot from the free-list. Update the number of
1595         ** fragmented bytes within the page. */
1596         memcpy(&aData[iAddr], &aData[pc], 2);
1597         aData[hdr+7] += (u8)x;
1598       }else if( x+pc > maxPC ){
1599         /* This slot extends off the end of the usable part of the page */
1600         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1601         return 0;
1602       }else{
1603         /* The slot remains on the free-list. Reduce its size to account
1604         ** for the portion used by the new allocation. */
1605         put2byte(&aData[pc+2], x);
1606       }
1607       return &aData[pc + x];
1608     }
1609     iAddr = pc;
1610     pc = get2byte(&aData[pc]);
1611     if( pc<=iAddr+size ){
1612       if( pc ){
1613         /* The next slot in the chain is not past the end of the current slot */
1614         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1615       }
1616       return 0;
1617     }
1618   }
1619   if( pc>maxPC+nByte-4 ){
1620     /* The free slot chain extends off the end of the page */
1621     *pRc = SQLITE_CORRUPT_PAGE(pPg);
1622   }
1623   return 0;
1624 }
1625 
1626 /*
1627 ** Allocate nByte bytes of space from within the B-Tree page passed
1628 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1629 ** of the first byte of allocated space. Return either SQLITE_OK or
1630 ** an error code (usually SQLITE_CORRUPT).
1631 **
1632 ** The caller guarantees that there is sufficient space to make the
1633 ** allocation.  This routine might need to defragment in order to bring
1634 ** all the space together, however.  This routine will avoid using
1635 ** the first two bytes past the cell pointer area since presumably this
1636 ** allocation is being made in order to insert a new cell, so we will
1637 ** also end up needing a new cell pointer.
1638 */
1639 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1640   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
1641   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
1642   int top;                             /* First byte of cell content area */
1643   int rc = SQLITE_OK;                  /* Integer return code */
1644   int gap;        /* First byte of gap between cell pointers and cell content */
1645 
1646   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1647   assert( pPage->pBt );
1648   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1649   assert( nByte>=0 );  /* Minimum cell size is 4 */
1650   assert( pPage->nFree>=nByte );
1651   assert( pPage->nOverflow==0 );
1652   assert( nByte < (int)(pPage->pBt->usableSize-8) );
1653 
1654   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1655   gap = pPage->cellOffset + 2*pPage->nCell;
1656   assert( gap<=65536 );
1657   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1658   ** and the reserved space is zero (the usual value for reserved space)
1659   ** then the cell content offset of an empty page wants to be 65536.
1660   ** However, that integer is too large to be stored in a 2-byte unsigned
1661   ** integer, so a value of 0 is used in its place. */
1662   top = get2byte(&data[hdr+5]);
1663   assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1664   if( gap>top ){
1665     if( top==0 && pPage->pBt->usableSize==65536 ){
1666       top = 65536;
1667     }else{
1668       return SQLITE_CORRUPT_PAGE(pPage);
1669     }
1670   }
1671 
1672   /* If there is enough space between gap and top for one more cell pointer,
1673   ** and if the freelist is not empty, then search the
1674   ** freelist looking for a slot big enough to satisfy the request.
1675   */
1676   testcase( gap+2==top );
1677   testcase( gap+1==top );
1678   testcase( gap==top );
1679   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1680     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1681     if( pSpace ){
1682       int g2;
1683       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1684       *pIdx = g2 = (int)(pSpace-data);
1685       if( g2<=gap ){
1686         return SQLITE_CORRUPT_PAGE(pPage);
1687       }else{
1688         return SQLITE_OK;
1689       }
1690     }else if( rc ){
1691       return rc;
1692     }
1693   }
1694 
1695   /* The request could not be fulfilled using a freelist slot.  Check
1696   ** to see if defragmentation is necessary.
1697   */
1698   testcase( gap+2+nByte==top );
1699   if( gap+2+nByte>top ){
1700     assert( pPage->nCell>0 || CORRUPT_DB );
1701     assert( pPage->nFree>=0 );
1702     rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1703     if( rc ) return rc;
1704     top = get2byteNotZero(&data[hdr+5]);
1705     assert( gap+2+nByte<=top );
1706   }
1707 
1708 
1709   /* Allocate memory from the gap in between the cell pointer array
1710   ** and the cell content area.  The btreeComputeFreeSpace() call has already
1711   ** validated the freelist.  Given that the freelist is valid, there
1712   ** is no way that the allocation can extend off the end of the page.
1713   ** The assert() below verifies the previous sentence.
1714   */
1715   top -= nByte;
1716   put2byte(&data[hdr+5], top);
1717   assert( top+nByte <= (int)pPage->pBt->usableSize );
1718   *pIdx = top;
1719   return SQLITE_OK;
1720 }
1721 
1722 /*
1723 ** Return a section of the pPage->aData to the freelist.
1724 ** The first byte of the new free block is pPage->aData[iStart]
1725 ** and the size of the block is iSize bytes.
1726 **
1727 ** Adjacent freeblocks are coalesced.
1728 **
1729 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1730 ** that routine will not detect overlap between cells or freeblocks.  Nor
1731 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1732 ** at the end of the page.  So do additional corruption checks inside this
1733 ** routine and return SQLITE_CORRUPT if any problems are found.
1734 */
1735 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1736   u16 iPtr;                             /* Address of ptr to next freeblock */
1737   u16 iFreeBlk;                         /* Address of the next freeblock */
1738   u8 hdr;                               /* Page header size.  0 or 100 */
1739   u8 nFrag = 0;                         /* Reduction in fragmentation */
1740   u16 iOrigSize = iSize;                /* Original value of iSize */
1741   u16 x;                                /* Offset to cell content area */
1742   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
1743   unsigned char *data = pPage->aData;   /* Page content */
1744 
1745   assert( pPage->pBt!=0 );
1746   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1747   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1748   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1749   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1750   assert( iSize>=4 );   /* Minimum cell size is 4 */
1751   assert( iStart<=pPage->pBt->usableSize-4 );
1752 
1753   /* The list of freeblocks must be in ascending order.  Find the
1754   ** spot on the list where iStart should be inserted.
1755   */
1756   hdr = pPage->hdrOffset;
1757   iPtr = hdr + 1;
1758   if( data[iPtr+1]==0 && data[iPtr]==0 ){
1759     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
1760   }else{
1761     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1762       if( iFreeBlk<iPtr+4 ){
1763         if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1764         return SQLITE_CORRUPT_PAGE(pPage);
1765       }
1766       iPtr = iFreeBlk;
1767     }
1768     if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1769       return SQLITE_CORRUPT_PAGE(pPage);
1770     }
1771     assert( iFreeBlk>iPtr || iFreeBlk==0 );
1772 
1773     /* At this point:
1774     **    iFreeBlk:   First freeblock after iStart, or zero if none
1775     **    iPtr:       The address of a pointer to iFreeBlk
1776     **
1777     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1778     */
1779     if( iFreeBlk && iEnd+3>=iFreeBlk ){
1780       nFrag = iFreeBlk - iEnd;
1781       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1782       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1783       if( iEnd > pPage->pBt->usableSize ){
1784         return SQLITE_CORRUPT_PAGE(pPage);
1785       }
1786       iSize = iEnd - iStart;
1787       iFreeBlk = get2byte(&data[iFreeBlk]);
1788     }
1789 
1790     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1791     ** pointer in the page header) then check to see if iStart should be
1792     ** coalesced onto the end of iPtr.
1793     */
1794     if( iPtr>hdr+1 ){
1795       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1796       if( iPtrEnd+3>=iStart ){
1797         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1798         nFrag += iStart - iPtrEnd;
1799         iSize = iEnd - iPtr;
1800         iStart = iPtr;
1801       }
1802     }
1803     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1804     data[hdr+7] -= nFrag;
1805   }
1806   x = get2byte(&data[hdr+5]);
1807   if( iStart<=x ){
1808     /* The new freeblock is at the beginning of the cell content area,
1809     ** so just extend the cell content area rather than create another
1810     ** freelist entry */
1811     if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1812     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1813     put2byte(&data[hdr+1], iFreeBlk);
1814     put2byte(&data[hdr+5], iEnd);
1815   }else{
1816     /* Insert the new freeblock into the freelist */
1817     put2byte(&data[iPtr], iStart);
1818   }
1819   if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1820     /* Overwrite deleted information with zeros when the secure_delete
1821     ** option is enabled */
1822     memset(&data[iStart], 0, iSize);
1823   }
1824   put2byte(&data[iStart], iFreeBlk);
1825   put2byte(&data[iStart+2], iSize);
1826   pPage->nFree += iOrigSize;
1827   return SQLITE_OK;
1828 }
1829 
1830 /*
1831 ** Decode the flags byte (the first byte of the header) for a page
1832 ** and initialize fields of the MemPage structure accordingly.
1833 **
1834 ** Only the following combinations are supported.  Anything different
1835 ** indicates a corrupt database files:
1836 **
1837 **         PTF_ZERODATA
1838 **         PTF_ZERODATA | PTF_LEAF
1839 **         PTF_LEAFDATA | PTF_INTKEY
1840 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1841 */
1842 static int decodeFlags(MemPage *pPage, int flagByte){
1843   BtShared *pBt;     /* A copy of pPage->pBt */
1844 
1845   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1846   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1847   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
1848   flagByte &= ~PTF_LEAF;
1849   pPage->childPtrSize = 4-4*pPage->leaf;
1850   pPage->xCellSize = cellSizePtr;
1851   pBt = pPage->pBt;
1852   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1853     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1854     ** interior table b-tree page. */
1855     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1856     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1857     ** leaf table b-tree page. */
1858     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1859     pPage->intKey = 1;
1860     if( pPage->leaf ){
1861       pPage->intKeyLeaf = 1;
1862       pPage->xParseCell = btreeParseCellPtr;
1863     }else{
1864       pPage->intKeyLeaf = 0;
1865       pPage->xCellSize = cellSizePtrNoPayload;
1866       pPage->xParseCell = btreeParseCellPtrNoPayload;
1867     }
1868     pPage->maxLocal = pBt->maxLeaf;
1869     pPage->minLocal = pBt->minLeaf;
1870   }else if( flagByte==PTF_ZERODATA ){
1871     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1872     ** interior index b-tree page. */
1873     assert( (PTF_ZERODATA)==2 );
1874     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1875     ** leaf index b-tree page. */
1876     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1877     pPage->intKey = 0;
1878     pPage->intKeyLeaf = 0;
1879     pPage->xParseCell = btreeParseCellPtrIndex;
1880     pPage->maxLocal = pBt->maxLocal;
1881     pPage->minLocal = pBt->minLocal;
1882   }else{
1883     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1884     ** an error. */
1885     return SQLITE_CORRUPT_PAGE(pPage);
1886   }
1887   pPage->max1bytePayload = pBt->max1bytePayload;
1888   return SQLITE_OK;
1889 }
1890 
1891 /*
1892 ** Compute the amount of freespace on the page.  In other words, fill
1893 ** in the pPage->nFree field.
1894 */
1895 static int btreeComputeFreeSpace(MemPage *pPage){
1896   int pc;            /* Address of a freeblock within pPage->aData[] */
1897   u8 hdr;            /* Offset to beginning of page header */
1898   u8 *data;          /* Equal to pPage->aData */
1899   int usableSize;    /* Amount of usable space on each page */
1900   int nFree;         /* Number of unused bytes on the page */
1901   int top;           /* First byte of the cell content area */
1902   int iCellFirst;    /* First allowable cell or freeblock offset */
1903   int iCellLast;     /* Last possible cell or freeblock offset */
1904 
1905   assert( pPage->pBt!=0 );
1906   assert( pPage->pBt->db!=0 );
1907   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1908   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1909   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1910   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1911   assert( pPage->isInit==1 );
1912   assert( pPage->nFree<0 );
1913 
1914   usableSize = pPage->pBt->usableSize;
1915   hdr = pPage->hdrOffset;
1916   data = pPage->aData;
1917   /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1918   ** the start of the cell content area. A zero value for this integer is
1919   ** interpreted as 65536. */
1920   top = get2byteNotZero(&data[hdr+5]);
1921   iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1922   iCellLast = usableSize - 4;
1923 
1924   /* Compute the total free space on the page
1925   ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1926   ** start of the first freeblock on the page, or is zero if there are no
1927   ** freeblocks. */
1928   pc = get2byte(&data[hdr+1]);
1929   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
1930   if( pc>0 ){
1931     u32 next, size;
1932     if( pc<top ){
1933       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1934       ** always be at least one cell before the first freeblock.
1935       */
1936       return SQLITE_CORRUPT_PAGE(pPage);
1937     }
1938     while( 1 ){
1939       if( pc>iCellLast ){
1940         /* Freeblock off the end of the page */
1941         return SQLITE_CORRUPT_PAGE(pPage);
1942       }
1943       next = get2byte(&data[pc]);
1944       size = get2byte(&data[pc+2]);
1945       nFree = nFree + size;
1946       if( next<=pc+size+3 ) break;
1947       pc = next;
1948     }
1949     if( next>0 ){
1950       /* Freeblock not in ascending order */
1951       return SQLITE_CORRUPT_PAGE(pPage);
1952     }
1953     if( pc+size>(unsigned int)usableSize ){
1954       /* Last freeblock extends past page end */
1955       return SQLITE_CORRUPT_PAGE(pPage);
1956     }
1957   }
1958 
1959   /* At this point, nFree contains the sum of the offset to the start
1960   ** of the cell-content area plus the number of free bytes within
1961   ** the cell-content area. If this is greater than the usable-size
1962   ** of the page, then the page must be corrupted. This check also
1963   ** serves to verify that the offset to the start of the cell-content
1964   ** area, according to the page header, lies within the page.
1965   */
1966   if( nFree>usableSize || nFree<iCellFirst ){
1967     return SQLITE_CORRUPT_PAGE(pPage);
1968   }
1969   pPage->nFree = (u16)(nFree - iCellFirst);
1970   return SQLITE_OK;
1971 }
1972 
1973 /*
1974 ** Do additional sanity check after btreeInitPage() if
1975 ** PRAGMA cell_size_check=ON
1976 */
1977 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1978   int iCellFirst;    /* First allowable cell or freeblock offset */
1979   int iCellLast;     /* Last possible cell or freeblock offset */
1980   int i;             /* Index into the cell pointer array */
1981   int sz;            /* Size of a cell */
1982   int pc;            /* Address of a freeblock within pPage->aData[] */
1983   u8 *data;          /* Equal to pPage->aData */
1984   int usableSize;    /* Maximum usable space on the page */
1985   int cellOffset;    /* Start of cell content area */
1986 
1987   iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1988   usableSize = pPage->pBt->usableSize;
1989   iCellLast = usableSize - 4;
1990   data = pPage->aData;
1991   cellOffset = pPage->cellOffset;
1992   if( !pPage->leaf ) iCellLast--;
1993   for(i=0; i<pPage->nCell; i++){
1994     pc = get2byteAligned(&data[cellOffset+i*2]);
1995     testcase( pc==iCellFirst );
1996     testcase( pc==iCellLast );
1997     if( pc<iCellFirst || pc>iCellLast ){
1998       return SQLITE_CORRUPT_PAGE(pPage);
1999     }
2000     sz = pPage->xCellSize(pPage, &data[pc]);
2001     testcase( pc+sz==usableSize );
2002     if( pc+sz>usableSize ){
2003       return SQLITE_CORRUPT_PAGE(pPage);
2004     }
2005   }
2006   return SQLITE_OK;
2007 }
2008 
2009 /*
2010 ** Initialize the auxiliary information for a disk block.
2011 **
2012 ** Return SQLITE_OK on success.  If we see that the page does
2013 ** not contain a well-formed database page, then return
2014 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
2015 ** guarantee that the page is well-formed.  It only shows that
2016 ** we failed to detect any corruption.
2017 */
2018 static int btreeInitPage(MemPage *pPage){
2019   u8 *data;          /* Equal to pPage->aData */
2020   BtShared *pBt;        /* The main btree structure */
2021 
2022   assert( pPage->pBt!=0 );
2023   assert( pPage->pBt->db!=0 );
2024   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2025   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2026   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2027   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2028   assert( pPage->isInit==0 );
2029 
2030   pBt = pPage->pBt;
2031   data = pPage->aData + pPage->hdrOffset;
2032   /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2033   ** the b-tree page type. */
2034   if( decodeFlags(pPage, data[0]) ){
2035     return SQLITE_CORRUPT_PAGE(pPage);
2036   }
2037   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2038   pPage->maskPage = (u16)(pBt->pageSize - 1);
2039   pPage->nOverflow = 0;
2040   pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2041   pPage->aCellIdx = data + pPage->childPtrSize + 8;
2042   pPage->aDataEnd = pPage->aData + pBt->usableSize;
2043   pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2044   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2045   ** number of cells on the page. */
2046   pPage->nCell = get2byte(&data[3]);
2047   if( pPage->nCell>MX_CELL(pBt) ){
2048     /* To many cells for a single page.  The page must be corrupt */
2049     return SQLITE_CORRUPT_PAGE(pPage);
2050   }
2051   testcase( pPage->nCell==MX_CELL(pBt) );
2052   /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2053   ** possible for a root page of a table that contains no rows) then the
2054   ** offset to the cell content area will equal the page size minus the
2055   ** bytes of reserved space. */
2056   assert( pPage->nCell>0
2057        || get2byteNotZero(&data[5])==(int)pBt->usableSize
2058        || CORRUPT_DB );
2059   pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */
2060   pPage->isInit = 1;
2061   if( pBt->db->flags & SQLITE_CellSizeCk ){
2062     return btreeCellSizeCheck(pPage);
2063   }
2064   return SQLITE_OK;
2065 }
2066 
2067 /*
2068 ** Set up a raw page so that it looks like a database page holding
2069 ** no entries.
2070 */
2071 static void zeroPage(MemPage *pPage, int flags){
2072   unsigned char *data = pPage->aData;
2073   BtShared *pBt = pPage->pBt;
2074   u8 hdr = pPage->hdrOffset;
2075   u16 first;
2076 
2077   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2078   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2079   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2080   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2081   assert( sqlite3_mutex_held(pBt->mutex) );
2082   if( pBt->btsFlags & BTS_FAST_SECURE ){
2083     memset(&data[hdr], 0, pBt->usableSize - hdr);
2084   }
2085   data[hdr] = (char)flags;
2086   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2087   memset(&data[hdr+1], 0, 4);
2088   data[hdr+7] = 0;
2089   put2byte(&data[hdr+5], pBt->usableSize);
2090   pPage->nFree = (u16)(pBt->usableSize - first);
2091   decodeFlags(pPage, flags);
2092   pPage->cellOffset = first;
2093   pPage->aDataEnd = &data[pBt->usableSize];
2094   pPage->aCellIdx = &data[first];
2095   pPage->aDataOfst = &data[pPage->childPtrSize];
2096   pPage->nOverflow = 0;
2097   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2098   pPage->maskPage = (u16)(pBt->pageSize - 1);
2099   pPage->nCell = 0;
2100   pPage->isInit = 1;
2101 }
2102 
2103 
2104 /*
2105 ** Convert a DbPage obtained from the pager into a MemPage used by
2106 ** the btree layer.
2107 */
2108 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2109   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2110   if( pgno!=pPage->pgno ){
2111     pPage->aData = sqlite3PagerGetData(pDbPage);
2112     pPage->pDbPage = pDbPage;
2113     pPage->pBt = pBt;
2114     pPage->pgno = pgno;
2115     pPage->hdrOffset = pgno==1 ? 100 : 0;
2116   }
2117   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2118   return pPage;
2119 }
2120 
2121 /*
2122 ** Get a page from the pager.  Initialize the MemPage.pBt and
2123 ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
2124 **
2125 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2126 ** about the content of the page at this time.  So do not go to the disk
2127 ** to fetch the content.  Just fill in the content with zeros for now.
2128 ** If in the future we call sqlite3PagerWrite() on this page, that
2129 ** means we have started to be concerned about content and the disk
2130 ** read should occur at that point.
2131 */
2132 static int btreeGetPage(
2133   BtShared *pBt,       /* The btree */
2134   Pgno pgno,           /* Number of the page to fetch */
2135   MemPage **ppPage,    /* Return the page in this parameter */
2136   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2137 ){
2138   int rc;
2139   DbPage *pDbPage;
2140 
2141   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2142   assert( sqlite3_mutex_held(pBt->mutex) );
2143   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2144   if( rc ) return rc;
2145   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2146   return SQLITE_OK;
2147 }
2148 
2149 /*
2150 ** Retrieve a page from the pager cache. If the requested page is not
2151 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2152 ** MemPage.aData elements if needed.
2153 */
2154 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2155   DbPage *pDbPage;
2156   assert( sqlite3_mutex_held(pBt->mutex) );
2157   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2158   if( pDbPage ){
2159     return btreePageFromDbPage(pDbPage, pgno, pBt);
2160   }
2161   return 0;
2162 }
2163 
2164 /*
2165 ** Return the size of the database file in pages. If there is any kind of
2166 ** error, return ((unsigned int)-1).
2167 */
2168 static Pgno btreePagecount(BtShared *pBt){
2169   return pBt->nPage;
2170 }
2171 Pgno sqlite3BtreeLastPage(Btree *p){
2172   assert( sqlite3BtreeHoldsMutex(p) );
2173   return btreePagecount(p->pBt);
2174 }
2175 
2176 /*
2177 ** Get a page from the pager and initialize it.
2178 **
2179 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2180 ** call.  Do additional sanity checking on the page in this case.
2181 ** And if the fetch fails, this routine must decrement pCur->iPage.
2182 **
2183 ** The page is fetched as read-write unless pCur is not NULL and is
2184 ** a read-only cursor.
2185 **
2186 ** If an error occurs, then *ppPage is undefined. It
2187 ** may remain unchanged, or it may be set to an invalid value.
2188 */
2189 static int getAndInitPage(
2190   BtShared *pBt,                  /* The database file */
2191   Pgno pgno,                      /* Number of the page to get */
2192   MemPage **ppPage,               /* Write the page pointer here */
2193   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
2194   int bReadOnly                   /* True for a read-only page */
2195 ){
2196   int rc;
2197   DbPage *pDbPage;
2198   assert( sqlite3_mutex_held(pBt->mutex) );
2199   assert( pCur==0 || ppPage==&pCur->pPage );
2200   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2201   assert( pCur==0 || pCur->iPage>0 );
2202 
2203   if( pgno>btreePagecount(pBt) ){
2204     rc = SQLITE_CORRUPT_BKPT;
2205     goto getAndInitPage_error1;
2206   }
2207   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2208   if( rc ){
2209     goto getAndInitPage_error1;
2210   }
2211   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2212   if( (*ppPage)->isInit==0 ){
2213     btreePageFromDbPage(pDbPage, pgno, pBt);
2214     rc = btreeInitPage(*ppPage);
2215     if( rc!=SQLITE_OK ){
2216       goto getAndInitPage_error2;
2217     }
2218   }
2219   assert( (*ppPage)->pgno==pgno );
2220   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2221 
2222   /* If obtaining a child page for a cursor, we must verify that the page is
2223   ** compatible with the root page. */
2224   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2225     rc = SQLITE_CORRUPT_PGNO(pgno);
2226     goto getAndInitPage_error2;
2227   }
2228   return SQLITE_OK;
2229 
2230 getAndInitPage_error2:
2231   releasePage(*ppPage);
2232 getAndInitPage_error1:
2233   if( pCur ){
2234     pCur->iPage--;
2235     pCur->pPage = pCur->apPage[pCur->iPage];
2236   }
2237   testcase( pgno==0 );
2238   assert( pgno!=0 || rc==SQLITE_CORRUPT );
2239   return rc;
2240 }
2241 
2242 /*
2243 ** Release a MemPage.  This should be called once for each prior
2244 ** call to btreeGetPage.
2245 **
2246 ** Page1 is a special case and must be released using releasePageOne().
2247 */
2248 static void releasePageNotNull(MemPage *pPage){
2249   assert( pPage->aData );
2250   assert( pPage->pBt );
2251   assert( pPage->pDbPage!=0 );
2252   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2253   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2254   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2255   sqlite3PagerUnrefNotNull(pPage->pDbPage);
2256 }
2257 static void releasePage(MemPage *pPage){
2258   if( pPage ) releasePageNotNull(pPage);
2259 }
2260 static void releasePageOne(MemPage *pPage){
2261   assert( pPage!=0 );
2262   assert( pPage->aData );
2263   assert( pPage->pBt );
2264   assert( pPage->pDbPage!=0 );
2265   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2266   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2267   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2268   sqlite3PagerUnrefPageOne(pPage->pDbPage);
2269 }
2270 
2271 /*
2272 ** Get an unused page.
2273 **
2274 ** This works just like btreeGetPage() with the addition:
2275 **
2276 **   *  If the page is already in use for some other purpose, immediately
2277 **      release it and return an SQLITE_CURRUPT error.
2278 **   *  Make sure the isInit flag is clear
2279 */
2280 static int btreeGetUnusedPage(
2281   BtShared *pBt,       /* The btree */
2282   Pgno pgno,           /* Number of the page to fetch */
2283   MemPage **ppPage,    /* Return the page in this parameter */
2284   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2285 ){
2286   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2287   if( rc==SQLITE_OK ){
2288     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2289       releasePage(*ppPage);
2290       *ppPage = 0;
2291       return SQLITE_CORRUPT_BKPT;
2292     }
2293     (*ppPage)->isInit = 0;
2294   }else{
2295     *ppPage = 0;
2296   }
2297   return rc;
2298 }
2299 
2300 
2301 /*
2302 ** During a rollback, when the pager reloads information into the cache
2303 ** so that the cache is restored to its original state at the start of
2304 ** the transaction, for each page restored this routine is called.
2305 **
2306 ** This routine needs to reset the extra data section at the end of the
2307 ** page to agree with the restored data.
2308 */
2309 static void pageReinit(DbPage *pData){
2310   MemPage *pPage;
2311   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2312   assert( sqlite3PagerPageRefcount(pData)>0 );
2313   if( pPage->isInit ){
2314     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2315     pPage->isInit = 0;
2316     if( sqlite3PagerPageRefcount(pData)>1 ){
2317       /* pPage might not be a btree page;  it might be an overflow page
2318       ** or ptrmap page or a free page.  In those cases, the following
2319       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2320       ** But no harm is done by this.  And it is very important that
2321       ** btreeInitPage() be called on every btree page so we make
2322       ** the call for every page that comes in for re-initing. */
2323       btreeInitPage(pPage);
2324     }
2325   }
2326 }
2327 
2328 /*
2329 ** Invoke the busy handler for a btree.
2330 */
2331 static int btreeInvokeBusyHandler(void *pArg){
2332   BtShared *pBt = (BtShared*)pArg;
2333   assert( pBt->db );
2334   assert( sqlite3_mutex_held(pBt->db->mutex) );
2335   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2336 }
2337 
2338 /*
2339 ** Open a database file.
2340 **
2341 ** zFilename is the name of the database file.  If zFilename is NULL
2342 ** then an ephemeral database is created.  The ephemeral database might
2343 ** be exclusively in memory, or it might use a disk-based memory cache.
2344 ** Either way, the ephemeral database will be automatically deleted
2345 ** when sqlite3BtreeClose() is called.
2346 **
2347 ** If zFilename is ":memory:" then an in-memory database is created
2348 ** that is automatically destroyed when it is closed.
2349 **
2350 ** The "flags" parameter is a bitmask that might contain bits like
2351 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2352 **
2353 ** If the database is already opened in the same database connection
2354 ** and we are in shared cache mode, then the open will fail with an
2355 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
2356 ** objects in the same database connection since doing so will lead
2357 ** to problems with locking.
2358 */
2359 int sqlite3BtreeOpen(
2360   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
2361   const char *zFilename,  /* Name of the file containing the BTree database */
2362   sqlite3 *db,            /* Associated database handle */
2363   Btree **ppBtree,        /* Pointer to new Btree object written here */
2364   int flags,              /* Options */
2365   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
2366 ){
2367   BtShared *pBt = 0;             /* Shared part of btree structure */
2368   Btree *p;                      /* Handle to return */
2369   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
2370   int rc = SQLITE_OK;            /* Result code from this function */
2371   u8 nReserve;                   /* Byte of unused space on each page */
2372   unsigned char zDbHeader[100];  /* Database header content */
2373 
2374   /* True if opening an ephemeral, temporary database */
2375   const int isTempDb = zFilename==0 || zFilename[0]==0;
2376 
2377   /* Set the variable isMemdb to true for an in-memory database, or
2378   ** false for a file-based database.
2379   */
2380 #ifdef SQLITE_OMIT_MEMORYDB
2381   const int isMemdb = 0;
2382 #else
2383   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2384                        || (isTempDb && sqlite3TempInMemory(db))
2385                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2386 #endif
2387 
2388   assert( db!=0 );
2389   assert( pVfs!=0 );
2390   assert( sqlite3_mutex_held(db->mutex) );
2391   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
2392 
2393   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2394   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2395 
2396   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2397   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2398 
2399   if( isMemdb ){
2400     flags |= BTREE_MEMORY;
2401   }
2402   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2403     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2404   }
2405   p = sqlite3MallocZero(sizeof(Btree));
2406   if( !p ){
2407     return SQLITE_NOMEM_BKPT;
2408   }
2409   p->inTrans = TRANS_NONE;
2410   p->db = db;
2411 #ifndef SQLITE_OMIT_SHARED_CACHE
2412   p->lock.pBtree = p;
2413   p->lock.iTable = 1;
2414 #endif
2415 
2416 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2417   /*
2418   ** If this Btree is a candidate for shared cache, try to find an
2419   ** existing BtShared object that we can share with
2420   */
2421   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2422     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2423       int nFilename = sqlite3Strlen30(zFilename)+1;
2424       int nFullPathname = pVfs->mxPathname+1;
2425       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2426       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2427 
2428       p->sharable = 1;
2429       if( !zFullPathname ){
2430         sqlite3_free(p);
2431         return SQLITE_NOMEM_BKPT;
2432       }
2433       if( isMemdb ){
2434         memcpy(zFullPathname, zFilename, nFilename);
2435       }else{
2436         rc = sqlite3OsFullPathname(pVfs, zFilename,
2437                                    nFullPathname, zFullPathname);
2438         if( rc ){
2439           if( rc==SQLITE_OK_SYMLINK ){
2440             rc = SQLITE_OK;
2441           }else{
2442             sqlite3_free(zFullPathname);
2443             sqlite3_free(p);
2444             return rc;
2445           }
2446         }
2447       }
2448 #if SQLITE_THREADSAFE
2449       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2450       sqlite3_mutex_enter(mutexOpen);
2451       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2452       sqlite3_mutex_enter(mutexShared);
2453 #endif
2454       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2455         assert( pBt->nRef>0 );
2456         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2457                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2458           int iDb;
2459           for(iDb=db->nDb-1; iDb>=0; iDb--){
2460             Btree *pExisting = db->aDb[iDb].pBt;
2461             if( pExisting && pExisting->pBt==pBt ){
2462               sqlite3_mutex_leave(mutexShared);
2463               sqlite3_mutex_leave(mutexOpen);
2464               sqlite3_free(zFullPathname);
2465               sqlite3_free(p);
2466               return SQLITE_CONSTRAINT;
2467             }
2468           }
2469           p->pBt = pBt;
2470           pBt->nRef++;
2471           break;
2472         }
2473       }
2474       sqlite3_mutex_leave(mutexShared);
2475       sqlite3_free(zFullPathname);
2476     }
2477 #ifdef SQLITE_DEBUG
2478     else{
2479       /* In debug mode, we mark all persistent databases as sharable
2480       ** even when they are not.  This exercises the locking code and
2481       ** gives more opportunity for asserts(sqlite3_mutex_held())
2482       ** statements to find locking problems.
2483       */
2484       p->sharable = 1;
2485     }
2486 #endif
2487   }
2488 #endif
2489   if( pBt==0 ){
2490     /*
2491     ** The following asserts make sure that structures used by the btree are
2492     ** the right size.  This is to guard against size changes that result
2493     ** when compiling on a different architecture.
2494     */
2495     assert( sizeof(i64)==8 );
2496     assert( sizeof(u64)==8 );
2497     assert( sizeof(u32)==4 );
2498     assert( sizeof(u16)==2 );
2499     assert( sizeof(Pgno)==4 );
2500 
2501     pBt = sqlite3MallocZero( sizeof(*pBt) );
2502     if( pBt==0 ){
2503       rc = SQLITE_NOMEM_BKPT;
2504       goto btree_open_out;
2505     }
2506     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2507                           sizeof(MemPage), flags, vfsFlags, pageReinit);
2508     if( rc==SQLITE_OK ){
2509       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2510       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2511     }
2512     if( rc!=SQLITE_OK ){
2513       goto btree_open_out;
2514     }
2515     pBt->openFlags = (u8)flags;
2516     pBt->db = db;
2517     sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2518     p->pBt = pBt;
2519 
2520     pBt->pCursor = 0;
2521     pBt->pPage1 = 0;
2522     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2523 #if defined(SQLITE_SECURE_DELETE)
2524     pBt->btsFlags |= BTS_SECURE_DELETE;
2525 #elif defined(SQLITE_FAST_SECURE_DELETE)
2526     pBt->btsFlags |= BTS_OVERWRITE;
2527 #endif
2528     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2529     ** determined by the 2-byte integer located at an offset of 16 bytes from
2530     ** the beginning of the database file. */
2531     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2532     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2533          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2534       pBt->pageSize = 0;
2535 #ifndef SQLITE_OMIT_AUTOVACUUM
2536       /* If the magic name ":memory:" will create an in-memory database, then
2537       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2538       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2539       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2540       ** regular file-name. In this case the auto-vacuum applies as per normal.
2541       */
2542       if( zFilename && !isMemdb ){
2543         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2544         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2545       }
2546 #endif
2547       nReserve = 0;
2548     }else{
2549       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2550       ** determined by the one-byte unsigned integer found at an offset of 20
2551       ** into the database file header. */
2552       nReserve = zDbHeader[20];
2553       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2554 #ifndef SQLITE_OMIT_AUTOVACUUM
2555       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2556       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2557 #endif
2558     }
2559     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2560     if( rc ) goto btree_open_out;
2561     pBt->usableSize = pBt->pageSize - nReserve;
2562     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
2563 
2564 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2565     /* Add the new BtShared object to the linked list sharable BtShareds.
2566     */
2567     pBt->nRef = 1;
2568     if( p->sharable ){
2569       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2570       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2571       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2572         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2573         if( pBt->mutex==0 ){
2574           rc = SQLITE_NOMEM_BKPT;
2575           goto btree_open_out;
2576         }
2577       }
2578       sqlite3_mutex_enter(mutexShared);
2579       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2580       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2581       sqlite3_mutex_leave(mutexShared);
2582     }
2583 #endif
2584   }
2585 
2586 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2587   /* If the new Btree uses a sharable pBtShared, then link the new
2588   ** Btree into the list of all sharable Btrees for the same connection.
2589   ** The list is kept in ascending order by pBt address.
2590   */
2591   if( p->sharable ){
2592     int i;
2593     Btree *pSib;
2594     for(i=0; i<db->nDb; i++){
2595       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2596         while( pSib->pPrev ){ pSib = pSib->pPrev; }
2597         if( (uptr)p->pBt<(uptr)pSib->pBt ){
2598           p->pNext = pSib;
2599           p->pPrev = 0;
2600           pSib->pPrev = p;
2601         }else{
2602           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2603             pSib = pSib->pNext;
2604           }
2605           p->pNext = pSib->pNext;
2606           p->pPrev = pSib;
2607           if( p->pNext ){
2608             p->pNext->pPrev = p;
2609           }
2610           pSib->pNext = p;
2611         }
2612         break;
2613       }
2614     }
2615   }
2616 #endif
2617   *ppBtree = p;
2618 
2619 btree_open_out:
2620   if( rc!=SQLITE_OK ){
2621     if( pBt && pBt->pPager ){
2622       sqlite3PagerClose(pBt->pPager, 0);
2623     }
2624     sqlite3_free(pBt);
2625     sqlite3_free(p);
2626     *ppBtree = 0;
2627   }else{
2628     sqlite3_file *pFile;
2629 
2630     /* If the B-Tree was successfully opened, set the pager-cache size to the
2631     ** default value. Except, when opening on an existing shared pager-cache,
2632     ** do not change the pager-cache size.
2633     */
2634     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2635       sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2636     }
2637 
2638     pFile = sqlite3PagerFile(pBt->pPager);
2639     if( pFile->pMethods ){
2640       sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2641     }
2642   }
2643   if( mutexOpen ){
2644     assert( sqlite3_mutex_held(mutexOpen) );
2645     sqlite3_mutex_leave(mutexOpen);
2646   }
2647   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2648   return rc;
2649 }
2650 
2651 /*
2652 ** Decrement the BtShared.nRef counter.  When it reaches zero,
2653 ** remove the BtShared structure from the sharing list.  Return
2654 ** true if the BtShared.nRef counter reaches zero and return
2655 ** false if it is still positive.
2656 */
2657 static int removeFromSharingList(BtShared *pBt){
2658 #ifndef SQLITE_OMIT_SHARED_CACHE
2659   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2660   BtShared *pList;
2661   int removed = 0;
2662 
2663   assert( sqlite3_mutex_notheld(pBt->mutex) );
2664   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2665   sqlite3_mutex_enter(pMainMtx);
2666   pBt->nRef--;
2667   if( pBt->nRef<=0 ){
2668     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2669       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2670     }else{
2671       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2672       while( ALWAYS(pList) && pList->pNext!=pBt ){
2673         pList=pList->pNext;
2674       }
2675       if( ALWAYS(pList) ){
2676         pList->pNext = pBt->pNext;
2677       }
2678     }
2679     if( SQLITE_THREADSAFE ){
2680       sqlite3_mutex_free(pBt->mutex);
2681     }
2682     removed = 1;
2683   }
2684   sqlite3_mutex_leave(pMainMtx);
2685   return removed;
2686 #else
2687   return 1;
2688 #endif
2689 }
2690 
2691 /*
2692 ** Make sure pBt->pTmpSpace points to an allocation of
2693 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2694 ** pointer.
2695 */
2696 static void allocateTempSpace(BtShared *pBt){
2697   if( !pBt->pTmpSpace ){
2698     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2699 
2700     /* One of the uses of pBt->pTmpSpace is to format cells before
2701     ** inserting them into a leaf page (function fillInCell()). If
2702     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2703     ** by the various routines that manipulate binary cells. Which
2704     ** can mean that fillInCell() only initializes the first 2 or 3
2705     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2706     ** it into a database page. This is not actually a problem, but it
2707     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2708     ** data is passed to system call write(). So to avoid this error,
2709     ** zero the first 4 bytes of temp space here.
2710     **
2711     ** Also:  Provide four bytes of initialized space before the
2712     ** beginning of pTmpSpace as an area available to prepend the
2713     ** left-child pointer to the beginning of a cell.
2714     */
2715     if( pBt->pTmpSpace ){
2716       memset(pBt->pTmpSpace, 0, 8);
2717       pBt->pTmpSpace += 4;
2718     }
2719   }
2720 }
2721 
2722 /*
2723 ** Free the pBt->pTmpSpace allocation
2724 */
2725 static void freeTempSpace(BtShared *pBt){
2726   if( pBt->pTmpSpace ){
2727     pBt->pTmpSpace -= 4;
2728     sqlite3PageFree(pBt->pTmpSpace);
2729     pBt->pTmpSpace = 0;
2730   }
2731 }
2732 
2733 /*
2734 ** Close an open database and invalidate all cursors.
2735 */
2736 int sqlite3BtreeClose(Btree *p){
2737   BtShared *pBt = p->pBt;
2738 
2739   /* Close all cursors opened via this handle.  */
2740   assert( sqlite3_mutex_held(p->db->mutex) );
2741   sqlite3BtreeEnter(p);
2742 
2743   /* Verify that no other cursors have this Btree open */
2744 #ifdef SQLITE_DEBUG
2745   {
2746     BtCursor *pCur = pBt->pCursor;
2747     while( pCur ){
2748       BtCursor *pTmp = pCur;
2749       pCur = pCur->pNext;
2750       assert( pTmp->pBtree!=p );
2751 
2752     }
2753   }
2754 #endif
2755 
2756   /* Rollback any active transaction and free the handle structure.
2757   ** The call to sqlite3BtreeRollback() drops any table-locks held by
2758   ** this handle.
2759   */
2760   sqlite3BtreeRollback(p, SQLITE_OK, 0);
2761   sqlite3BtreeLeave(p);
2762 
2763   /* If there are still other outstanding references to the shared-btree
2764   ** structure, return now. The remainder of this procedure cleans
2765   ** up the shared-btree.
2766   */
2767   assert( p->wantToLock==0 && p->locked==0 );
2768   if( !p->sharable || removeFromSharingList(pBt) ){
2769     /* The pBt is no longer on the sharing list, so we can access
2770     ** it without having to hold the mutex.
2771     **
2772     ** Clean out and delete the BtShared object.
2773     */
2774     assert( !pBt->pCursor );
2775     sqlite3PagerClose(pBt->pPager, p->db);
2776     if( pBt->xFreeSchema && pBt->pSchema ){
2777       pBt->xFreeSchema(pBt->pSchema);
2778     }
2779     sqlite3DbFree(0, pBt->pSchema);
2780     freeTempSpace(pBt);
2781     sqlite3_free(pBt);
2782   }
2783 
2784 #ifndef SQLITE_OMIT_SHARED_CACHE
2785   assert( p->wantToLock==0 );
2786   assert( p->locked==0 );
2787   if( p->pPrev ) p->pPrev->pNext = p->pNext;
2788   if( p->pNext ) p->pNext->pPrev = p->pPrev;
2789 #endif
2790 
2791   sqlite3_free(p);
2792   return SQLITE_OK;
2793 }
2794 
2795 /*
2796 ** Change the "soft" limit on the number of pages in the cache.
2797 ** Unused and unmodified pages will be recycled when the number of
2798 ** pages in the cache exceeds this soft limit.  But the size of the
2799 ** cache is allowed to grow larger than this limit if it contains
2800 ** dirty pages or pages still in active use.
2801 */
2802 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2803   BtShared *pBt = p->pBt;
2804   assert( sqlite3_mutex_held(p->db->mutex) );
2805   sqlite3BtreeEnter(p);
2806   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2807   sqlite3BtreeLeave(p);
2808   return SQLITE_OK;
2809 }
2810 
2811 /*
2812 ** Change the "spill" limit on the number of pages in the cache.
2813 ** If the number of pages exceeds this limit during a write transaction,
2814 ** the pager might attempt to "spill" pages to the journal early in
2815 ** order to free up memory.
2816 **
2817 ** The value returned is the current spill size.  If zero is passed
2818 ** as an argument, no changes are made to the spill size setting, so
2819 ** using mxPage of 0 is a way to query the current spill size.
2820 */
2821 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2822   BtShared *pBt = p->pBt;
2823   int res;
2824   assert( sqlite3_mutex_held(p->db->mutex) );
2825   sqlite3BtreeEnter(p);
2826   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2827   sqlite3BtreeLeave(p);
2828   return res;
2829 }
2830 
2831 #if SQLITE_MAX_MMAP_SIZE>0
2832 /*
2833 ** Change the limit on the amount of the database file that may be
2834 ** memory mapped.
2835 */
2836 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2837   BtShared *pBt = p->pBt;
2838   assert( sqlite3_mutex_held(p->db->mutex) );
2839   sqlite3BtreeEnter(p);
2840   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2841   sqlite3BtreeLeave(p);
2842   return SQLITE_OK;
2843 }
2844 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2845 
2846 /*
2847 ** Change the way data is synced to disk in order to increase or decrease
2848 ** how well the database resists damage due to OS crashes and power
2849 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
2850 ** there is a high probability of damage)  Level 2 is the default.  There
2851 ** is a very low but non-zero probability of damage.  Level 3 reduces the
2852 ** probability of damage to near zero but with a write performance reduction.
2853 */
2854 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2855 int sqlite3BtreeSetPagerFlags(
2856   Btree *p,              /* The btree to set the safety level on */
2857   unsigned pgFlags       /* Various PAGER_* flags */
2858 ){
2859   BtShared *pBt = p->pBt;
2860   assert( sqlite3_mutex_held(p->db->mutex) );
2861   sqlite3BtreeEnter(p);
2862   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2863   sqlite3BtreeLeave(p);
2864   return SQLITE_OK;
2865 }
2866 #endif
2867 
2868 /*
2869 ** Change the default pages size and the number of reserved bytes per page.
2870 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2871 ** without changing anything.
2872 **
2873 ** The page size must be a power of 2 between 512 and 65536.  If the page
2874 ** size supplied does not meet this constraint then the page size is not
2875 ** changed.
2876 **
2877 ** Page sizes are constrained to be a power of two so that the region
2878 ** of the database file used for locking (beginning at PENDING_BYTE,
2879 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2880 ** at the beginning of a page.
2881 **
2882 ** If parameter nReserve is less than zero, then the number of reserved
2883 ** bytes per page is left unchanged.
2884 **
2885 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2886 ** and autovacuum mode can no longer be changed.
2887 */
2888 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2889   int rc = SQLITE_OK;
2890   int x;
2891   BtShared *pBt = p->pBt;
2892   assert( nReserve>=0 && nReserve<=255 );
2893   sqlite3BtreeEnter(p);
2894   pBt->nReserveWanted = nReserve;
2895   x = pBt->pageSize - pBt->usableSize;
2896   if( nReserve<x ) nReserve = x;
2897   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2898     sqlite3BtreeLeave(p);
2899     return SQLITE_READONLY;
2900   }
2901   assert( nReserve>=0 && nReserve<=255 );
2902   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2903         ((pageSize-1)&pageSize)==0 ){
2904     assert( (pageSize & 7)==0 );
2905     assert( !pBt->pCursor );
2906     if( nReserve>32 && pageSize==512 ) pageSize = 1024;
2907     pBt->pageSize = (u32)pageSize;
2908     freeTempSpace(pBt);
2909   }
2910   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2911   pBt->usableSize = pBt->pageSize - (u16)nReserve;
2912   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2913   sqlite3BtreeLeave(p);
2914   return rc;
2915 }
2916 
2917 /*
2918 ** Return the currently defined page size
2919 */
2920 int sqlite3BtreeGetPageSize(Btree *p){
2921   return p->pBt->pageSize;
2922 }
2923 
2924 /*
2925 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2926 ** may only be called if it is guaranteed that the b-tree mutex is already
2927 ** held.
2928 **
2929 ** This is useful in one special case in the backup API code where it is
2930 ** known that the shared b-tree mutex is held, but the mutex on the
2931 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2932 ** were to be called, it might collide with some other operation on the
2933 ** database handle that owns *p, causing undefined behavior.
2934 */
2935 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2936   int n;
2937   assert( sqlite3_mutex_held(p->pBt->mutex) );
2938   n = p->pBt->pageSize - p->pBt->usableSize;
2939   return n;
2940 }
2941 
2942 /*
2943 ** Return the number of bytes of space at the end of every page that
2944 ** are intentually left unused.  This is the "reserved" space that is
2945 ** sometimes used by extensions.
2946 **
2947 ** The value returned is the larger of the current reserve size and
2948 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2949 ** The amount of reserve can only grow - never shrink.
2950 */
2951 int sqlite3BtreeGetRequestedReserve(Btree *p){
2952   int n1, n2;
2953   sqlite3BtreeEnter(p);
2954   n1 = (int)p->pBt->nReserveWanted;
2955   n2 = sqlite3BtreeGetReserveNoMutex(p);
2956   sqlite3BtreeLeave(p);
2957   return n1>n2 ? n1 : n2;
2958 }
2959 
2960 
2961 /*
2962 ** Set the maximum page count for a database if mxPage is positive.
2963 ** No changes are made if mxPage is 0 or negative.
2964 ** Regardless of the value of mxPage, return the maximum page count.
2965 */
2966 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2967   Pgno n;
2968   sqlite3BtreeEnter(p);
2969   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2970   sqlite3BtreeLeave(p);
2971   return n;
2972 }
2973 
2974 /*
2975 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2976 **
2977 **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2978 **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2979 **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2980 **    newFlag==(-1)    No changes
2981 **
2982 ** This routine acts as a query if newFlag is less than zero
2983 **
2984 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2985 ** freelist leaf pages are not written back to the database.  Thus in-page
2986 ** deleted content is cleared, but freelist deleted content is not.
2987 **
2988 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2989 ** that freelist leaf pages are written back into the database, increasing
2990 ** the amount of disk I/O.
2991 */
2992 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2993   int b;
2994   if( p==0 ) return 0;
2995   sqlite3BtreeEnter(p);
2996   assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2997   assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
2998   if( newFlag>=0 ){
2999     p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3000     p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3001   }
3002   b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3003   sqlite3BtreeLeave(p);
3004   return b;
3005 }
3006 
3007 /*
3008 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3009 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3010 ** is disabled. The default value for the auto-vacuum property is
3011 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3012 */
3013 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3014 #ifdef SQLITE_OMIT_AUTOVACUUM
3015   return SQLITE_READONLY;
3016 #else
3017   BtShared *pBt = p->pBt;
3018   int rc = SQLITE_OK;
3019   u8 av = (u8)autoVacuum;
3020 
3021   sqlite3BtreeEnter(p);
3022   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3023     rc = SQLITE_READONLY;
3024   }else{
3025     pBt->autoVacuum = av ?1:0;
3026     pBt->incrVacuum = av==2 ?1:0;
3027   }
3028   sqlite3BtreeLeave(p);
3029   return rc;
3030 #endif
3031 }
3032 
3033 /*
3034 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3035 ** enabled 1 is returned. Otherwise 0.
3036 */
3037 int sqlite3BtreeGetAutoVacuum(Btree *p){
3038 #ifdef SQLITE_OMIT_AUTOVACUUM
3039   return BTREE_AUTOVACUUM_NONE;
3040 #else
3041   int rc;
3042   sqlite3BtreeEnter(p);
3043   rc = (
3044     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3045     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3046     BTREE_AUTOVACUUM_INCR
3047   );
3048   sqlite3BtreeLeave(p);
3049   return rc;
3050 #endif
3051 }
3052 
3053 /*
3054 ** If the user has not set the safety-level for this database connection
3055 ** using "PRAGMA synchronous", and if the safety-level is not already
3056 ** set to the value passed to this function as the second parameter,
3057 ** set it so.
3058 */
3059 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3060     && !defined(SQLITE_OMIT_WAL)
3061 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3062   sqlite3 *db;
3063   Db *pDb;
3064   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3065     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3066     if( pDb->bSyncSet==0
3067      && pDb->safety_level!=safety_level
3068      && pDb!=&db->aDb[1]
3069     ){
3070       pDb->safety_level = safety_level;
3071       sqlite3PagerSetFlags(pBt->pPager,
3072           pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3073     }
3074   }
3075 }
3076 #else
3077 # define setDefaultSyncFlag(pBt,safety_level)
3078 #endif
3079 
3080 /* Forward declaration */
3081 static int newDatabase(BtShared*);
3082 
3083 
3084 /*
3085 ** Get a reference to pPage1 of the database file.  This will
3086 ** also acquire a readlock on that file.
3087 **
3088 ** SQLITE_OK is returned on success.  If the file is not a
3089 ** well-formed database file, then SQLITE_CORRUPT is returned.
3090 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
3091 ** is returned if we run out of memory.
3092 */
3093 static int lockBtree(BtShared *pBt){
3094   int rc;              /* Result code from subfunctions */
3095   MemPage *pPage1;     /* Page 1 of the database file */
3096   u32 nPage;           /* Number of pages in the database */
3097   u32 nPageFile = 0;   /* Number of pages in the database file */
3098 
3099   assert( sqlite3_mutex_held(pBt->mutex) );
3100   assert( pBt->pPage1==0 );
3101   rc = sqlite3PagerSharedLock(pBt->pPager);
3102   if( rc!=SQLITE_OK ) return rc;
3103   rc = btreeGetPage(pBt, 1, &pPage1, 0);
3104   if( rc!=SQLITE_OK ) return rc;
3105 
3106   /* Do some checking to help insure the file we opened really is
3107   ** a valid database file.
3108   */
3109   nPage = get4byte(28+(u8*)pPage1->aData);
3110   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3111   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3112     nPage = nPageFile;
3113   }
3114   if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3115     nPage = 0;
3116   }
3117   if( nPage>0 ){
3118     u32 pageSize;
3119     u32 usableSize;
3120     u8 *page1 = pPage1->aData;
3121     rc = SQLITE_NOTADB;
3122     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3123     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3124     ** 61 74 20 33 00. */
3125     if( memcmp(page1, zMagicHeader, 16)!=0 ){
3126       goto page1_init_failed;
3127     }
3128 
3129 #ifdef SQLITE_OMIT_WAL
3130     if( page1[18]>1 ){
3131       pBt->btsFlags |= BTS_READ_ONLY;
3132     }
3133     if( page1[19]>1 ){
3134       goto page1_init_failed;
3135     }
3136 #else
3137     if( page1[18]>2 ){
3138       pBt->btsFlags |= BTS_READ_ONLY;
3139     }
3140     if( page1[19]>2 ){
3141       goto page1_init_failed;
3142     }
3143 
3144     /* If the read version is set to 2, this database should be accessed
3145     ** in WAL mode. If the log is not already open, open it now. Then
3146     ** return SQLITE_OK and return without populating BtShared.pPage1.
3147     ** The caller detects this and calls this function again. This is
3148     ** required as the version of page 1 currently in the page1 buffer
3149     ** may not be the latest version - there may be a newer one in the log
3150     ** file.
3151     */
3152     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3153       int isOpen = 0;
3154       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3155       if( rc!=SQLITE_OK ){
3156         goto page1_init_failed;
3157       }else{
3158         setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3159         if( isOpen==0 ){
3160           releasePageOne(pPage1);
3161           return SQLITE_OK;
3162         }
3163       }
3164       rc = SQLITE_NOTADB;
3165     }else{
3166       setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3167     }
3168 #endif
3169 
3170     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3171     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3172     **
3173     ** The original design allowed these amounts to vary, but as of
3174     ** version 3.6.0, we require them to be fixed.
3175     */
3176     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3177       goto page1_init_failed;
3178     }
3179     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3180     ** determined by the 2-byte integer located at an offset of 16 bytes from
3181     ** the beginning of the database file. */
3182     pageSize = (page1[16]<<8) | (page1[17]<<16);
3183     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3184     ** between 512 and 65536 inclusive. */
3185     if( ((pageSize-1)&pageSize)!=0
3186      || pageSize>SQLITE_MAX_PAGE_SIZE
3187      || pageSize<=256
3188     ){
3189       goto page1_init_failed;
3190     }
3191     pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3192     assert( (pageSize & 7)==0 );
3193     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3194     ** integer at offset 20 is the number of bytes of space at the end of
3195     ** each page to reserve for extensions.
3196     **
3197     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3198     ** determined by the one-byte unsigned integer found at an offset of 20
3199     ** into the database file header. */
3200     usableSize = pageSize - page1[20];
3201     if( (u32)pageSize!=pBt->pageSize ){
3202       /* After reading the first page of the database assuming a page size
3203       ** of BtShared.pageSize, we have discovered that the page-size is
3204       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3205       ** zero and return SQLITE_OK. The caller will call this function
3206       ** again with the correct page-size.
3207       */
3208       releasePageOne(pPage1);
3209       pBt->usableSize = usableSize;
3210       pBt->pageSize = pageSize;
3211       freeTempSpace(pBt);
3212       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3213                                    pageSize-usableSize);
3214       return rc;
3215     }
3216     if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3217       rc = SQLITE_CORRUPT_BKPT;
3218       goto page1_init_failed;
3219     }
3220     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3221     ** be less than 480. In other words, if the page size is 512, then the
3222     ** reserved space size cannot exceed 32. */
3223     if( usableSize<480 ){
3224       goto page1_init_failed;
3225     }
3226     pBt->pageSize = pageSize;
3227     pBt->usableSize = usableSize;
3228 #ifndef SQLITE_OMIT_AUTOVACUUM
3229     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3230     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3231 #endif
3232   }
3233 
3234   /* maxLocal is the maximum amount of payload to store locally for
3235   ** a cell.  Make sure it is small enough so that at least minFanout
3236   ** cells can will fit on one page.  We assume a 10-byte page header.
3237   ** Besides the payload, the cell must store:
3238   **     2-byte pointer to the cell
3239   **     4-byte child pointer
3240   **     9-byte nKey value
3241   **     4-byte nData value
3242   **     4-byte overflow page pointer
3243   ** So a cell consists of a 2-byte pointer, a header which is as much as
3244   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3245   ** page pointer.
3246   */
3247   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3248   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3249   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3250   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3251   if( pBt->maxLocal>127 ){
3252     pBt->max1bytePayload = 127;
3253   }else{
3254     pBt->max1bytePayload = (u8)pBt->maxLocal;
3255   }
3256   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3257   pBt->pPage1 = pPage1;
3258   pBt->nPage = nPage;
3259   return SQLITE_OK;
3260 
3261 page1_init_failed:
3262   releasePageOne(pPage1);
3263   pBt->pPage1 = 0;
3264   return rc;
3265 }
3266 
3267 #ifndef NDEBUG
3268 /*
3269 ** Return the number of cursors open on pBt. This is for use
3270 ** in assert() expressions, so it is only compiled if NDEBUG is not
3271 ** defined.
3272 **
3273 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
3274 ** false then all cursors are counted.
3275 **
3276 ** For the purposes of this routine, a cursor is any cursor that
3277 ** is capable of reading or writing to the database.  Cursors that
3278 ** have been tripped into the CURSOR_FAULT state are not counted.
3279 */
3280 static int countValidCursors(BtShared *pBt, int wrOnly){
3281   BtCursor *pCur;
3282   int r = 0;
3283   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3284     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3285      && pCur->eState!=CURSOR_FAULT ) r++;
3286   }
3287   return r;
3288 }
3289 #endif
3290 
3291 /*
3292 ** If there are no outstanding cursors and we are not in the middle
3293 ** of a transaction but there is a read lock on the database, then
3294 ** this routine unrefs the first page of the database file which
3295 ** has the effect of releasing the read lock.
3296 **
3297 ** If there is a transaction in progress, this routine is a no-op.
3298 */
3299 static void unlockBtreeIfUnused(BtShared *pBt){
3300   assert( sqlite3_mutex_held(pBt->mutex) );
3301   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3302   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3303     MemPage *pPage1 = pBt->pPage1;
3304     assert( pPage1->aData );
3305     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3306     pBt->pPage1 = 0;
3307     releasePageOne(pPage1);
3308   }
3309 }
3310 
3311 /*
3312 ** If pBt points to an empty file then convert that empty file
3313 ** into a new empty database by initializing the first page of
3314 ** the database.
3315 */
3316 static int newDatabase(BtShared *pBt){
3317   MemPage *pP1;
3318   unsigned char *data;
3319   int rc;
3320 
3321   assert( sqlite3_mutex_held(pBt->mutex) );
3322   if( pBt->nPage>0 ){
3323     return SQLITE_OK;
3324   }
3325   pP1 = pBt->pPage1;
3326   assert( pP1!=0 );
3327   data = pP1->aData;
3328   rc = sqlite3PagerWrite(pP1->pDbPage);
3329   if( rc ) return rc;
3330   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3331   assert( sizeof(zMagicHeader)==16 );
3332   data[16] = (u8)((pBt->pageSize>>8)&0xff);
3333   data[17] = (u8)((pBt->pageSize>>16)&0xff);
3334   data[18] = 1;
3335   data[19] = 1;
3336   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3337   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3338   data[21] = 64;
3339   data[22] = 32;
3340   data[23] = 32;
3341   memset(&data[24], 0, 100-24);
3342   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3343   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3344 #ifndef SQLITE_OMIT_AUTOVACUUM
3345   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3346   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3347   put4byte(&data[36 + 4*4], pBt->autoVacuum);
3348   put4byte(&data[36 + 7*4], pBt->incrVacuum);
3349 #endif
3350   pBt->nPage = 1;
3351   data[31] = 1;
3352   return SQLITE_OK;
3353 }
3354 
3355 /*
3356 ** Initialize the first page of the database file (creating a database
3357 ** consisting of a single page and no schema objects). Return SQLITE_OK
3358 ** if successful, or an SQLite error code otherwise.
3359 */
3360 int sqlite3BtreeNewDb(Btree *p){
3361   int rc;
3362   sqlite3BtreeEnter(p);
3363   p->pBt->nPage = 0;
3364   rc = newDatabase(p->pBt);
3365   sqlite3BtreeLeave(p);
3366   return rc;
3367 }
3368 
3369 /*
3370 ** Attempt to start a new transaction. A write-transaction
3371 ** is started if the second argument is nonzero, otherwise a read-
3372 ** transaction.  If the second argument is 2 or more and exclusive
3373 ** transaction is started, meaning that no other process is allowed
3374 ** to access the database.  A preexisting transaction may not be
3375 ** upgraded to exclusive by calling this routine a second time - the
3376 ** exclusivity flag only works for a new transaction.
3377 **
3378 ** A write-transaction must be started before attempting any
3379 ** changes to the database.  None of the following routines
3380 ** will work unless a transaction is started first:
3381 **
3382 **      sqlite3BtreeCreateTable()
3383 **      sqlite3BtreeCreateIndex()
3384 **      sqlite3BtreeClearTable()
3385 **      sqlite3BtreeDropTable()
3386 **      sqlite3BtreeInsert()
3387 **      sqlite3BtreeDelete()
3388 **      sqlite3BtreeUpdateMeta()
3389 **
3390 ** If an initial attempt to acquire the lock fails because of lock contention
3391 ** and the database was previously unlocked, then invoke the busy handler
3392 ** if there is one.  But if there was previously a read-lock, do not
3393 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
3394 ** returned when there is already a read-lock in order to avoid a deadlock.
3395 **
3396 ** Suppose there are two processes A and B.  A has a read lock and B has
3397 ** a reserved lock.  B tries to promote to exclusive but is blocked because
3398 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
3399 ** One or the other of the two processes must give way or there can be
3400 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
3401 ** when A already has a read lock, we encourage A to give up and let B
3402 ** proceed.
3403 */
3404 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3405   BtShared *pBt = p->pBt;
3406   Pager *pPager = pBt->pPager;
3407   int rc = SQLITE_OK;
3408 
3409   sqlite3BtreeEnter(p);
3410   btreeIntegrity(p);
3411 
3412   /* If the btree is already in a write-transaction, or it
3413   ** is already in a read-transaction and a read-transaction
3414   ** is requested, this is a no-op.
3415   */
3416   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3417     goto trans_begun;
3418   }
3419   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3420 
3421   if( (p->db->flags & SQLITE_ResetDatabase)
3422    && sqlite3PagerIsreadonly(pPager)==0
3423   ){
3424     pBt->btsFlags &= ~BTS_READ_ONLY;
3425   }
3426 
3427   /* Write transactions are not possible on a read-only database */
3428   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3429     rc = SQLITE_READONLY;
3430     goto trans_begun;
3431   }
3432 
3433 #ifndef SQLITE_OMIT_SHARED_CACHE
3434   {
3435     sqlite3 *pBlock = 0;
3436     /* If another database handle has already opened a write transaction
3437     ** on this shared-btree structure and a second write transaction is
3438     ** requested, return SQLITE_LOCKED.
3439     */
3440     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3441      || (pBt->btsFlags & BTS_PENDING)!=0
3442     ){
3443       pBlock = pBt->pWriter->db;
3444     }else if( wrflag>1 ){
3445       BtLock *pIter;
3446       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3447         if( pIter->pBtree!=p ){
3448           pBlock = pIter->pBtree->db;
3449           break;
3450         }
3451       }
3452     }
3453     if( pBlock ){
3454       sqlite3ConnectionBlocked(p->db, pBlock);
3455       rc = SQLITE_LOCKED_SHAREDCACHE;
3456       goto trans_begun;
3457     }
3458   }
3459 #endif
3460 
3461   /* Any read-only or read-write transaction implies a read-lock on
3462   ** page 1. So if some other shared-cache client already has a write-lock
3463   ** on page 1, the transaction cannot be opened. */
3464   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3465   if( SQLITE_OK!=rc ) goto trans_begun;
3466 
3467   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3468   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3469   do {
3470     sqlite3PagerWalDb(pPager, p->db);
3471 
3472 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3473     /* If transitioning from no transaction directly to a write transaction,
3474     ** block for the WRITER lock first if possible. */
3475     if( pBt->pPage1==0 && wrflag ){
3476       assert( pBt->inTransaction==TRANS_NONE );
3477       rc = sqlite3PagerWalWriteLock(pPager, 1);
3478       if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3479     }
3480 #endif
3481 
3482     /* Call lockBtree() until either pBt->pPage1 is populated or
3483     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3484     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3485     ** reading page 1 it discovers that the page-size of the database
3486     ** file is not pBt->pageSize. In this case lockBtree() will update
3487     ** pBt->pageSize to the page-size of the file on disk.
3488     */
3489     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3490 
3491     if( rc==SQLITE_OK && wrflag ){
3492       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3493         rc = SQLITE_READONLY;
3494       }else{
3495         rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3496         if( rc==SQLITE_OK ){
3497           rc = newDatabase(pBt);
3498         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3499           /* if there was no transaction opened when this function was
3500           ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3501           ** code to SQLITE_BUSY. */
3502           rc = SQLITE_BUSY;
3503         }
3504       }
3505     }
3506 
3507     if( rc!=SQLITE_OK ){
3508       (void)sqlite3PagerWalWriteLock(pPager, 0);
3509       unlockBtreeIfUnused(pBt);
3510     }
3511   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3512           btreeInvokeBusyHandler(pBt) );
3513   sqlite3PagerWalDb(pPager, 0);
3514 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3515   if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3516 #endif
3517 
3518   if( rc==SQLITE_OK ){
3519     if( p->inTrans==TRANS_NONE ){
3520       pBt->nTransaction++;
3521 #ifndef SQLITE_OMIT_SHARED_CACHE
3522       if( p->sharable ){
3523         assert( p->lock.pBtree==p && p->lock.iTable==1 );
3524         p->lock.eLock = READ_LOCK;
3525         p->lock.pNext = pBt->pLock;
3526         pBt->pLock = &p->lock;
3527       }
3528 #endif
3529     }
3530     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3531     if( p->inTrans>pBt->inTransaction ){
3532       pBt->inTransaction = p->inTrans;
3533     }
3534     if( wrflag ){
3535       MemPage *pPage1 = pBt->pPage1;
3536 #ifndef SQLITE_OMIT_SHARED_CACHE
3537       assert( !pBt->pWriter );
3538       pBt->pWriter = p;
3539       pBt->btsFlags &= ~BTS_EXCLUSIVE;
3540       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3541 #endif
3542 
3543       /* If the db-size header field is incorrect (as it may be if an old
3544       ** client has been writing the database file), update it now. Doing
3545       ** this sooner rather than later means the database size can safely
3546       ** re-read the database size from page 1 if a savepoint or transaction
3547       ** rollback occurs within the transaction.
3548       */
3549       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3550         rc = sqlite3PagerWrite(pPage1->pDbPage);
3551         if( rc==SQLITE_OK ){
3552           put4byte(&pPage1->aData[28], pBt->nPage);
3553         }
3554       }
3555     }
3556   }
3557 
3558 trans_begun:
3559   if( rc==SQLITE_OK ){
3560     if( pSchemaVersion ){
3561       *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3562     }
3563     if( wrflag ){
3564       /* This call makes sure that the pager has the correct number of
3565       ** open savepoints. If the second parameter is greater than 0 and
3566       ** the sub-journal is not already open, then it will be opened here.
3567       */
3568       rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3569     }
3570   }
3571 
3572   btreeIntegrity(p);
3573   sqlite3BtreeLeave(p);
3574   return rc;
3575 }
3576 
3577 #ifndef SQLITE_OMIT_AUTOVACUUM
3578 
3579 /*
3580 ** Set the pointer-map entries for all children of page pPage. Also, if
3581 ** pPage contains cells that point to overflow pages, set the pointer
3582 ** map entries for the overflow pages as well.
3583 */
3584 static int setChildPtrmaps(MemPage *pPage){
3585   int i;                             /* Counter variable */
3586   int nCell;                         /* Number of cells in page pPage */
3587   int rc;                            /* Return code */
3588   BtShared *pBt = pPage->pBt;
3589   Pgno pgno = pPage->pgno;
3590 
3591   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3592   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3593   if( rc!=SQLITE_OK ) return rc;
3594   nCell = pPage->nCell;
3595 
3596   for(i=0; i<nCell; i++){
3597     u8 *pCell = findCell(pPage, i);
3598 
3599     ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3600 
3601     if( !pPage->leaf ){
3602       Pgno childPgno = get4byte(pCell);
3603       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3604     }
3605   }
3606 
3607   if( !pPage->leaf ){
3608     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3609     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3610   }
3611 
3612   return rc;
3613 }
3614 
3615 /*
3616 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
3617 ** that it points to iTo. Parameter eType describes the type of pointer to
3618 ** be modified, as  follows:
3619 **
3620 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
3621 **                   page of pPage.
3622 **
3623 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3624 **                   page pointed to by one of the cells on pPage.
3625 **
3626 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3627 **                   overflow page in the list.
3628 */
3629 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3630   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3631   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3632   if( eType==PTRMAP_OVERFLOW2 ){
3633     /* The pointer is always the first 4 bytes of the page in this case.  */
3634     if( get4byte(pPage->aData)!=iFrom ){
3635       return SQLITE_CORRUPT_PAGE(pPage);
3636     }
3637     put4byte(pPage->aData, iTo);
3638   }else{
3639     int i;
3640     int nCell;
3641     int rc;
3642 
3643     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3644     if( rc ) return rc;
3645     nCell = pPage->nCell;
3646 
3647     for(i=0; i<nCell; i++){
3648       u8 *pCell = findCell(pPage, i);
3649       if( eType==PTRMAP_OVERFLOW1 ){
3650         CellInfo info;
3651         pPage->xParseCell(pPage, pCell, &info);
3652         if( info.nLocal<info.nPayload ){
3653           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3654             return SQLITE_CORRUPT_PAGE(pPage);
3655           }
3656           if( iFrom==get4byte(pCell+info.nSize-4) ){
3657             put4byte(pCell+info.nSize-4, iTo);
3658             break;
3659           }
3660         }
3661       }else{
3662         if( get4byte(pCell)==iFrom ){
3663           put4byte(pCell, iTo);
3664           break;
3665         }
3666       }
3667     }
3668 
3669     if( i==nCell ){
3670       if( eType!=PTRMAP_BTREE ||
3671           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3672         return SQLITE_CORRUPT_PAGE(pPage);
3673       }
3674       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3675     }
3676   }
3677   return SQLITE_OK;
3678 }
3679 
3680 
3681 /*
3682 ** Move the open database page pDbPage to location iFreePage in the
3683 ** database. The pDbPage reference remains valid.
3684 **
3685 ** The isCommit flag indicates that there is no need to remember that
3686 ** the journal needs to be sync()ed before database page pDbPage->pgno
3687 ** can be written to. The caller has already promised not to write to that
3688 ** page.
3689 */
3690 static int relocatePage(
3691   BtShared *pBt,           /* Btree */
3692   MemPage *pDbPage,        /* Open page to move */
3693   u8 eType,                /* Pointer map 'type' entry for pDbPage */
3694   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
3695   Pgno iFreePage,          /* The location to move pDbPage to */
3696   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
3697 ){
3698   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
3699   Pgno iDbPage = pDbPage->pgno;
3700   Pager *pPager = pBt->pPager;
3701   int rc;
3702 
3703   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3704       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3705   assert( sqlite3_mutex_held(pBt->mutex) );
3706   assert( pDbPage->pBt==pBt );
3707   if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3708 
3709   /* Move page iDbPage from its current location to page number iFreePage */
3710   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3711       iDbPage, iFreePage, iPtrPage, eType));
3712   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3713   if( rc!=SQLITE_OK ){
3714     return rc;
3715   }
3716   pDbPage->pgno = iFreePage;
3717 
3718   /* If pDbPage was a btree-page, then it may have child pages and/or cells
3719   ** that point to overflow pages. The pointer map entries for all these
3720   ** pages need to be changed.
3721   **
3722   ** If pDbPage is an overflow page, then the first 4 bytes may store a
3723   ** pointer to a subsequent overflow page. If this is the case, then
3724   ** the pointer map needs to be updated for the subsequent overflow page.
3725   */
3726   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3727     rc = setChildPtrmaps(pDbPage);
3728     if( rc!=SQLITE_OK ){
3729       return rc;
3730     }
3731   }else{
3732     Pgno nextOvfl = get4byte(pDbPage->aData);
3733     if( nextOvfl!=0 ){
3734       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3735       if( rc!=SQLITE_OK ){
3736         return rc;
3737       }
3738     }
3739   }
3740 
3741   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3742   ** that it points at iFreePage. Also fix the pointer map entry for
3743   ** iPtrPage.
3744   */
3745   if( eType!=PTRMAP_ROOTPAGE ){
3746     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3747     if( rc!=SQLITE_OK ){
3748       return rc;
3749     }
3750     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3751     if( rc!=SQLITE_OK ){
3752       releasePage(pPtrPage);
3753       return rc;
3754     }
3755     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3756     releasePage(pPtrPage);
3757     if( rc==SQLITE_OK ){
3758       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3759     }
3760   }
3761   return rc;
3762 }
3763 
3764 /* Forward declaration required by incrVacuumStep(). */
3765 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3766 
3767 /*
3768 ** Perform a single step of an incremental-vacuum. If successful, return
3769 ** SQLITE_OK. If there is no work to do (and therefore no point in
3770 ** calling this function again), return SQLITE_DONE. Or, if an error
3771 ** occurs, return some other error code.
3772 **
3773 ** More specifically, this function attempts to re-organize the database so
3774 ** that the last page of the file currently in use is no longer in use.
3775 **
3776 ** Parameter nFin is the number of pages that this database would contain
3777 ** were this function called until it returns SQLITE_DONE.
3778 **
3779 ** If the bCommit parameter is non-zero, this function assumes that the
3780 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3781 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3782 ** operation, or false for an incremental vacuum.
3783 */
3784 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3785   Pgno nFreeList;           /* Number of pages still on the free-list */
3786   int rc;
3787 
3788   assert( sqlite3_mutex_held(pBt->mutex) );
3789   assert( iLastPg>nFin );
3790 
3791   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3792     u8 eType;
3793     Pgno iPtrPage;
3794 
3795     nFreeList = get4byte(&pBt->pPage1->aData[36]);
3796     if( nFreeList==0 ){
3797       return SQLITE_DONE;
3798     }
3799 
3800     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3801     if( rc!=SQLITE_OK ){
3802       return rc;
3803     }
3804     if( eType==PTRMAP_ROOTPAGE ){
3805       return SQLITE_CORRUPT_BKPT;
3806     }
3807 
3808     if( eType==PTRMAP_FREEPAGE ){
3809       if( bCommit==0 ){
3810         /* Remove the page from the files free-list. This is not required
3811         ** if bCommit is non-zero. In that case, the free-list will be
3812         ** truncated to zero after this function returns, so it doesn't
3813         ** matter if it still contains some garbage entries.
3814         */
3815         Pgno iFreePg;
3816         MemPage *pFreePg;
3817         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3818         if( rc!=SQLITE_OK ){
3819           return rc;
3820         }
3821         assert( iFreePg==iLastPg );
3822         releasePage(pFreePg);
3823       }
3824     } else {
3825       Pgno iFreePg;             /* Index of free page to move pLastPg to */
3826       MemPage *pLastPg;
3827       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
3828       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
3829 
3830       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3831       if( rc!=SQLITE_OK ){
3832         return rc;
3833       }
3834 
3835       /* If bCommit is zero, this loop runs exactly once and page pLastPg
3836       ** is swapped with the first free page pulled off the free list.
3837       **
3838       ** On the other hand, if bCommit is greater than zero, then keep
3839       ** looping until a free-page located within the first nFin pages
3840       ** of the file is found.
3841       */
3842       if( bCommit==0 ){
3843         eMode = BTALLOC_LE;
3844         iNear = nFin;
3845       }
3846       do {
3847         MemPage *pFreePg;
3848         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3849         if( rc!=SQLITE_OK ){
3850           releasePage(pLastPg);
3851           return rc;
3852         }
3853         releasePage(pFreePg);
3854       }while( bCommit && iFreePg>nFin );
3855       assert( iFreePg<iLastPg );
3856 
3857       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3858       releasePage(pLastPg);
3859       if( rc!=SQLITE_OK ){
3860         return rc;
3861       }
3862     }
3863   }
3864 
3865   if( bCommit==0 ){
3866     do {
3867       iLastPg--;
3868     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3869     pBt->bDoTruncate = 1;
3870     pBt->nPage = iLastPg;
3871   }
3872   return SQLITE_OK;
3873 }
3874 
3875 /*
3876 ** The database opened by the first argument is an auto-vacuum database
3877 ** nOrig pages in size containing nFree free pages. Return the expected
3878 ** size of the database in pages following an auto-vacuum operation.
3879 */
3880 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3881   int nEntry;                     /* Number of entries on one ptrmap page */
3882   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
3883   Pgno nFin;                      /* Return value */
3884 
3885   nEntry = pBt->usableSize/5;
3886   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3887   nFin = nOrig - nFree - nPtrmap;
3888   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3889     nFin--;
3890   }
3891   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3892     nFin--;
3893   }
3894 
3895   return nFin;
3896 }
3897 
3898 /*
3899 ** A write-transaction must be opened before calling this function.
3900 ** It performs a single unit of work towards an incremental vacuum.
3901 **
3902 ** If the incremental vacuum is finished after this function has run,
3903 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3904 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3905 */
3906 int sqlite3BtreeIncrVacuum(Btree *p){
3907   int rc;
3908   BtShared *pBt = p->pBt;
3909 
3910   sqlite3BtreeEnter(p);
3911   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3912   if( !pBt->autoVacuum ){
3913     rc = SQLITE_DONE;
3914   }else{
3915     Pgno nOrig = btreePagecount(pBt);
3916     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3917     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3918 
3919     if( nOrig<nFin || nFree>=nOrig ){
3920       rc = SQLITE_CORRUPT_BKPT;
3921     }else if( nFree>0 ){
3922       rc = saveAllCursors(pBt, 0, 0);
3923       if( rc==SQLITE_OK ){
3924         invalidateAllOverflowCache(pBt);
3925         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3926       }
3927       if( rc==SQLITE_OK ){
3928         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3929         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3930       }
3931     }else{
3932       rc = SQLITE_DONE;
3933     }
3934   }
3935   sqlite3BtreeLeave(p);
3936   return rc;
3937 }
3938 
3939 /*
3940 ** This routine is called prior to sqlite3PagerCommit when a transaction
3941 ** is committed for an auto-vacuum database.
3942 */
3943 static int autoVacuumCommit(Btree *p){
3944   int rc = SQLITE_OK;
3945   Pager *pPager;
3946   BtShared *pBt;
3947   sqlite3 *db;
3948   VVA_ONLY( int nRef );
3949 
3950   assert( p!=0 );
3951   pBt = p->pBt;
3952   pPager = pBt->pPager;
3953   VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
3954 
3955   assert( sqlite3_mutex_held(pBt->mutex) );
3956   invalidateAllOverflowCache(pBt);
3957   assert(pBt->autoVacuum);
3958   if( !pBt->incrVacuum ){
3959     Pgno nFin;         /* Number of pages in database after autovacuuming */
3960     Pgno nFree;        /* Number of pages on the freelist initially */
3961     Pgno nVac;         /* Number of pages to vacuum */
3962     Pgno iFree;        /* The next page to be freed */
3963     Pgno nOrig;        /* Database size before freeing */
3964 
3965     nOrig = btreePagecount(pBt);
3966     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3967       /* It is not possible to create a database for which the final page
3968       ** is either a pointer-map page or the pending-byte page. If one
3969       ** is encountered, this indicates corruption.
3970       */
3971       return SQLITE_CORRUPT_BKPT;
3972     }
3973 
3974     nFree = get4byte(&pBt->pPage1->aData[36]);
3975     db = p->db;
3976     if( db->xAutovacPages ){
3977       int iDb;
3978       for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
3979         if( db->aDb[iDb].pBt==p ) break;
3980       }
3981       nVac = db->xAutovacPages(
3982         db->pAutovacPagesArg,
3983         db->aDb[iDb].zDbSName,
3984         nOrig,
3985         nFree,
3986         pBt->pageSize
3987       );
3988       if( nVac>nFree ){
3989         nVac = nFree;
3990       }
3991       if( nVac==0 ){
3992         return SQLITE_OK;
3993       }
3994     }else{
3995       nVac = nFree;
3996     }
3997     nFin = finalDbSize(pBt, nOrig, nVac);
3998     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3999     if( nFin<nOrig ){
4000       rc = saveAllCursors(pBt, 0, 0);
4001     }
4002     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4003       rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4004     }
4005     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4006       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4007       if( nVac==nFree ){
4008         put4byte(&pBt->pPage1->aData[32], 0);
4009         put4byte(&pBt->pPage1->aData[36], 0);
4010       }
4011       put4byte(&pBt->pPage1->aData[28], nFin);
4012       pBt->bDoTruncate = 1;
4013       pBt->nPage = nFin;
4014     }
4015     if( rc!=SQLITE_OK ){
4016       sqlite3PagerRollback(pPager);
4017     }
4018   }
4019 
4020   assert( nRef>=sqlite3PagerRefcount(pPager) );
4021   return rc;
4022 }
4023 
4024 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4025 # define setChildPtrmaps(x) SQLITE_OK
4026 #endif
4027 
4028 /*
4029 ** This routine does the first phase of a two-phase commit.  This routine
4030 ** causes a rollback journal to be created (if it does not already exist)
4031 ** and populated with enough information so that if a power loss occurs
4032 ** the database can be restored to its original state by playing back
4033 ** the journal.  Then the contents of the journal are flushed out to
4034 ** the disk.  After the journal is safely on oxide, the changes to the
4035 ** database are written into the database file and flushed to oxide.
4036 ** At the end of this call, the rollback journal still exists on the
4037 ** disk and we are still holding all locks, so the transaction has not
4038 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4039 ** commit process.
4040 **
4041 ** This call is a no-op if no write-transaction is currently active on pBt.
4042 **
4043 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4044 ** the name of a super-journal file that should be written into the
4045 ** individual journal file, or is NULL, indicating no super-journal file
4046 ** (single database transaction).
4047 **
4048 ** When this is called, the super-journal should already have been
4049 ** created, populated with this journal pointer and synced to disk.
4050 **
4051 ** Once this is routine has returned, the only thing required to commit
4052 ** the write-transaction for this database file is to delete the journal.
4053 */
4054 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4055   int rc = SQLITE_OK;
4056   if( p->inTrans==TRANS_WRITE ){
4057     BtShared *pBt = p->pBt;
4058     sqlite3BtreeEnter(p);
4059 #ifndef SQLITE_OMIT_AUTOVACUUM
4060     if( pBt->autoVacuum ){
4061       rc = autoVacuumCommit(p);
4062       if( rc!=SQLITE_OK ){
4063         sqlite3BtreeLeave(p);
4064         return rc;
4065       }
4066     }
4067     if( pBt->bDoTruncate ){
4068       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4069     }
4070 #endif
4071     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4072     sqlite3BtreeLeave(p);
4073   }
4074   return rc;
4075 }
4076 
4077 /*
4078 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4079 ** at the conclusion of a transaction.
4080 */
4081 static void btreeEndTransaction(Btree *p){
4082   BtShared *pBt = p->pBt;
4083   sqlite3 *db = p->db;
4084   assert( sqlite3BtreeHoldsMutex(p) );
4085 
4086 #ifndef SQLITE_OMIT_AUTOVACUUM
4087   pBt->bDoTruncate = 0;
4088 #endif
4089   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4090     /* If there are other active statements that belong to this database
4091     ** handle, downgrade to a read-only transaction. The other statements
4092     ** may still be reading from the database.  */
4093     downgradeAllSharedCacheTableLocks(p);
4094     p->inTrans = TRANS_READ;
4095   }else{
4096     /* If the handle had any kind of transaction open, decrement the
4097     ** transaction count of the shared btree. If the transaction count
4098     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4099     ** call below will unlock the pager.  */
4100     if( p->inTrans!=TRANS_NONE ){
4101       clearAllSharedCacheTableLocks(p);
4102       pBt->nTransaction--;
4103       if( 0==pBt->nTransaction ){
4104         pBt->inTransaction = TRANS_NONE;
4105       }
4106     }
4107 
4108     /* Set the current transaction state to TRANS_NONE and unlock the
4109     ** pager if this call closed the only read or write transaction.  */
4110     p->inTrans = TRANS_NONE;
4111     unlockBtreeIfUnused(pBt);
4112   }
4113 
4114   btreeIntegrity(p);
4115 }
4116 
4117 /*
4118 ** Commit the transaction currently in progress.
4119 **
4120 ** This routine implements the second phase of a 2-phase commit.  The
4121 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4122 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
4123 ** routine did all the work of writing information out to disk and flushing the
4124 ** contents so that they are written onto the disk platter.  All this
4125 ** routine has to do is delete or truncate or zero the header in the
4126 ** the rollback journal (which causes the transaction to commit) and
4127 ** drop locks.
4128 **
4129 ** Normally, if an error occurs while the pager layer is attempting to
4130 ** finalize the underlying journal file, this function returns an error and
4131 ** the upper layer will attempt a rollback. However, if the second argument
4132 ** is non-zero then this b-tree transaction is part of a multi-file
4133 ** transaction. In this case, the transaction has already been committed
4134 ** (by deleting a super-journal file) and the caller will ignore this
4135 ** functions return code. So, even if an error occurs in the pager layer,
4136 ** reset the b-tree objects internal state to indicate that the write
4137 ** transaction has been closed. This is quite safe, as the pager will have
4138 ** transitioned to the error state.
4139 **
4140 ** This will release the write lock on the database file.  If there
4141 ** are no active cursors, it also releases the read lock.
4142 */
4143 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4144 
4145   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4146   sqlite3BtreeEnter(p);
4147   btreeIntegrity(p);
4148 
4149   /* If the handle has a write-transaction open, commit the shared-btrees
4150   ** transaction and set the shared state to TRANS_READ.
4151   */
4152   if( p->inTrans==TRANS_WRITE ){
4153     int rc;
4154     BtShared *pBt = p->pBt;
4155     assert( pBt->inTransaction==TRANS_WRITE );
4156     assert( pBt->nTransaction>0 );
4157     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4158     if( rc!=SQLITE_OK && bCleanup==0 ){
4159       sqlite3BtreeLeave(p);
4160       return rc;
4161     }
4162     p->iBDataVersion--;  /* Compensate for pPager->iDataVersion++; */
4163     pBt->inTransaction = TRANS_READ;
4164     btreeClearHasContent(pBt);
4165   }
4166 
4167   btreeEndTransaction(p);
4168   sqlite3BtreeLeave(p);
4169   return SQLITE_OK;
4170 }
4171 
4172 /*
4173 ** Do both phases of a commit.
4174 */
4175 int sqlite3BtreeCommit(Btree *p){
4176   int rc;
4177   sqlite3BtreeEnter(p);
4178   rc = sqlite3BtreeCommitPhaseOne(p, 0);
4179   if( rc==SQLITE_OK ){
4180     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4181   }
4182   sqlite3BtreeLeave(p);
4183   return rc;
4184 }
4185 
4186 /*
4187 ** This routine sets the state to CURSOR_FAULT and the error
4188 ** code to errCode for every cursor on any BtShared that pBtree
4189 ** references.  Or if the writeOnly flag is set to 1, then only
4190 ** trip write cursors and leave read cursors unchanged.
4191 **
4192 ** Every cursor is a candidate to be tripped, including cursors
4193 ** that belong to other database connections that happen to be
4194 ** sharing the cache with pBtree.
4195 **
4196 ** This routine gets called when a rollback occurs. If the writeOnly
4197 ** flag is true, then only write-cursors need be tripped - read-only
4198 ** cursors save their current positions so that they may continue
4199 ** following the rollback. Or, if writeOnly is false, all cursors are
4200 ** tripped. In general, writeOnly is false if the transaction being
4201 ** rolled back modified the database schema. In this case b-tree root
4202 ** pages may be moved or deleted from the database altogether, making
4203 ** it unsafe for read cursors to continue.
4204 **
4205 ** If the writeOnly flag is true and an error is encountered while
4206 ** saving the current position of a read-only cursor, all cursors,
4207 ** including all read-cursors are tripped.
4208 **
4209 ** SQLITE_OK is returned if successful, or if an error occurs while
4210 ** saving a cursor position, an SQLite error code.
4211 */
4212 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4213   BtCursor *p;
4214   int rc = SQLITE_OK;
4215 
4216   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4217   if( pBtree ){
4218     sqlite3BtreeEnter(pBtree);
4219     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4220       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4221         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4222           rc = saveCursorPosition(p);
4223           if( rc!=SQLITE_OK ){
4224             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4225             break;
4226           }
4227         }
4228       }else{
4229         sqlite3BtreeClearCursor(p);
4230         p->eState = CURSOR_FAULT;
4231         p->skipNext = errCode;
4232       }
4233       btreeReleaseAllCursorPages(p);
4234     }
4235     sqlite3BtreeLeave(pBtree);
4236   }
4237   return rc;
4238 }
4239 
4240 /*
4241 ** Set the pBt->nPage field correctly, according to the current
4242 ** state of the database.  Assume pBt->pPage1 is valid.
4243 */
4244 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4245   int nPage = get4byte(&pPage1->aData[28]);
4246   testcase( nPage==0 );
4247   if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4248   testcase( pBt->nPage!=nPage );
4249   pBt->nPage = nPage;
4250 }
4251 
4252 /*
4253 ** Rollback the transaction in progress.
4254 **
4255 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4256 ** Only write cursors are tripped if writeOnly is true but all cursors are
4257 ** tripped if writeOnly is false.  Any attempt to use
4258 ** a tripped cursor will result in an error.
4259 **
4260 ** This will release the write lock on the database file.  If there
4261 ** are no active cursors, it also releases the read lock.
4262 */
4263 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4264   int rc;
4265   BtShared *pBt = p->pBt;
4266   MemPage *pPage1;
4267 
4268   assert( writeOnly==1 || writeOnly==0 );
4269   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4270   sqlite3BtreeEnter(p);
4271   if( tripCode==SQLITE_OK ){
4272     rc = tripCode = saveAllCursors(pBt, 0, 0);
4273     if( rc ) writeOnly = 0;
4274   }else{
4275     rc = SQLITE_OK;
4276   }
4277   if( tripCode ){
4278     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4279     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4280     if( rc2!=SQLITE_OK ) rc = rc2;
4281   }
4282   btreeIntegrity(p);
4283 
4284   if( p->inTrans==TRANS_WRITE ){
4285     int rc2;
4286 
4287     assert( TRANS_WRITE==pBt->inTransaction );
4288     rc2 = sqlite3PagerRollback(pBt->pPager);
4289     if( rc2!=SQLITE_OK ){
4290       rc = rc2;
4291     }
4292 
4293     /* The rollback may have destroyed the pPage1->aData value.  So
4294     ** call btreeGetPage() on page 1 again to make
4295     ** sure pPage1->aData is set correctly. */
4296     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4297       btreeSetNPage(pBt, pPage1);
4298       releasePageOne(pPage1);
4299     }
4300     assert( countValidCursors(pBt, 1)==0 );
4301     pBt->inTransaction = TRANS_READ;
4302     btreeClearHasContent(pBt);
4303   }
4304 
4305   btreeEndTransaction(p);
4306   sqlite3BtreeLeave(p);
4307   return rc;
4308 }
4309 
4310 /*
4311 ** Start a statement subtransaction. The subtransaction can be rolled
4312 ** back independently of the main transaction. You must start a transaction
4313 ** before starting a subtransaction. The subtransaction is ended automatically
4314 ** if the main transaction commits or rolls back.
4315 **
4316 ** Statement subtransactions are used around individual SQL statements
4317 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4318 ** error occurs within the statement, the effect of that one statement
4319 ** can be rolled back without having to rollback the entire transaction.
4320 **
4321 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4322 ** value passed as the second parameter is the total number of savepoints,
4323 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4324 ** are no active savepoints and no other statement-transactions open,
4325 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4326 ** using the sqlite3BtreeSavepoint() function.
4327 */
4328 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4329   int rc;
4330   BtShared *pBt = p->pBt;
4331   sqlite3BtreeEnter(p);
4332   assert( p->inTrans==TRANS_WRITE );
4333   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4334   assert( iStatement>0 );
4335   assert( iStatement>p->db->nSavepoint );
4336   assert( pBt->inTransaction==TRANS_WRITE );
4337   /* At the pager level, a statement transaction is a savepoint with
4338   ** an index greater than all savepoints created explicitly using
4339   ** SQL statements. It is illegal to open, release or rollback any
4340   ** such savepoints while the statement transaction savepoint is active.
4341   */
4342   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4343   sqlite3BtreeLeave(p);
4344   return rc;
4345 }
4346 
4347 /*
4348 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4349 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4350 ** savepoint identified by parameter iSavepoint, depending on the value
4351 ** of op.
4352 **
4353 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4354 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4355 ** contents of the entire transaction are rolled back. This is different
4356 ** from a normal transaction rollback, as no locks are released and the
4357 ** transaction remains open.
4358 */
4359 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4360   int rc = SQLITE_OK;
4361   if( p && p->inTrans==TRANS_WRITE ){
4362     BtShared *pBt = p->pBt;
4363     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4364     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4365     sqlite3BtreeEnter(p);
4366     if( op==SAVEPOINT_ROLLBACK ){
4367       rc = saveAllCursors(pBt, 0, 0);
4368     }
4369     if( rc==SQLITE_OK ){
4370       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4371     }
4372     if( rc==SQLITE_OK ){
4373       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4374         pBt->nPage = 0;
4375       }
4376       rc = newDatabase(pBt);
4377       btreeSetNPage(pBt, pBt->pPage1);
4378 
4379       /* pBt->nPage might be zero if the database was corrupt when
4380       ** the transaction was started. Otherwise, it must be at least 1.  */
4381       assert( CORRUPT_DB || pBt->nPage>0 );
4382     }
4383     sqlite3BtreeLeave(p);
4384   }
4385   return rc;
4386 }
4387 
4388 /*
4389 ** Create a new cursor for the BTree whose root is on the page
4390 ** iTable. If a read-only cursor is requested, it is assumed that
4391 ** the caller already has at least a read-only transaction open
4392 ** on the database already. If a write-cursor is requested, then
4393 ** the caller is assumed to have an open write transaction.
4394 **
4395 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4396 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4397 ** can be used for reading or for writing if other conditions for writing
4398 ** are also met.  These are the conditions that must be met in order
4399 ** for writing to be allowed:
4400 **
4401 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4402 **
4403 ** 2:  Other database connections that share the same pager cache
4404 **     but which are not in the READ_UNCOMMITTED state may not have
4405 **     cursors open with wrFlag==0 on the same table.  Otherwise
4406 **     the changes made by this write cursor would be visible to
4407 **     the read cursors in the other database connection.
4408 **
4409 ** 3:  The database must be writable (not on read-only media)
4410 **
4411 ** 4:  There must be an active transaction.
4412 **
4413 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4414 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4415 ** this cursor will only be used to seek to and delete entries of an index
4416 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4417 ** this implementation.  But in a hypothetical alternative storage engine
4418 ** in which index entries are automatically deleted when corresponding table
4419 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4420 ** operations on this cursor can be no-ops and all READ operations can
4421 ** return a null row (2-bytes: 0x01 0x00).
4422 **
4423 ** No checking is done to make sure that page iTable really is the
4424 ** root page of a b-tree.  If it is not, then the cursor acquired
4425 ** will not work correctly.
4426 **
4427 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4428 ** on pCur to initialize the memory space prior to invoking this routine.
4429 */
4430 static int btreeCursor(
4431   Btree *p,                              /* The btree */
4432   Pgno iTable,                           /* Root page of table to open */
4433   int wrFlag,                            /* 1 to write. 0 read-only */
4434   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4435   BtCursor *pCur                         /* Space for new cursor */
4436 ){
4437   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4438   BtCursor *pX;                          /* Looping over other all cursors */
4439 
4440   assert( sqlite3BtreeHoldsMutex(p) );
4441   assert( wrFlag==0
4442        || wrFlag==BTREE_WRCSR
4443        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4444   );
4445 
4446   /* The following assert statements verify that if this is a sharable
4447   ** b-tree database, the connection is holding the required table locks,
4448   ** and that no other connection has any open cursor that conflicts with
4449   ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
4450   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4451           || iTable<1 );
4452   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4453 
4454   /* Assert that the caller has opened the required transaction. */
4455   assert( p->inTrans>TRANS_NONE );
4456   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4457   assert( pBt->pPage1 && pBt->pPage1->aData );
4458   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4459 
4460   if( wrFlag ){
4461     allocateTempSpace(pBt);
4462     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4463   }
4464   if( iTable<=1 ){
4465     if( iTable<1 ){
4466       return SQLITE_CORRUPT_BKPT;
4467     }else if( btreePagecount(pBt)==0 ){
4468       assert( wrFlag==0 );
4469       iTable = 0;
4470     }
4471   }
4472 
4473   /* Now that no other errors can occur, finish filling in the BtCursor
4474   ** variables and link the cursor into the BtShared list.  */
4475   pCur->pgnoRoot = iTable;
4476   pCur->iPage = -1;
4477   pCur->pKeyInfo = pKeyInfo;
4478   pCur->pBtree = p;
4479   pCur->pBt = pBt;
4480   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4481   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4482   /* If there are two or more cursors on the same btree, then all such
4483   ** cursors *must* have the BTCF_Multiple flag set. */
4484   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4485     if( pX->pgnoRoot==iTable ){
4486       pX->curFlags |= BTCF_Multiple;
4487       pCur->curFlags |= BTCF_Multiple;
4488     }
4489   }
4490   pCur->pNext = pBt->pCursor;
4491   pBt->pCursor = pCur;
4492   pCur->eState = CURSOR_INVALID;
4493   return SQLITE_OK;
4494 }
4495 static int btreeCursorWithLock(
4496   Btree *p,                              /* The btree */
4497   Pgno iTable,                           /* Root page of table to open */
4498   int wrFlag,                            /* 1 to write. 0 read-only */
4499   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4500   BtCursor *pCur                         /* Space for new cursor */
4501 ){
4502   int rc;
4503   sqlite3BtreeEnter(p);
4504   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4505   sqlite3BtreeLeave(p);
4506   return rc;
4507 }
4508 int sqlite3BtreeCursor(
4509   Btree *p,                                   /* The btree */
4510   Pgno iTable,                                /* Root page of table to open */
4511   int wrFlag,                                 /* 1 to write. 0 read-only */
4512   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4513   BtCursor *pCur                              /* Write new cursor here */
4514 ){
4515   if( p->sharable ){
4516     return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4517   }else{
4518     return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4519   }
4520 }
4521 
4522 /*
4523 ** Return the size of a BtCursor object in bytes.
4524 **
4525 ** This interfaces is needed so that users of cursors can preallocate
4526 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4527 ** to users so they cannot do the sizeof() themselves - they must call
4528 ** this routine.
4529 */
4530 int sqlite3BtreeCursorSize(void){
4531   return ROUND8(sizeof(BtCursor));
4532 }
4533 
4534 /*
4535 ** Initialize memory that will be converted into a BtCursor object.
4536 **
4537 ** The simple approach here would be to memset() the entire object
4538 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4539 ** do not need to be zeroed and they are large, so we can save a lot
4540 ** of run-time by skipping the initialization of those elements.
4541 */
4542 void sqlite3BtreeCursorZero(BtCursor *p){
4543   memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4544 }
4545 
4546 /*
4547 ** Close a cursor.  The read lock on the database file is released
4548 ** when the last cursor is closed.
4549 */
4550 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4551   Btree *pBtree = pCur->pBtree;
4552   if( pBtree ){
4553     BtShared *pBt = pCur->pBt;
4554     sqlite3BtreeEnter(pBtree);
4555     assert( pBt->pCursor!=0 );
4556     if( pBt->pCursor==pCur ){
4557       pBt->pCursor = pCur->pNext;
4558     }else{
4559       BtCursor *pPrev = pBt->pCursor;
4560       do{
4561         if( pPrev->pNext==pCur ){
4562           pPrev->pNext = pCur->pNext;
4563           break;
4564         }
4565         pPrev = pPrev->pNext;
4566       }while( ALWAYS(pPrev) );
4567     }
4568     btreeReleaseAllCursorPages(pCur);
4569     unlockBtreeIfUnused(pBt);
4570     sqlite3_free(pCur->aOverflow);
4571     sqlite3_free(pCur->pKey);
4572     if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4573       /* Since the BtShared is not sharable, there is no need to
4574       ** worry about the missing sqlite3BtreeLeave() call here.  */
4575       assert( pBtree->sharable==0 );
4576       sqlite3BtreeClose(pBtree);
4577     }else{
4578       sqlite3BtreeLeave(pBtree);
4579     }
4580     pCur->pBtree = 0;
4581   }
4582   return SQLITE_OK;
4583 }
4584 
4585 /*
4586 ** Make sure the BtCursor* given in the argument has a valid
4587 ** BtCursor.info structure.  If it is not already valid, call
4588 ** btreeParseCell() to fill it in.
4589 **
4590 ** BtCursor.info is a cache of the information in the current cell.
4591 ** Using this cache reduces the number of calls to btreeParseCell().
4592 */
4593 #ifndef NDEBUG
4594   static int cellInfoEqual(CellInfo *a, CellInfo *b){
4595     if( a->nKey!=b->nKey ) return 0;
4596     if( a->pPayload!=b->pPayload ) return 0;
4597     if( a->nPayload!=b->nPayload ) return 0;
4598     if( a->nLocal!=b->nLocal ) return 0;
4599     if( a->nSize!=b->nSize ) return 0;
4600     return 1;
4601   }
4602   static void assertCellInfo(BtCursor *pCur){
4603     CellInfo info;
4604     memset(&info, 0, sizeof(info));
4605     btreeParseCell(pCur->pPage, pCur->ix, &info);
4606     assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4607   }
4608 #else
4609   #define assertCellInfo(x)
4610 #endif
4611 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4612   if( pCur->info.nSize==0 ){
4613     pCur->curFlags |= BTCF_ValidNKey;
4614     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4615   }else{
4616     assertCellInfo(pCur);
4617   }
4618 }
4619 
4620 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4621 /*
4622 ** Return true if the given BtCursor is valid.  A valid cursor is one
4623 ** that is currently pointing to a row in a (non-empty) table.
4624 ** This is a verification routine is used only within assert() statements.
4625 */
4626 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4627   return pCur && pCur->eState==CURSOR_VALID;
4628 }
4629 #endif /* NDEBUG */
4630 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4631   assert( pCur!=0 );
4632   return pCur->eState==CURSOR_VALID;
4633 }
4634 
4635 /*
4636 ** Return the value of the integer key or "rowid" for a table btree.
4637 ** This routine is only valid for a cursor that is pointing into a
4638 ** ordinary table btree.  If the cursor points to an index btree or
4639 ** is invalid, the result of this routine is undefined.
4640 */
4641 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4642   assert( cursorHoldsMutex(pCur) );
4643   assert( pCur->eState==CURSOR_VALID );
4644   assert( pCur->curIntKey );
4645   getCellInfo(pCur);
4646   return pCur->info.nKey;
4647 }
4648 
4649 /*
4650 ** Pin or unpin a cursor.
4651 */
4652 void sqlite3BtreeCursorPin(BtCursor *pCur){
4653   assert( (pCur->curFlags & BTCF_Pinned)==0 );
4654   pCur->curFlags |= BTCF_Pinned;
4655 }
4656 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4657   assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4658   pCur->curFlags &= ~BTCF_Pinned;
4659 }
4660 
4661 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4662 /*
4663 ** Return the offset into the database file for the start of the
4664 ** payload to which the cursor is pointing.
4665 */
4666 i64 sqlite3BtreeOffset(BtCursor *pCur){
4667   assert( cursorHoldsMutex(pCur) );
4668   assert( pCur->eState==CURSOR_VALID );
4669   getCellInfo(pCur);
4670   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4671          (i64)(pCur->info.pPayload - pCur->pPage->aData);
4672 }
4673 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4674 
4675 /*
4676 ** Return the number of bytes of payload for the entry that pCur is
4677 ** currently pointing to.  For table btrees, this will be the amount
4678 ** of data.  For index btrees, this will be the size of the key.
4679 **
4680 ** The caller must guarantee that the cursor is pointing to a non-NULL
4681 ** valid entry.  In other words, the calling procedure must guarantee
4682 ** that the cursor has Cursor.eState==CURSOR_VALID.
4683 */
4684 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4685   assert( cursorHoldsMutex(pCur) );
4686   assert( pCur->eState==CURSOR_VALID );
4687   getCellInfo(pCur);
4688   return pCur->info.nPayload;
4689 }
4690 
4691 /*
4692 ** Return an upper bound on the size of any record for the table
4693 ** that the cursor is pointing into.
4694 **
4695 ** This is an optimization.  Everything will still work if this
4696 ** routine always returns 2147483647 (which is the largest record
4697 ** that SQLite can handle) or more.  But returning a smaller value might
4698 ** prevent large memory allocations when trying to interpret a
4699 ** corrupt datrabase.
4700 **
4701 ** The current implementation merely returns the size of the underlying
4702 ** database file.
4703 */
4704 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4705   assert( cursorHoldsMutex(pCur) );
4706   assert( pCur->eState==CURSOR_VALID );
4707   return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4708 }
4709 
4710 /*
4711 ** Given the page number of an overflow page in the database (parameter
4712 ** ovfl), this function finds the page number of the next page in the
4713 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4714 ** pointer-map data instead of reading the content of page ovfl to do so.
4715 **
4716 ** If an error occurs an SQLite error code is returned. Otherwise:
4717 **
4718 ** The page number of the next overflow page in the linked list is
4719 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4720 ** list, *pPgnoNext is set to zero.
4721 **
4722 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4723 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4724 ** reference. It is the responsibility of the caller to call releasePage()
4725 ** on *ppPage to free the reference. In no reference was obtained (because
4726 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4727 ** *ppPage is set to zero.
4728 */
4729 static int getOverflowPage(
4730   BtShared *pBt,               /* The database file */
4731   Pgno ovfl,                   /* Current overflow page number */
4732   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4733   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4734 ){
4735   Pgno next = 0;
4736   MemPage *pPage = 0;
4737   int rc = SQLITE_OK;
4738 
4739   assert( sqlite3_mutex_held(pBt->mutex) );
4740   assert(pPgnoNext);
4741 
4742 #ifndef SQLITE_OMIT_AUTOVACUUM
4743   /* Try to find the next page in the overflow list using the
4744   ** autovacuum pointer-map pages. Guess that the next page in
4745   ** the overflow list is page number (ovfl+1). If that guess turns
4746   ** out to be wrong, fall back to loading the data of page
4747   ** number ovfl to determine the next page number.
4748   */
4749   if( pBt->autoVacuum ){
4750     Pgno pgno;
4751     Pgno iGuess = ovfl+1;
4752     u8 eType;
4753 
4754     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4755       iGuess++;
4756     }
4757 
4758     if( iGuess<=btreePagecount(pBt) ){
4759       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4760       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4761         next = iGuess;
4762         rc = SQLITE_DONE;
4763       }
4764     }
4765   }
4766 #endif
4767 
4768   assert( next==0 || rc==SQLITE_DONE );
4769   if( rc==SQLITE_OK ){
4770     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4771     assert( rc==SQLITE_OK || pPage==0 );
4772     if( rc==SQLITE_OK ){
4773       next = get4byte(pPage->aData);
4774     }
4775   }
4776 
4777   *pPgnoNext = next;
4778   if( ppPage ){
4779     *ppPage = pPage;
4780   }else{
4781     releasePage(pPage);
4782   }
4783   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4784 }
4785 
4786 /*
4787 ** Copy data from a buffer to a page, or from a page to a buffer.
4788 **
4789 ** pPayload is a pointer to data stored on database page pDbPage.
4790 ** If argument eOp is false, then nByte bytes of data are copied
4791 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4792 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4793 ** of data are copied from the buffer pBuf to pPayload.
4794 **
4795 ** SQLITE_OK is returned on success, otherwise an error code.
4796 */
4797 static int copyPayload(
4798   void *pPayload,           /* Pointer to page data */
4799   void *pBuf,               /* Pointer to buffer */
4800   int nByte,                /* Number of bytes to copy */
4801   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4802   DbPage *pDbPage           /* Page containing pPayload */
4803 ){
4804   if( eOp ){
4805     /* Copy data from buffer to page (a write operation) */
4806     int rc = sqlite3PagerWrite(pDbPage);
4807     if( rc!=SQLITE_OK ){
4808       return rc;
4809     }
4810     memcpy(pPayload, pBuf, nByte);
4811   }else{
4812     /* Copy data from page to buffer (a read operation) */
4813     memcpy(pBuf, pPayload, nByte);
4814   }
4815   return SQLITE_OK;
4816 }
4817 
4818 /*
4819 ** This function is used to read or overwrite payload information
4820 ** for the entry that the pCur cursor is pointing to. The eOp
4821 ** argument is interpreted as follows:
4822 **
4823 **   0: The operation is a read. Populate the overflow cache.
4824 **   1: The operation is a write. Populate the overflow cache.
4825 **
4826 ** A total of "amt" bytes are read or written beginning at "offset".
4827 ** Data is read to or from the buffer pBuf.
4828 **
4829 ** The content being read or written might appear on the main page
4830 ** or be scattered out on multiple overflow pages.
4831 **
4832 ** If the current cursor entry uses one or more overflow pages
4833 ** this function may allocate space for and lazily populate
4834 ** the overflow page-list cache array (BtCursor.aOverflow).
4835 ** Subsequent calls use this cache to make seeking to the supplied offset
4836 ** more efficient.
4837 **
4838 ** Once an overflow page-list cache has been allocated, it must be
4839 ** invalidated if some other cursor writes to the same table, or if
4840 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4841 ** mode, the following events may invalidate an overflow page-list cache.
4842 **
4843 **   * An incremental vacuum,
4844 **   * A commit in auto_vacuum="full" mode,
4845 **   * Creating a table (may require moving an overflow page).
4846 */
4847 static int accessPayload(
4848   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4849   u32 offset,          /* Begin reading this far into payload */
4850   u32 amt,             /* Read this many bytes */
4851   unsigned char *pBuf, /* Write the bytes into this buffer */
4852   int eOp              /* zero to read. non-zero to write. */
4853 ){
4854   unsigned char *aPayload;
4855   int rc = SQLITE_OK;
4856   int iIdx = 0;
4857   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
4858   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4859 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4860   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4861 #endif
4862 
4863   assert( pPage );
4864   assert( eOp==0 || eOp==1 );
4865   assert( pCur->eState==CURSOR_VALID );
4866   if( pCur->ix>=pPage->nCell ){
4867     return SQLITE_CORRUPT_PAGE(pPage);
4868   }
4869   assert( cursorHoldsMutex(pCur) );
4870 
4871   getCellInfo(pCur);
4872   aPayload = pCur->info.pPayload;
4873   assert( offset+amt <= pCur->info.nPayload );
4874 
4875   assert( aPayload > pPage->aData );
4876   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4877     /* Trying to read or write past the end of the data is an error.  The
4878     ** conditional above is really:
4879     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4880     ** but is recast into its current form to avoid integer overflow problems
4881     */
4882     return SQLITE_CORRUPT_PAGE(pPage);
4883   }
4884 
4885   /* Check if data must be read/written to/from the btree page itself. */
4886   if( offset<pCur->info.nLocal ){
4887     int a = amt;
4888     if( a+offset>pCur->info.nLocal ){
4889       a = pCur->info.nLocal - offset;
4890     }
4891     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4892     offset = 0;
4893     pBuf += a;
4894     amt -= a;
4895   }else{
4896     offset -= pCur->info.nLocal;
4897   }
4898 
4899 
4900   if( rc==SQLITE_OK && amt>0 ){
4901     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4902     Pgno nextPage;
4903 
4904     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4905 
4906     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4907     **
4908     ** The aOverflow[] array is sized at one entry for each overflow page
4909     ** in the overflow chain. The page number of the first overflow page is
4910     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4911     ** means "not yet known" (the cache is lazily populated).
4912     */
4913     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4914       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4915       if( pCur->aOverflow==0
4916        || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4917       ){
4918         Pgno *aNew = (Pgno*)sqlite3Realloc(
4919             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4920         );
4921         if( aNew==0 ){
4922           return SQLITE_NOMEM_BKPT;
4923         }else{
4924           pCur->aOverflow = aNew;
4925         }
4926       }
4927       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4928       pCur->curFlags |= BTCF_ValidOvfl;
4929     }else{
4930       /* If the overflow page-list cache has been allocated and the
4931       ** entry for the first required overflow page is valid, skip
4932       ** directly to it.
4933       */
4934       if( pCur->aOverflow[offset/ovflSize] ){
4935         iIdx = (offset/ovflSize);
4936         nextPage = pCur->aOverflow[iIdx];
4937         offset = (offset%ovflSize);
4938       }
4939     }
4940 
4941     assert( rc==SQLITE_OK && amt>0 );
4942     while( nextPage ){
4943       /* If required, populate the overflow page-list cache. */
4944       if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4945       assert( pCur->aOverflow[iIdx]==0
4946               || pCur->aOverflow[iIdx]==nextPage
4947               || CORRUPT_DB );
4948       pCur->aOverflow[iIdx] = nextPage;
4949 
4950       if( offset>=ovflSize ){
4951         /* The only reason to read this page is to obtain the page
4952         ** number for the next page in the overflow chain. The page
4953         ** data is not required. So first try to lookup the overflow
4954         ** page-list cache, if any, then fall back to the getOverflowPage()
4955         ** function.
4956         */
4957         assert( pCur->curFlags & BTCF_ValidOvfl );
4958         assert( pCur->pBtree->db==pBt->db );
4959         if( pCur->aOverflow[iIdx+1] ){
4960           nextPage = pCur->aOverflow[iIdx+1];
4961         }else{
4962           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4963         }
4964         offset -= ovflSize;
4965       }else{
4966         /* Need to read this page properly. It contains some of the
4967         ** range of data that is being read (eOp==0) or written (eOp!=0).
4968         */
4969         int a = amt;
4970         if( a + offset > ovflSize ){
4971           a = ovflSize - offset;
4972         }
4973 
4974 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4975         /* If all the following are true:
4976         **
4977         **   1) this is a read operation, and
4978         **   2) data is required from the start of this overflow page, and
4979         **   3) there are no dirty pages in the page-cache
4980         **   4) the database is file-backed, and
4981         **   5) the page is not in the WAL file
4982         **   6) at least 4 bytes have already been read into the output buffer
4983         **
4984         ** then data can be read directly from the database file into the
4985         ** output buffer, bypassing the page-cache altogether. This speeds
4986         ** up loading large records that span many overflow pages.
4987         */
4988         if( eOp==0                                             /* (1) */
4989          && offset==0                                          /* (2) */
4990          && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
4991          && &pBuf[-4]>=pBufStart                               /* (6) */
4992         ){
4993           sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4994           u8 aSave[4];
4995           u8 *aWrite = &pBuf[-4];
4996           assert( aWrite>=pBufStart );                         /* due to (6) */
4997           memcpy(aSave, aWrite, 4);
4998           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4999           if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5000           nextPage = get4byte(aWrite);
5001           memcpy(aWrite, aSave, 4);
5002         }else
5003 #endif
5004 
5005         {
5006           DbPage *pDbPage;
5007           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5008               (eOp==0 ? PAGER_GET_READONLY : 0)
5009           );
5010           if( rc==SQLITE_OK ){
5011             aPayload = sqlite3PagerGetData(pDbPage);
5012             nextPage = get4byte(aPayload);
5013             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5014             sqlite3PagerUnref(pDbPage);
5015             offset = 0;
5016           }
5017         }
5018         amt -= a;
5019         if( amt==0 ) return rc;
5020         pBuf += a;
5021       }
5022       if( rc ) break;
5023       iIdx++;
5024     }
5025   }
5026 
5027   if( rc==SQLITE_OK && amt>0 ){
5028     /* Overflow chain ends prematurely */
5029     return SQLITE_CORRUPT_PAGE(pPage);
5030   }
5031   return rc;
5032 }
5033 
5034 /*
5035 ** Read part of the payload for the row at which that cursor pCur is currently
5036 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
5037 ** begins at "offset".
5038 **
5039 ** pCur can be pointing to either a table or an index b-tree.
5040 ** If pointing to a table btree, then the content section is read.  If
5041 ** pCur is pointing to an index b-tree then the key section is read.
5042 **
5043 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5044 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
5045 ** cursor might be invalid or might need to be restored before being read.
5046 **
5047 ** Return SQLITE_OK on success or an error code if anything goes
5048 ** wrong.  An error is returned if "offset+amt" is larger than
5049 ** the available payload.
5050 */
5051 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5052   assert( cursorHoldsMutex(pCur) );
5053   assert( pCur->eState==CURSOR_VALID );
5054   assert( pCur->iPage>=0 && pCur->pPage );
5055   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5056 }
5057 
5058 /*
5059 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5060 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
5061 ** interface.
5062 */
5063 #ifndef SQLITE_OMIT_INCRBLOB
5064 static SQLITE_NOINLINE int accessPayloadChecked(
5065   BtCursor *pCur,
5066   u32 offset,
5067   u32 amt,
5068   void *pBuf
5069 ){
5070   int rc;
5071   if ( pCur->eState==CURSOR_INVALID ){
5072     return SQLITE_ABORT;
5073   }
5074   assert( cursorOwnsBtShared(pCur) );
5075   rc = btreeRestoreCursorPosition(pCur);
5076   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5077 }
5078 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5079   if( pCur->eState==CURSOR_VALID ){
5080     assert( cursorOwnsBtShared(pCur) );
5081     return accessPayload(pCur, offset, amt, pBuf, 0);
5082   }else{
5083     return accessPayloadChecked(pCur, offset, amt, pBuf);
5084   }
5085 }
5086 #endif /* SQLITE_OMIT_INCRBLOB */
5087 
5088 /*
5089 ** Return a pointer to payload information from the entry that the
5090 ** pCur cursor is pointing to.  The pointer is to the beginning of
5091 ** the key if index btrees (pPage->intKey==0) and is the data for
5092 ** table btrees (pPage->intKey==1). The number of bytes of available
5093 ** key/data is written into *pAmt.  If *pAmt==0, then the value
5094 ** returned will not be a valid pointer.
5095 **
5096 ** This routine is an optimization.  It is common for the entire key
5097 ** and data to fit on the local page and for there to be no overflow
5098 ** pages.  When that is so, this routine can be used to access the
5099 ** key and data without making a copy.  If the key and/or data spills
5100 ** onto overflow pages, then accessPayload() must be used to reassemble
5101 ** the key/data and copy it into a preallocated buffer.
5102 **
5103 ** The pointer returned by this routine looks directly into the cached
5104 ** page of the database.  The data might change or move the next time
5105 ** any btree routine is called.
5106 */
5107 static const void *fetchPayload(
5108   BtCursor *pCur,      /* Cursor pointing to entry to read from */
5109   u32 *pAmt            /* Write the number of available bytes here */
5110 ){
5111   int amt;
5112   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5113   assert( pCur->eState==CURSOR_VALID );
5114   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5115   assert( cursorOwnsBtShared(pCur) );
5116   assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5117   assert( pCur->info.nSize>0 );
5118   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5119   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5120   amt = pCur->info.nLocal;
5121   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5122     /* There is too little space on the page for the expected amount
5123     ** of local content. Database must be corrupt. */
5124     assert( CORRUPT_DB );
5125     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5126   }
5127   *pAmt = (u32)amt;
5128   return (void*)pCur->info.pPayload;
5129 }
5130 
5131 
5132 /*
5133 ** For the entry that cursor pCur is point to, return as
5134 ** many bytes of the key or data as are available on the local
5135 ** b-tree page.  Write the number of available bytes into *pAmt.
5136 **
5137 ** The pointer returned is ephemeral.  The key/data may move
5138 ** or be destroyed on the next call to any Btree routine,
5139 ** including calls from other threads against the same cache.
5140 ** Hence, a mutex on the BtShared should be held prior to calling
5141 ** this routine.
5142 **
5143 ** These routines is used to get quick access to key and data
5144 ** in the common case where no overflow pages are used.
5145 */
5146 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5147   return fetchPayload(pCur, pAmt);
5148 }
5149 
5150 
5151 /*
5152 ** Move the cursor down to a new child page.  The newPgno argument is the
5153 ** page number of the child page to move to.
5154 **
5155 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5156 ** the new child page does not match the flags field of the parent (i.e.
5157 ** if an intkey page appears to be the parent of a non-intkey page, or
5158 ** vice-versa).
5159 */
5160 static int moveToChild(BtCursor *pCur, u32 newPgno){
5161   BtShared *pBt = pCur->pBt;
5162 
5163   assert( cursorOwnsBtShared(pCur) );
5164   assert( pCur->eState==CURSOR_VALID );
5165   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5166   assert( pCur->iPage>=0 );
5167   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5168     return SQLITE_CORRUPT_BKPT;
5169   }
5170   pCur->info.nSize = 0;
5171   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5172   pCur->aiIdx[pCur->iPage] = pCur->ix;
5173   pCur->apPage[pCur->iPage] = pCur->pPage;
5174   pCur->ix = 0;
5175   pCur->iPage++;
5176   return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5177 }
5178 
5179 #ifdef SQLITE_DEBUG
5180 /*
5181 ** Page pParent is an internal (non-leaf) tree page. This function
5182 ** asserts that page number iChild is the left-child if the iIdx'th
5183 ** cell in page pParent. Or, if iIdx is equal to the total number of
5184 ** cells in pParent, that page number iChild is the right-child of
5185 ** the page.
5186 */
5187 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5188   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
5189                             ** in a corrupt database */
5190   assert( iIdx<=pParent->nCell );
5191   if( iIdx==pParent->nCell ){
5192     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5193   }else{
5194     assert( get4byte(findCell(pParent, iIdx))==iChild );
5195   }
5196 }
5197 #else
5198 #  define assertParentIndex(x,y,z)
5199 #endif
5200 
5201 /*
5202 ** Move the cursor up to the parent page.
5203 **
5204 ** pCur->idx is set to the cell index that contains the pointer
5205 ** to the page we are coming from.  If we are coming from the
5206 ** right-most child page then pCur->idx is set to one more than
5207 ** the largest cell index.
5208 */
5209 static void moveToParent(BtCursor *pCur){
5210   MemPage *pLeaf;
5211   assert( cursorOwnsBtShared(pCur) );
5212   assert( pCur->eState==CURSOR_VALID );
5213   assert( pCur->iPage>0 );
5214   assert( pCur->pPage );
5215   assertParentIndex(
5216     pCur->apPage[pCur->iPage-1],
5217     pCur->aiIdx[pCur->iPage-1],
5218     pCur->pPage->pgno
5219   );
5220   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5221   pCur->info.nSize = 0;
5222   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5223   pCur->ix = pCur->aiIdx[pCur->iPage-1];
5224   pLeaf = pCur->pPage;
5225   pCur->pPage = pCur->apPage[--pCur->iPage];
5226   releasePageNotNull(pLeaf);
5227 }
5228 
5229 /*
5230 ** Move the cursor to point to the root page of its b-tree structure.
5231 **
5232 ** If the table has a virtual root page, then the cursor is moved to point
5233 ** to the virtual root page instead of the actual root page. A table has a
5234 ** virtual root page when the actual root page contains no cells and a
5235 ** single child page. This can only happen with the table rooted at page 1.
5236 **
5237 ** If the b-tree structure is empty, the cursor state is set to
5238 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5239 ** the cursor is set to point to the first cell located on the root
5240 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5241 **
5242 ** If this function returns successfully, it may be assumed that the
5243 ** page-header flags indicate that the [virtual] root-page is the expected
5244 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5245 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5246 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5247 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5248 ** b-tree).
5249 */
5250 static int moveToRoot(BtCursor *pCur){
5251   MemPage *pRoot;
5252   int rc = SQLITE_OK;
5253 
5254   assert( cursorOwnsBtShared(pCur) );
5255   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5256   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
5257   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
5258   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5259   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5260 
5261   if( pCur->iPage>=0 ){
5262     if( pCur->iPage ){
5263       releasePageNotNull(pCur->pPage);
5264       while( --pCur->iPage ){
5265         releasePageNotNull(pCur->apPage[pCur->iPage]);
5266       }
5267       pCur->pPage = pCur->apPage[0];
5268       goto skip_init;
5269     }
5270   }else if( pCur->pgnoRoot==0 ){
5271     pCur->eState = CURSOR_INVALID;
5272     return SQLITE_EMPTY;
5273   }else{
5274     assert( pCur->iPage==(-1) );
5275     if( pCur->eState>=CURSOR_REQUIRESEEK ){
5276       if( pCur->eState==CURSOR_FAULT ){
5277         assert( pCur->skipNext!=SQLITE_OK );
5278         return pCur->skipNext;
5279       }
5280       sqlite3BtreeClearCursor(pCur);
5281     }
5282     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5283                         0, pCur->curPagerFlags);
5284     if( rc!=SQLITE_OK ){
5285       pCur->eState = CURSOR_INVALID;
5286       return rc;
5287     }
5288     pCur->iPage = 0;
5289     pCur->curIntKey = pCur->pPage->intKey;
5290   }
5291   pRoot = pCur->pPage;
5292   assert( pRoot->pgno==pCur->pgnoRoot );
5293 
5294   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5295   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5296   ** NULL, the caller expects a table b-tree. If this is not the case,
5297   ** return an SQLITE_CORRUPT error.
5298   **
5299   ** Earlier versions of SQLite assumed that this test could not fail
5300   ** if the root page was already loaded when this function was called (i.e.
5301   ** if pCur->iPage>=0). But this is not so if the database is corrupted
5302   ** in such a way that page pRoot is linked into a second b-tree table
5303   ** (or the freelist).  */
5304   assert( pRoot->intKey==1 || pRoot->intKey==0 );
5305   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5306     return SQLITE_CORRUPT_PAGE(pCur->pPage);
5307   }
5308 
5309 skip_init:
5310   pCur->ix = 0;
5311   pCur->info.nSize = 0;
5312   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5313 
5314   pRoot = pCur->pPage;
5315   if( pRoot->nCell>0 ){
5316     pCur->eState = CURSOR_VALID;
5317   }else if( !pRoot->leaf ){
5318     Pgno subpage;
5319     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5320     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5321     pCur->eState = CURSOR_VALID;
5322     rc = moveToChild(pCur, subpage);
5323   }else{
5324     pCur->eState = CURSOR_INVALID;
5325     rc = SQLITE_EMPTY;
5326   }
5327   return rc;
5328 }
5329 
5330 /*
5331 ** Move the cursor down to the left-most leaf entry beneath the
5332 ** entry to which it is currently pointing.
5333 **
5334 ** The left-most leaf is the one with the smallest key - the first
5335 ** in ascending order.
5336 */
5337 static int moveToLeftmost(BtCursor *pCur){
5338   Pgno pgno;
5339   int rc = SQLITE_OK;
5340   MemPage *pPage;
5341 
5342   assert( cursorOwnsBtShared(pCur) );
5343   assert( pCur->eState==CURSOR_VALID );
5344   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5345     assert( pCur->ix<pPage->nCell );
5346     pgno = get4byte(findCell(pPage, pCur->ix));
5347     rc = moveToChild(pCur, pgno);
5348   }
5349   return rc;
5350 }
5351 
5352 /*
5353 ** Move the cursor down to the right-most leaf entry beneath the
5354 ** page to which it is currently pointing.  Notice the difference
5355 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5356 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5357 ** finds the right-most entry beneath the *page*.
5358 **
5359 ** The right-most entry is the one with the largest key - the last
5360 ** key in ascending order.
5361 */
5362 static int moveToRightmost(BtCursor *pCur){
5363   Pgno pgno;
5364   int rc = SQLITE_OK;
5365   MemPage *pPage = 0;
5366 
5367   assert( cursorOwnsBtShared(pCur) );
5368   assert( pCur->eState==CURSOR_VALID );
5369   while( !(pPage = pCur->pPage)->leaf ){
5370     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5371     pCur->ix = pPage->nCell;
5372     rc = moveToChild(pCur, pgno);
5373     if( rc ) return rc;
5374   }
5375   pCur->ix = pPage->nCell-1;
5376   assert( pCur->info.nSize==0 );
5377   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5378   return SQLITE_OK;
5379 }
5380 
5381 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5382 ** on success.  Set *pRes to 0 if the cursor actually points to something
5383 ** or set *pRes to 1 if the table is empty.
5384 */
5385 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5386   int rc;
5387 
5388   assert( cursorOwnsBtShared(pCur) );
5389   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5390   rc = moveToRoot(pCur);
5391   if( rc==SQLITE_OK ){
5392     assert( pCur->pPage->nCell>0 );
5393     *pRes = 0;
5394     rc = moveToLeftmost(pCur);
5395   }else if( rc==SQLITE_EMPTY ){
5396     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5397     *pRes = 1;
5398     rc = SQLITE_OK;
5399   }
5400   return rc;
5401 }
5402 
5403 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5404 ** on success.  Set *pRes to 0 if the cursor actually points to something
5405 ** or set *pRes to 1 if the table is empty.
5406 */
5407 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5408   int rc;
5409 
5410   assert( cursorOwnsBtShared(pCur) );
5411   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5412 
5413   /* If the cursor already points to the last entry, this is a no-op. */
5414   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5415 #ifdef SQLITE_DEBUG
5416     /* This block serves to assert() that the cursor really does point
5417     ** to the last entry in the b-tree. */
5418     int ii;
5419     for(ii=0; ii<pCur->iPage; ii++){
5420       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5421     }
5422     assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5423     testcase( pCur->ix!=pCur->pPage->nCell-1 );
5424     /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5425     assert( pCur->pPage->leaf );
5426 #endif
5427     *pRes = 0;
5428     return SQLITE_OK;
5429   }
5430 
5431   rc = moveToRoot(pCur);
5432   if( rc==SQLITE_OK ){
5433     assert( pCur->eState==CURSOR_VALID );
5434     *pRes = 0;
5435     rc = moveToRightmost(pCur);
5436     if( rc==SQLITE_OK ){
5437       pCur->curFlags |= BTCF_AtLast;
5438     }else{
5439       pCur->curFlags &= ~BTCF_AtLast;
5440     }
5441   }else if( rc==SQLITE_EMPTY ){
5442     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5443     *pRes = 1;
5444     rc = SQLITE_OK;
5445   }
5446   return rc;
5447 }
5448 
5449 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5450 ** table near the key intKey.   Return a success code.
5451 **
5452 ** If an exact match is not found, then the cursor is always
5453 ** left pointing at a leaf page which would hold the entry if it
5454 ** were present.  The cursor might point to an entry that comes
5455 ** before or after the key.
5456 **
5457 ** An integer is written into *pRes which is the result of
5458 ** comparing the key with the entry to which the cursor is
5459 ** pointing.  The meaning of the integer written into
5460 ** *pRes is as follows:
5461 **
5462 **     *pRes<0      The cursor is left pointing at an entry that
5463 **                  is smaller than intKey or if the table is empty
5464 **                  and the cursor is therefore left point to nothing.
5465 **
5466 **     *pRes==0     The cursor is left pointing at an entry that
5467 **                  exactly matches intKey.
5468 **
5469 **     *pRes>0      The cursor is left pointing at an entry that
5470 **                  is larger than intKey.
5471 */
5472 int sqlite3BtreeTableMoveto(
5473   BtCursor *pCur,          /* The cursor to be moved */
5474   i64 intKey,              /* The table key */
5475   int biasRight,           /* If true, bias the search to the high end */
5476   int *pRes                /* Write search results here */
5477 ){
5478   int rc;
5479 
5480   assert( cursorOwnsBtShared(pCur) );
5481   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5482   assert( pRes );
5483   assert( pCur->pKeyInfo==0 );
5484   assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5485 
5486   /* If the cursor is already positioned at the point we are trying
5487   ** to move to, then just return without doing any work */
5488   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5489     if( pCur->info.nKey==intKey ){
5490       *pRes = 0;
5491       return SQLITE_OK;
5492     }
5493     if( pCur->info.nKey<intKey ){
5494       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5495         *pRes = -1;
5496         return SQLITE_OK;
5497       }
5498       /* If the requested key is one more than the previous key, then
5499       ** try to get there using sqlite3BtreeNext() rather than a full
5500       ** binary search.  This is an optimization only.  The correct answer
5501       ** is still obtained without this case, only a little more slowely */
5502       if( pCur->info.nKey+1==intKey ){
5503         *pRes = 0;
5504         rc = sqlite3BtreeNext(pCur, 0);
5505         if( rc==SQLITE_OK ){
5506           getCellInfo(pCur);
5507           if( pCur->info.nKey==intKey ){
5508             return SQLITE_OK;
5509           }
5510         }else if( rc!=SQLITE_DONE ){
5511           return rc;
5512         }
5513       }
5514     }
5515   }
5516 
5517 #ifdef SQLITE_DEBUG
5518   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5519 #endif
5520 
5521   rc = moveToRoot(pCur);
5522   if( rc ){
5523     if( rc==SQLITE_EMPTY ){
5524       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5525       *pRes = -1;
5526       return SQLITE_OK;
5527     }
5528     return rc;
5529   }
5530   assert( pCur->pPage );
5531   assert( pCur->pPage->isInit );
5532   assert( pCur->eState==CURSOR_VALID );
5533   assert( pCur->pPage->nCell > 0 );
5534   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5535   assert( pCur->curIntKey );
5536 
5537   for(;;){
5538     int lwr, upr, idx, c;
5539     Pgno chldPg;
5540     MemPage *pPage = pCur->pPage;
5541     u8 *pCell;                          /* Pointer to current cell in pPage */
5542 
5543     /* pPage->nCell must be greater than zero. If this is the root-page
5544     ** the cursor would have been INVALID above and this for(;;) loop
5545     ** not run. If this is not the root-page, then the moveToChild() routine
5546     ** would have already detected db corruption. Similarly, pPage must
5547     ** be the right kind (index or table) of b-tree page. Otherwise
5548     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5549     assert( pPage->nCell>0 );
5550     assert( pPage->intKey );
5551     lwr = 0;
5552     upr = pPage->nCell-1;
5553     assert( biasRight==0 || biasRight==1 );
5554     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5555     pCur->ix = (u16)idx;
5556     for(;;){
5557       i64 nCellKey;
5558       pCell = findCellPastPtr(pPage, idx);
5559       if( pPage->intKeyLeaf ){
5560         while( 0x80 <= *(pCell++) ){
5561           if( pCell>=pPage->aDataEnd ){
5562             return SQLITE_CORRUPT_PAGE(pPage);
5563           }
5564         }
5565       }
5566       getVarint(pCell, (u64*)&nCellKey);
5567       if( nCellKey<intKey ){
5568         lwr = idx+1;
5569         if( lwr>upr ){ c = -1; break; }
5570       }else if( nCellKey>intKey ){
5571         upr = idx-1;
5572         if( lwr>upr ){ c = +1; break; }
5573       }else{
5574         assert( nCellKey==intKey );
5575         pCur->ix = (u16)idx;
5576         if( !pPage->leaf ){
5577           lwr = idx;
5578           goto moveto_table_next_layer;
5579         }else{
5580           pCur->curFlags |= BTCF_ValidNKey;
5581           pCur->info.nKey = nCellKey;
5582           pCur->info.nSize = 0;
5583           *pRes = 0;
5584           return SQLITE_OK;
5585         }
5586       }
5587       assert( lwr+upr>=0 );
5588       idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5589     }
5590     assert( lwr==upr+1 || !pPage->leaf );
5591     assert( pPage->isInit );
5592     if( pPage->leaf ){
5593       assert( pCur->ix<pCur->pPage->nCell );
5594       pCur->ix = (u16)idx;
5595       *pRes = c;
5596       rc = SQLITE_OK;
5597       goto moveto_table_finish;
5598     }
5599 moveto_table_next_layer:
5600     if( lwr>=pPage->nCell ){
5601       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5602     }else{
5603       chldPg = get4byte(findCell(pPage, lwr));
5604     }
5605     pCur->ix = (u16)lwr;
5606     rc = moveToChild(pCur, chldPg);
5607     if( rc ) break;
5608   }
5609 moveto_table_finish:
5610   pCur->info.nSize = 0;
5611   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5612   return rc;
5613 }
5614 
5615 /* Move the cursor so that it points to an entry in an index table
5616 ** near the key pIdxKey.   Return a success code.
5617 **
5618 ** If an exact match is not found, then the cursor is always
5619 ** left pointing at a leaf page which would hold the entry if it
5620 ** were present.  The cursor might point to an entry that comes
5621 ** before or after the key.
5622 **
5623 ** An integer is written into *pRes which is the result of
5624 ** comparing the key with the entry to which the cursor is
5625 ** pointing.  The meaning of the integer written into
5626 ** *pRes is as follows:
5627 **
5628 **     *pRes<0      The cursor is left pointing at an entry that
5629 **                  is smaller than pIdxKey or if the table is empty
5630 **                  and the cursor is therefore left point to nothing.
5631 **
5632 **     *pRes==0     The cursor is left pointing at an entry that
5633 **                  exactly matches pIdxKey.
5634 **
5635 **     *pRes>0      The cursor is left pointing at an entry that
5636 **                  is larger than pIdxKey.
5637 **
5638 ** The pIdxKey->eqSeen field is set to 1 if there
5639 ** exists an entry in the table that exactly matches pIdxKey.
5640 */
5641 int sqlite3BtreeIndexMoveto(
5642   BtCursor *pCur,          /* The cursor to be moved */
5643   UnpackedRecord *pIdxKey, /* Unpacked index key */
5644   int *pRes                /* Write search results here */
5645 ){
5646   int rc;
5647   RecordCompare xRecordCompare;
5648 
5649   assert( cursorOwnsBtShared(pCur) );
5650   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5651   assert( pRes );
5652   assert( pCur->pKeyInfo!=0 );
5653 
5654 #ifdef SQLITE_DEBUG
5655   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5656 #endif
5657 
5658   xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5659   pIdxKey->errCode = 0;
5660   assert( pIdxKey->default_rc==1
5661        || pIdxKey->default_rc==0
5662        || pIdxKey->default_rc==-1
5663   );
5664 
5665   rc = moveToRoot(pCur);
5666   if( rc ){
5667     if( rc==SQLITE_EMPTY ){
5668       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5669       *pRes = -1;
5670       return SQLITE_OK;
5671     }
5672     return rc;
5673   }
5674   assert( pCur->pPage );
5675   assert( pCur->pPage->isInit );
5676   assert( pCur->eState==CURSOR_VALID );
5677   assert( pCur->pPage->nCell > 0 );
5678   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5679   assert( pCur->curIntKey || pIdxKey );
5680   for(;;){
5681     int lwr, upr, idx, c;
5682     Pgno chldPg;
5683     MemPage *pPage = pCur->pPage;
5684     u8 *pCell;                          /* Pointer to current cell in pPage */
5685 
5686     /* pPage->nCell must be greater than zero. If this is the root-page
5687     ** the cursor would have been INVALID above and this for(;;) loop
5688     ** not run. If this is not the root-page, then the moveToChild() routine
5689     ** would have already detected db corruption. Similarly, pPage must
5690     ** be the right kind (index or table) of b-tree page. Otherwise
5691     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5692     assert( pPage->nCell>0 );
5693     assert( pPage->intKey==(pIdxKey==0) );
5694     lwr = 0;
5695     upr = pPage->nCell-1;
5696     idx = upr>>1; /* idx = (lwr+upr)/2; */
5697     pCur->ix = (u16)idx;
5698     for(;;){
5699       int nCell;  /* Size of the pCell cell in bytes */
5700       pCell = findCellPastPtr(pPage, idx);
5701 
5702       /* The maximum supported page-size is 65536 bytes. This means that
5703       ** the maximum number of record bytes stored on an index B-Tree
5704       ** page is less than 16384 bytes and may be stored as a 2-byte
5705       ** varint. This information is used to attempt to avoid parsing
5706       ** the entire cell by checking for the cases where the record is
5707       ** stored entirely within the b-tree page by inspecting the first
5708       ** 2 bytes of the cell.
5709       */
5710       nCell = pCell[0];
5711       if( nCell<=pPage->max1bytePayload ){
5712         /* This branch runs if the record-size field of the cell is a
5713         ** single byte varint and the record fits entirely on the main
5714         ** b-tree page.  */
5715         testcase( pCell+nCell+1==pPage->aDataEnd );
5716         c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5717       }else if( !(pCell[1] & 0x80)
5718         && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5719       ){
5720         /* The record-size field is a 2 byte varint and the record
5721         ** fits entirely on the main b-tree page.  */
5722         testcase( pCell+nCell+2==pPage->aDataEnd );
5723         c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5724       }else{
5725         /* The record flows over onto one or more overflow pages. In
5726         ** this case the whole cell needs to be parsed, a buffer allocated
5727         ** and accessPayload() used to retrieve the record into the
5728         ** buffer before VdbeRecordCompare() can be called.
5729         **
5730         ** If the record is corrupt, the xRecordCompare routine may read
5731         ** up to two varints past the end of the buffer. An extra 18
5732         ** bytes of padding is allocated at the end of the buffer in
5733         ** case this happens.  */
5734         void *pCellKey;
5735         u8 * const pCellBody = pCell - pPage->childPtrSize;
5736         const int nOverrun = 18;  /* Size of the overrun padding */
5737         pPage->xParseCell(pPage, pCellBody, &pCur->info);
5738         nCell = (int)pCur->info.nKey;
5739         testcase( nCell<0 );   /* True if key size is 2^32 or more */
5740         testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5741         testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5742         testcase( nCell==2 );  /* Minimum legal index key size */
5743         if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5744           rc = SQLITE_CORRUPT_PAGE(pPage);
5745           goto moveto_index_finish;
5746         }
5747         pCellKey = sqlite3Malloc( nCell+nOverrun );
5748         if( pCellKey==0 ){
5749           rc = SQLITE_NOMEM_BKPT;
5750           goto moveto_index_finish;
5751         }
5752         pCur->ix = (u16)idx;
5753         rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5754         memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5755         pCur->curFlags &= ~BTCF_ValidOvfl;
5756         if( rc ){
5757           sqlite3_free(pCellKey);
5758           goto moveto_index_finish;
5759         }
5760         c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5761         sqlite3_free(pCellKey);
5762       }
5763       assert(
5764           (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5765        && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5766       );
5767       if( c<0 ){
5768         lwr = idx+1;
5769       }else if( c>0 ){
5770         upr = idx-1;
5771       }else{
5772         assert( c==0 );
5773         *pRes = 0;
5774         rc = SQLITE_OK;
5775         pCur->ix = (u16)idx;
5776         if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5777         goto moveto_index_finish;
5778       }
5779       if( lwr>upr ) break;
5780       assert( lwr+upr>=0 );
5781       idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5782     }
5783     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5784     assert( pPage->isInit );
5785     if( pPage->leaf ){
5786       assert( pCur->ix<pCur->pPage->nCell );
5787       pCur->ix = (u16)idx;
5788       *pRes = c;
5789       rc = SQLITE_OK;
5790       goto moveto_index_finish;
5791     }
5792     if( lwr>=pPage->nCell ){
5793       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5794     }else{
5795       chldPg = get4byte(findCell(pPage, lwr));
5796     }
5797     pCur->ix = (u16)lwr;
5798     rc = moveToChild(pCur, chldPg);
5799     if( rc ) break;
5800   }
5801 moveto_index_finish:
5802   pCur->info.nSize = 0;
5803   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5804   return rc;
5805 }
5806 
5807 
5808 /*
5809 ** Return TRUE if the cursor is not pointing at an entry of the table.
5810 **
5811 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5812 ** past the last entry in the table or sqlite3BtreePrev() moves past
5813 ** the first entry.  TRUE is also returned if the table is empty.
5814 */
5815 int sqlite3BtreeEof(BtCursor *pCur){
5816   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5817   ** have been deleted? This API will need to change to return an error code
5818   ** as well as the boolean result value.
5819   */
5820   return (CURSOR_VALID!=pCur->eState);
5821 }
5822 
5823 /*
5824 ** Return an estimate for the number of rows in the table that pCur is
5825 ** pointing to.  Return a negative number if no estimate is currently
5826 ** available.
5827 */
5828 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5829   i64 n;
5830   u8 i;
5831 
5832   assert( cursorOwnsBtShared(pCur) );
5833   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5834 
5835   /* Currently this interface is only called by the OP_IfSmaller
5836   ** opcode, and it that case the cursor will always be valid and
5837   ** will always point to a leaf node. */
5838   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5839   if( NEVER(pCur->pPage->leaf==0) ) return -1;
5840 
5841   n = pCur->pPage->nCell;
5842   for(i=0; i<pCur->iPage; i++){
5843     n *= pCur->apPage[i]->nCell;
5844   }
5845   return n;
5846 }
5847 
5848 /*
5849 ** Advance the cursor to the next entry in the database.
5850 ** Return value:
5851 **
5852 **    SQLITE_OK        success
5853 **    SQLITE_DONE      cursor is already pointing at the last element
5854 **    otherwise        some kind of error occurred
5855 **
5856 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
5857 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5858 ** to the next cell on the current page.  The (slower) btreeNext() helper
5859 ** routine is called when it is necessary to move to a different page or
5860 ** to restore the cursor.
5861 **
5862 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5863 ** cursor corresponds to an SQL index and this routine could have been
5864 ** skipped if the SQL index had been a unique index.  The F argument
5865 ** is a hint to the implement.  SQLite btree implementation does not use
5866 ** this hint, but COMDB2 does.
5867 */
5868 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5869   int rc;
5870   int idx;
5871   MemPage *pPage;
5872 
5873   assert( cursorOwnsBtShared(pCur) );
5874   if( pCur->eState!=CURSOR_VALID ){
5875     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5876     rc = restoreCursorPosition(pCur);
5877     if( rc!=SQLITE_OK ){
5878       return rc;
5879     }
5880     if( CURSOR_INVALID==pCur->eState ){
5881       return SQLITE_DONE;
5882     }
5883     if( pCur->eState==CURSOR_SKIPNEXT ){
5884       pCur->eState = CURSOR_VALID;
5885       if( pCur->skipNext>0 ) return SQLITE_OK;
5886     }
5887   }
5888 
5889   pPage = pCur->pPage;
5890   idx = ++pCur->ix;
5891   if( !pPage->isInit || sqlite3FaultSim(412) ){
5892     /* The only known way for this to happen is for there to be a
5893     ** recursive SQL function that does a DELETE operation as part of a
5894     ** SELECT which deletes content out from under an active cursor
5895     ** in a corrupt database file where the table being DELETE-ed from
5896     ** has pages in common with the table being queried.  See TH3
5897     ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5898     ** example. */
5899     return SQLITE_CORRUPT_BKPT;
5900   }
5901 
5902   if( idx>=pPage->nCell ){
5903     if( !pPage->leaf ){
5904       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5905       if( rc ) return rc;
5906       return moveToLeftmost(pCur);
5907     }
5908     do{
5909       if( pCur->iPage==0 ){
5910         pCur->eState = CURSOR_INVALID;
5911         return SQLITE_DONE;
5912       }
5913       moveToParent(pCur);
5914       pPage = pCur->pPage;
5915     }while( pCur->ix>=pPage->nCell );
5916     if( pPage->intKey ){
5917       return sqlite3BtreeNext(pCur, 0);
5918     }else{
5919       return SQLITE_OK;
5920     }
5921   }
5922   if( pPage->leaf ){
5923     return SQLITE_OK;
5924   }else{
5925     return moveToLeftmost(pCur);
5926   }
5927 }
5928 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5929   MemPage *pPage;
5930   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5931   assert( cursorOwnsBtShared(pCur) );
5932   assert( flags==0 || flags==1 );
5933   pCur->info.nSize = 0;
5934   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5935   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5936   pPage = pCur->pPage;
5937   if( (++pCur->ix)>=pPage->nCell ){
5938     pCur->ix--;
5939     return btreeNext(pCur);
5940   }
5941   if( pPage->leaf ){
5942     return SQLITE_OK;
5943   }else{
5944     return moveToLeftmost(pCur);
5945   }
5946 }
5947 
5948 /*
5949 ** Step the cursor to the back to the previous entry in the database.
5950 ** Return values:
5951 **
5952 **     SQLITE_OK     success
5953 **     SQLITE_DONE   the cursor is already on the first element of the table
5954 **     otherwise     some kind of error occurred
5955 **
5956 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
5957 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5958 ** to the previous cell on the current page.  The (slower) btreePrevious()
5959 ** helper routine is called when it is necessary to move to a different page
5960 ** or to restore the cursor.
5961 **
5962 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5963 ** the cursor corresponds to an SQL index and this routine could have been
5964 ** skipped if the SQL index had been a unique index.  The F argument is a
5965 ** hint to the implement.  The native SQLite btree implementation does not
5966 ** use this hint, but COMDB2 does.
5967 */
5968 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5969   int rc;
5970   MemPage *pPage;
5971 
5972   assert( cursorOwnsBtShared(pCur) );
5973   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5974   assert( pCur->info.nSize==0 );
5975   if( pCur->eState!=CURSOR_VALID ){
5976     rc = restoreCursorPosition(pCur);
5977     if( rc!=SQLITE_OK ){
5978       return rc;
5979     }
5980     if( CURSOR_INVALID==pCur->eState ){
5981       return SQLITE_DONE;
5982     }
5983     if( CURSOR_SKIPNEXT==pCur->eState ){
5984       pCur->eState = CURSOR_VALID;
5985       if( pCur->skipNext<0 ) return SQLITE_OK;
5986     }
5987   }
5988 
5989   pPage = pCur->pPage;
5990   assert( pPage->isInit );
5991   if( !pPage->leaf ){
5992     int idx = pCur->ix;
5993     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5994     if( rc ) return rc;
5995     rc = moveToRightmost(pCur);
5996   }else{
5997     while( pCur->ix==0 ){
5998       if( pCur->iPage==0 ){
5999         pCur->eState = CURSOR_INVALID;
6000         return SQLITE_DONE;
6001       }
6002       moveToParent(pCur);
6003     }
6004     assert( pCur->info.nSize==0 );
6005     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6006 
6007     pCur->ix--;
6008     pPage = pCur->pPage;
6009     if( pPage->intKey && !pPage->leaf ){
6010       rc = sqlite3BtreePrevious(pCur, 0);
6011     }else{
6012       rc = SQLITE_OK;
6013     }
6014   }
6015   return rc;
6016 }
6017 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6018   assert( cursorOwnsBtShared(pCur) );
6019   assert( flags==0 || flags==1 );
6020   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
6021   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6022   pCur->info.nSize = 0;
6023   if( pCur->eState!=CURSOR_VALID
6024    || pCur->ix==0
6025    || pCur->pPage->leaf==0
6026   ){
6027     return btreePrevious(pCur);
6028   }
6029   pCur->ix--;
6030   return SQLITE_OK;
6031 }
6032 
6033 /*
6034 ** Allocate a new page from the database file.
6035 **
6036 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
6037 ** has already been called on the new page.)  The new page has also
6038 ** been referenced and the calling routine is responsible for calling
6039 ** sqlite3PagerUnref() on the new page when it is done.
6040 **
6041 ** SQLITE_OK is returned on success.  Any other return value indicates
6042 ** an error.  *ppPage is set to NULL in the event of an error.
6043 **
6044 ** If the "nearby" parameter is not 0, then an effort is made to
6045 ** locate a page close to the page number "nearby".  This can be used in an
6046 ** attempt to keep related pages close to each other in the database file,
6047 ** which in turn can make database access faster.
6048 **
6049 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6050 ** anywhere on the free-list, then it is guaranteed to be returned.  If
6051 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6052 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
6053 ** are no restrictions on which page is returned.
6054 */
6055 static int allocateBtreePage(
6056   BtShared *pBt,         /* The btree */
6057   MemPage **ppPage,      /* Store pointer to the allocated page here */
6058   Pgno *pPgno,           /* Store the page number here */
6059   Pgno nearby,           /* Search for a page near this one */
6060   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6061 ){
6062   MemPage *pPage1;
6063   int rc;
6064   u32 n;     /* Number of pages on the freelist */
6065   u32 k;     /* Number of leaves on the trunk of the freelist */
6066   MemPage *pTrunk = 0;
6067   MemPage *pPrevTrunk = 0;
6068   Pgno mxPage;     /* Total size of the database file */
6069 
6070   assert( sqlite3_mutex_held(pBt->mutex) );
6071   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6072   pPage1 = pBt->pPage1;
6073   mxPage = btreePagecount(pBt);
6074   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
6075   ** stores stores the total number of pages on the freelist. */
6076   n = get4byte(&pPage1->aData[36]);
6077   testcase( n==mxPage-1 );
6078   if( n>=mxPage ){
6079     return SQLITE_CORRUPT_BKPT;
6080   }
6081   if( n>0 ){
6082     /* There are pages on the freelist.  Reuse one of those pages. */
6083     Pgno iTrunk;
6084     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6085     u32 nSearch = 0;   /* Count of the number of search attempts */
6086 
6087     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6088     ** shows that the page 'nearby' is somewhere on the free-list, then
6089     ** the entire-list will be searched for that page.
6090     */
6091 #ifndef SQLITE_OMIT_AUTOVACUUM
6092     if( eMode==BTALLOC_EXACT ){
6093       if( nearby<=mxPage ){
6094         u8 eType;
6095         assert( nearby>0 );
6096         assert( pBt->autoVacuum );
6097         rc = ptrmapGet(pBt, nearby, &eType, 0);
6098         if( rc ) return rc;
6099         if( eType==PTRMAP_FREEPAGE ){
6100           searchList = 1;
6101         }
6102       }
6103     }else if( eMode==BTALLOC_LE ){
6104       searchList = 1;
6105     }
6106 #endif
6107 
6108     /* Decrement the free-list count by 1. Set iTrunk to the index of the
6109     ** first free-list trunk page. iPrevTrunk is initially 1.
6110     */
6111     rc = sqlite3PagerWrite(pPage1->pDbPage);
6112     if( rc ) return rc;
6113     put4byte(&pPage1->aData[36], n-1);
6114 
6115     /* The code within this loop is run only once if the 'searchList' variable
6116     ** is not true. Otherwise, it runs once for each trunk-page on the
6117     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6118     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6119     */
6120     do {
6121       pPrevTrunk = pTrunk;
6122       if( pPrevTrunk ){
6123         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6124         ** is the page number of the next freelist trunk page in the list or
6125         ** zero if this is the last freelist trunk page. */
6126         iTrunk = get4byte(&pPrevTrunk->aData[0]);
6127       }else{
6128         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6129         ** stores the page number of the first page of the freelist, or zero if
6130         ** the freelist is empty. */
6131         iTrunk = get4byte(&pPage1->aData[32]);
6132       }
6133       testcase( iTrunk==mxPage );
6134       if( iTrunk>mxPage || nSearch++ > n ){
6135         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6136       }else{
6137         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6138       }
6139       if( rc ){
6140         pTrunk = 0;
6141         goto end_allocate_page;
6142       }
6143       assert( pTrunk!=0 );
6144       assert( pTrunk->aData!=0 );
6145       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6146       ** is the number of leaf page pointers to follow. */
6147       k = get4byte(&pTrunk->aData[4]);
6148       if( k==0 && !searchList ){
6149         /* The trunk has no leaves and the list is not being searched.
6150         ** So extract the trunk page itself and use it as the newly
6151         ** allocated page */
6152         assert( pPrevTrunk==0 );
6153         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6154         if( rc ){
6155           goto end_allocate_page;
6156         }
6157         *pPgno = iTrunk;
6158         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6159         *ppPage = pTrunk;
6160         pTrunk = 0;
6161         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6162       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6163         /* Value of k is out of range.  Database corruption */
6164         rc = SQLITE_CORRUPT_PGNO(iTrunk);
6165         goto end_allocate_page;
6166 #ifndef SQLITE_OMIT_AUTOVACUUM
6167       }else if( searchList
6168             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6169       ){
6170         /* The list is being searched and this trunk page is the page
6171         ** to allocate, regardless of whether it has leaves.
6172         */
6173         *pPgno = iTrunk;
6174         *ppPage = pTrunk;
6175         searchList = 0;
6176         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6177         if( rc ){
6178           goto end_allocate_page;
6179         }
6180         if( k==0 ){
6181           if( !pPrevTrunk ){
6182             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6183           }else{
6184             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6185             if( rc!=SQLITE_OK ){
6186               goto end_allocate_page;
6187             }
6188             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6189           }
6190         }else{
6191           /* The trunk page is required by the caller but it contains
6192           ** pointers to free-list leaves. The first leaf becomes a trunk
6193           ** page in this case.
6194           */
6195           MemPage *pNewTrunk;
6196           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6197           if( iNewTrunk>mxPage ){
6198             rc = SQLITE_CORRUPT_PGNO(iTrunk);
6199             goto end_allocate_page;
6200           }
6201           testcase( iNewTrunk==mxPage );
6202           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6203           if( rc!=SQLITE_OK ){
6204             goto end_allocate_page;
6205           }
6206           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6207           if( rc!=SQLITE_OK ){
6208             releasePage(pNewTrunk);
6209             goto end_allocate_page;
6210           }
6211           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6212           put4byte(&pNewTrunk->aData[4], k-1);
6213           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6214           releasePage(pNewTrunk);
6215           if( !pPrevTrunk ){
6216             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6217             put4byte(&pPage1->aData[32], iNewTrunk);
6218           }else{
6219             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6220             if( rc ){
6221               goto end_allocate_page;
6222             }
6223             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6224           }
6225         }
6226         pTrunk = 0;
6227         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6228 #endif
6229       }else if( k>0 ){
6230         /* Extract a leaf from the trunk */
6231         u32 closest;
6232         Pgno iPage;
6233         unsigned char *aData = pTrunk->aData;
6234         if( nearby>0 ){
6235           u32 i;
6236           closest = 0;
6237           if( eMode==BTALLOC_LE ){
6238             for(i=0; i<k; i++){
6239               iPage = get4byte(&aData[8+i*4]);
6240               if( iPage<=nearby ){
6241                 closest = i;
6242                 break;
6243               }
6244             }
6245           }else{
6246             int dist;
6247             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6248             for(i=1; i<k; i++){
6249               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6250               if( d2<dist ){
6251                 closest = i;
6252                 dist = d2;
6253               }
6254             }
6255           }
6256         }else{
6257           closest = 0;
6258         }
6259 
6260         iPage = get4byte(&aData[8+closest*4]);
6261         testcase( iPage==mxPage );
6262         if( iPage>mxPage || iPage<2 ){
6263           rc = SQLITE_CORRUPT_PGNO(iTrunk);
6264           goto end_allocate_page;
6265         }
6266         testcase( iPage==mxPage );
6267         if( !searchList
6268          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6269         ){
6270           int noContent;
6271           *pPgno = iPage;
6272           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6273                  ": %d more free pages\n",
6274                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
6275           rc = sqlite3PagerWrite(pTrunk->pDbPage);
6276           if( rc ) goto end_allocate_page;
6277           if( closest<k-1 ){
6278             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6279           }
6280           put4byte(&aData[4], k-1);
6281           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6282           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6283           if( rc==SQLITE_OK ){
6284             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6285             if( rc!=SQLITE_OK ){
6286               releasePage(*ppPage);
6287               *ppPage = 0;
6288             }
6289           }
6290           searchList = 0;
6291         }
6292       }
6293       releasePage(pPrevTrunk);
6294       pPrevTrunk = 0;
6295     }while( searchList );
6296   }else{
6297     /* There are no pages on the freelist, so append a new page to the
6298     ** database image.
6299     **
6300     ** Normally, new pages allocated by this block can be requested from the
6301     ** pager layer with the 'no-content' flag set. This prevents the pager
6302     ** from trying to read the pages content from disk. However, if the
6303     ** current transaction has already run one or more incremental-vacuum
6304     ** steps, then the page we are about to allocate may contain content
6305     ** that is required in the event of a rollback. In this case, do
6306     ** not set the no-content flag. This causes the pager to load and journal
6307     ** the current page content before overwriting it.
6308     **
6309     ** Note that the pager will not actually attempt to load or journal
6310     ** content for any page that really does lie past the end of the database
6311     ** file on disk. So the effects of disabling the no-content optimization
6312     ** here are confined to those pages that lie between the end of the
6313     ** database image and the end of the database file.
6314     */
6315     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6316 
6317     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6318     if( rc ) return rc;
6319     pBt->nPage++;
6320     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6321 
6322 #ifndef SQLITE_OMIT_AUTOVACUUM
6323     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6324       /* If *pPgno refers to a pointer-map page, allocate two new pages
6325       ** at the end of the file instead of one. The first allocated page
6326       ** becomes a new pointer-map page, the second is used by the caller.
6327       */
6328       MemPage *pPg = 0;
6329       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6330       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6331       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6332       if( rc==SQLITE_OK ){
6333         rc = sqlite3PagerWrite(pPg->pDbPage);
6334         releasePage(pPg);
6335       }
6336       if( rc ) return rc;
6337       pBt->nPage++;
6338       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6339     }
6340 #endif
6341     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6342     *pPgno = pBt->nPage;
6343 
6344     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6345     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6346     if( rc ) return rc;
6347     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6348     if( rc!=SQLITE_OK ){
6349       releasePage(*ppPage);
6350       *ppPage = 0;
6351     }
6352     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6353   }
6354 
6355   assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6356 
6357 end_allocate_page:
6358   releasePage(pTrunk);
6359   releasePage(pPrevTrunk);
6360   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6361   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6362   return rc;
6363 }
6364 
6365 /*
6366 ** This function is used to add page iPage to the database file free-list.
6367 ** It is assumed that the page is not already a part of the free-list.
6368 **
6369 ** The value passed as the second argument to this function is optional.
6370 ** If the caller happens to have a pointer to the MemPage object
6371 ** corresponding to page iPage handy, it may pass it as the second value.
6372 ** Otherwise, it may pass NULL.
6373 **
6374 ** If a pointer to a MemPage object is passed as the second argument,
6375 ** its reference count is not altered by this function.
6376 */
6377 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6378   MemPage *pTrunk = 0;                /* Free-list trunk page */
6379   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
6380   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
6381   MemPage *pPage;                     /* Page being freed. May be NULL. */
6382   int rc;                             /* Return Code */
6383   u32 nFree;                          /* Initial number of pages on free-list */
6384 
6385   assert( sqlite3_mutex_held(pBt->mutex) );
6386   assert( CORRUPT_DB || iPage>1 );
6387   assert( !pMemPage || pMemPage->pgno==iPage );
6388 
6389   if( NEVER(iPage<2) || iPage>pBt->nPage ){
6390     return SQLITE_CORRUPT_BKPT;
6391   }
6392   if( pMemPage ){
6393     pPage = pMemPage;
6394     sqlite3PagerRef(pPage->pDbPage);
6395   }else{
6396     pPage = btreePageLookup(pBt, iPage);
6397   }
6398 
6399   /* Increment the free page count on pPage1 */
6400   rc = sqlite3PagerWrite(pPage1->pDbPage);
6401   if( rc ) goto freepage_out;
6402   nFree = get4byte(&pPage1->aData[36]);
6403   put4byte(&pPage1->aData[36], nFree+1);
6404 
6405   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6406     /* If the secure_delete option is enabled, then
6407     ** always fully overwrite deleted information with zeros.
6408     */
6409     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6410      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6411     ){
6412       goto freepage_out;
6413     }
6414     memset(pPage->aData, 0, pPage->pBt->pageSize);
6415   }
6416 
6417   /* If the database supports auto-vacuum, write an entry in the pointer-map
6418   ** to indicate that the page is free.
6419   */
6420   if( ISAUTOVACUUM ){
6421     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6422     if( rc ) goto freepage_out;
6423   }
6424 
6425   /* Now manipulate the actual database free-list structure. There are two
6426   ** possibilities. If the free-list is currently empty, or if the first
6427   ** trunk page in the free-list is full, then this page will become a
6428   ** new free-list trunk page. Otherwise, it will become a leaf of the
6429   ** first trunk page in the current free-list. This block tests if it
6430   ** is possible to add the page as a new free-list leaf.
6431   */
6432   if( nFree!=0 ){
6433     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6434 
6435     iTrunk = get4byte(&pPage1->aData[32]);
6436     if( iTrunk>btreePagecount(pBt) ){
6437       rc = SQLITE_CORRUPT_BKPT;
6438       goto freepage_out;
6439     }
6440     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6441     if( rc!=SQLITE_OK ){
6442       goto freepage_out;
6443     }
6444 
6445     nLeaf = get4byte(&pTrunk->aData[4]);
6446     assert( pBt->usableSize>32 );
6447     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6448       rc = SQLITE_CORRUPT_BKPT;
6449       goto freepage_out;
6450     }
6451     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6452       /* In this case there is room on the trunk page to insert the page
6453       ** being freed as a new leaf.
6454       **
6455       ** Note that the trunk page is not really full until it contains
6456       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6457       ** coded.  But due to a coding error in versions of SQLite prior to
6458       ** 3.6.0, databases with freelist trunk pages holding more than
6459       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6460       ** to maintain backwards compatibility with older versions of SQLite,
6461       ** we will continue to restrict the number of entries to usableSize/4 - 8
6462       ** for now.  At some point in the future (once everyone has upgraded
6463       ** to 3.6.0 or later) we should consider fixing the conditional above
6464       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6465       **
6466       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6467       ** avoid using the last six entries in the freelist trunk page array in
6468       ** order that database files created by newer versions of SQLite can be
6469       ** read by older versions of SQLite.
6470       */
6471       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6472       if( rc==SQLITE_OK ){
6473         put4byte(&pTrunk->aData[4], nLeaf+1);
6474         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6475         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6476           sqlite3PagerDontWrite(pPage->pDbPage);
6477         }
6478         rc = btreeSetHasContent(pBt, iPage);
6479       }
6480       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6481       goto freepage_out;
6482     }
6483   }
6484 
6485   /* If control flows to this point, then it was not possible to add the
6486   ** the page being freed as a leaf page of the first trunk in the free-list.
6487   ** Possibly because the free-list is empty, or possibly because the
6488   ** first trunk in the free-list is full. Either way, the page being freed
6489   ** will become the new first trunk page in the free-list.
6490   */
6491   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6492     goto freepage_out;
6493   }
6494   rc = sqlite3PagerWrite(pPage->pDbPage);
6495   if( rc!=SQLITE_OK ){
6496     goto freepage_out;
6497   }
6498   put4byte(pPage->aData, iTrunk);
6499   put4byte(&pPage->aData[4], 0);
6500   put4byte(&pPage1->aData[32], iPage);
6501   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6502 
6503 freepage_out:
6504   if( pPage ){
6505     pPage->isInit = 0;
6506   }
6507   releasePage(pPage);
6508   releasePage(pTrunk);
6509   return rc;
6510 }
6511 static void freePage(MemPage *pPage, int *pRC){
6512   if( (*pRC)==SQLITE_OK ){
6513     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6514   }
6515 }
6516 
6517 /*
6518 ** Free the overflow pages associated with the given Cell.
6519 */
6520 static SQLITE_NOINLINE int clearCellOverflow(
6521   MemPage *pPage,          /* The page that contains the Cell */
6522   unsigned char *pCell,    /* First byte of the Cell */
6523   CellInfo *pInfo          /* Size information about the cell */
6524 ){
6525   BtShared *pBt;
6526   Pgno ovflPgno;
6527   int rc;
6528   int nOvfl;
6529   u32 ovflPageSize;
6530 
6531   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6532   assert( pInfo->nLocal!=pInfo->nPayload );
6533   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6534   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6535   if( pCell + pInfo->nSize > pPage->aDataEnd ){
6536     /* Cell extends past end of page */
6537     return SQLITE_CORRUPT_PAGE(pPage);
6538   }
6539   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6540   pBt = pPage->pBt;
6541   assert( pBt->usableSize > 4 );
6542   ovflPageSize = pBt->usableSize - 4;
6543   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6544   assert( nOvfl>0 ||
6545     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6546   );
6547   while( nOvfl-- ){
6548     Pgno iNext = 0;
6549     MemPage *pOvfl = 0;
6550     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6551       /* 0 is not a legal page number and page 1 cannot be an
6552       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6553       ** file the database must be corrupt. */
6554       return SQLITE_CORRUPT_BKPT;
6555     }
6556     if( nOvfl ){
6557       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6558       if( rc ) return rc;
6559     }
6560 
6561     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6562      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6563     ){
6564       /* There is no reason any cursor should have an outstanding reference
6565       ** to an overflow page belonging to a cell that is being deleted/updated.
6566       ** So if there exists more than one reference to this page, then it
6567       ** must not really be an overflow page and the database must be corrupt.
6568       ** It is helpful to detect this before calling freePage2(), as
6569       ** freePage2() may zero the page contents if secure-delete mode is
6570       ** enabled. If this 'overflow' page happens to be a page that the
6571       ** caller is iterating through or using in some other way, this
6572       ** can be problematic.
6573       */
6574       rc = SQLITE_CORRUPT_BKPT;
6575     }else{
6576       rc = freePage2(pBt, pOvfl, ovflPgno);
6577     }
6578 
6579     if( pOvfl ){
6580       sqlite3PagerUnref(pOvfl->pDbPage);
6581     }
6582     if( rc ) return rc;
6583     ovflPgno = iNext;
6584   }
6585   return SQLITE_OK;
6586 }
6587 
6588 /* Call xParseCell to compute the size of a cell.  If the cell contains
6589 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6590 ** STore the result code (SQLITE_OK or some error code) in rc.
6591 **
6592 ** Implemented as macro to force inlining for performance.
6593 */
6594 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo)   \
6595   pPage->xParseCell(pPage, pCell, &sInfo);          \
6596   if( sInfo.nLocal!=sInfo.nPayload ){               \
6597     rc = clearCellOverflow(pPage, pCell, &sInfo);   \
6598   }else{                                            \
6599     rc = SQLITE_OK;                                 \
6600   }
6601 
6602 
6603 /*
6604 ** Create the byte sequence used to represent a cell on page pPage
6605 ** and write that byte sequence into pCell[].  Overflow pages are
6606 ** allocated and filled in as necessary.  The calling procedure
6607 ** is responsible for making sure sufficient space has been allocated
6608 ** for pCell[].
6609 **
6610 ** Note that pCell does not necessary need to point to the pPage->aData
6611 ** area.  pCell might point to some temporary storage.  The cell will
6612 ** be constructed in this temporary area then copied into pPage->aData
6613 ** later.
6614 */
6615 static int fillInCell(
6616   MemPage *pPage,                /* The page that contains the cell */
6617   unsigned char *pCell,          /* Complete text of the cell */
6618   const BtreePayload *pX,        /* Payload with which to construct the cell */
6619   int *pnSize                    /* Write cell size here */
6620 ){
6621   int nPayload;
6622   const u8 *pSrc;
6623   int nSrc, n, rc, mn;
6624   int spaceLeft;
6625   MemPage *pToRelease;
6626   unsigned char *pPrior;
6627   unsigned char *pPayload;
6628   BtShared *pBt;
6629   Pgno pgnoOvfl;
6630   int nHeader;
6631 
6632   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6633 
6634   /* pPage is not necessarily writeable since pCell might be auxiliary
6635   ** buffer space that is separate from the pPage buffer area */
6636   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6637             || sqlite3PagerIswriteable(pPage->pDbPage) );
6638 
6639   /* Fill in the header. */
6640   nHeader = pPage->childPtrSize;
6641   if( pPage->intKey ){
6642     nPayload = pX->nData + pX->nZero;
6643     pSrc = pX->pData;
6644     nSrc = pX->nData;
6645     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6646     nHeader += putVarint32(&pCell[nHeader], nPayload);
6647     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6648   }else{
6649     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6650     nSrc = nPayload = (int)pX->nKey;
6651     pSrc = pX->pKey;
6652     nHeader += putVarint32(&pCell[nHeader], nPayload);
6653   }
6654 
6655   /* Fill in the payload */
6656   pPayload = &pCell[nHeader];
6657   if( nPayload<=pPage->maxLocal ){
6658     /* This is the common case where everything fits on the btree page
6659     ** and no overflow pages are required. */
6660     n = nHeader + nPayload;
6661     testcase( n==3 );
6662     testcase( n==4 );
6663     if( n<4 ) n = 4;
6664     *pnSize = n;
6665     assert( nSrc<=nPayload );
6666     testcase( nSrc<nPayload );
6667     memcpy(pPayload, pSrc, nSrc);
6668     memset(pPayload+nSrc, 0, nPayload-nSrc);
6669     return SQLITE_OK;
6670   }
6671 
6672   /* If we reach this point, it means that some of the content will need
6673   ** to spill onto overflow pages.
6674   */
6675   mn = pPage->minLocal;
6676   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6677   testcase( n==pPage->maxLocal );
6678   testcase( n==pPage->maxLocal+1 );
6679   if( n > pPage->maxLocal ) n = mn;
6680   spaceLeft = n;
6681   *pnSize = n + nHeader + 4;
6682   pPrior = &pCell[nHeader+n];
6683   pToRelease = 0;
6684   pgnoOvfl = 0;
6685   pBt = pPage->pBt;
6686 
6687   /* At this point variables should be set as follows:
6688   **
6689   **   nPayload           Total payload size in bytes
6690   **   pPayload           Begin writing payload here
6691   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6692   **                      that means content must spill into overflow pages.
6693   **   *pnSize            Size of the local cell (not counting overflow pages)
6694   **   pPrior             Where to write the pgno of the first overflow page
6695   **
6696   ** Use a call to btreeParseCellPtr() to verify that the values above
6697   ** were computed correctly.
6698   */
6699 #ifdef SQLITE_DEBUG
6700   {
6701     CellInfo info;
6702     pPage->xParseCell(pPage, pCell, &info);
6703     assert( nHeader==(int)(info.pPayload - pCell) );
6704     assert( info.nKey==pX->nKey );
6705     assert( *pnSize == info.nSize );
6706     assert( spaceLeft == info.nLocal );
6707   }
6708 #endif
6709 
6710   /* Write the payload into the local Cell and any extra into overflow pages */
6711   while( 1 ){
6712     n = nPayload;
6713     if( n>spaceLeft ) n = spaceLeft;
6714 
6715     /* If pToRelease is not zero than pPayload points into the data area
6716     ** of pToRelease.  Make sure pToRelease is still writeable. */
6717     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6718 
6719     /* If pPayload is part of the data area of pPage, then make sure pPage
6720     ** is still writeable */
6721     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6722             || sqlite3PagerIswriteable(pPage->pDbPage) );
6723 
6724     if( nSrc>=n ){
6725       memcpy(pPayload, pSrc, n);
6726     }else if( nSrc>0 ){
6727       n = nSrc;
6728       memcpy(pPayload, pSrc, n);
6729     }else{
6730       memset(pPayload, 0, n);
6731     }
6732     nPayload -= n;
6733     if( nPayload<=0 ) break;
6734     pPayload += n;
6735     pSrc += n;
6736     nSrc -= n;
6737     spaceLeft -= n;
6738     if( spaceLeft==0 ){
6739       MemPage *pOvfl = 0;
6740 #ifndef SQLITE_OMIT_AUTOVACUUM
6741       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6742       if( pBt->autoVacuum ){
6743         do{
6744           pgnoOvfl++;
6745         } while(
6746           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6747         );
6748       }
6749 #endif
6750       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6751 #ifndef SQLITE_OMIT_AUTOVACUUM
6752       /* If the database supports auto-vacuum, and the second or subsequent
6753       ** overflow page is being allocated, add an entry to the pointer-map
6754       ** for that page now.
6755       **
6756       ** If this is the first overflow page, then write a partial entry
6757       ** to the pointer-map. If we write nothing to this pointer-map slot,
6758       ** then the optimistic overflow chain processing in clearCell()
6759       ** may misinterpret the uninitialized values and delete the
6760       ** wrong pages from the database.
6761       */
6762       if( pBt->autoVacuum && rc==SQLITE_OK ){
6763         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6764         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6765         if( rc ){
6766           releasePage(pOvfl);
6767         }
6768       }
6769 #endif
6770       if( rc ){
6771         releasePage(pToRelease);
6772         return rc;
6773       }
6774 
6775       /* If pToRelease is not zero than pPrior points into the data area
6776       ** of pToRelease.  Make sure pToRelease is still writeable. */
6777       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6778 
6779       /* If pPrior is part of the data area of pPage, then make sure pPage
6780       ** is still writeable */
6781       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6782             || sqlite3PagerIswriteable(pPage->pDbPage) );
6783 
6784       put4byte(pPrior, pgnoOvfl);
6785       releasePage(pToRelease);
6786       pToRelease = pOvfl;
6787       pPrior = pOvfl->aData;
6788       put4byte(pPrior, 0);
6789       pPayload = &pOvfl->aData[4];
6790       spaceLeft = pBt->usableSize - 4;
6791     }
6792   }
6793   releasePage(pToRelease);
6794   return SQLITE_OK;
6795 }
6796 
6797 /*
6798 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6799 ** The cell content is not freed or deallocated.  It is assumed that
6800 ** the cell content has been copied someplace else.  This routine just
6801 ** removes the reference to the cell from pPage.
6802 **
6803 ** "sz" must be the number of bytes in the cell.
6804 */
6805 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6806   u32 pc;         /* Offset to cell content of cell being deleted */
6807   u8 *data;       /* pPage->aData */
6808   u8 *ptr;        /* Used to move bytes around within data[] */
6809   int rc;         /* The return code */
6810   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6811 
6812   if( *pRC ) return;
6813   assert( idx>=0 && idx<pPage->nCell );
6814   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6815   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6816   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6817   assert( pPage->nFree>=0 );
6818   data = pPage->aData;
6819   ptr = &pPage->aCellIdx[2*idx];
6820   pc = get2byte(ptr);
6821   hdr = pPage->hdrOffset;
6822   testcase( pc==get2byte(&data[hdr+5]) );
6823   testcase( pc+sz==pPage->pBt->usableSize );
6824   if( pc+sz > pPage->pBt->usableSize ){
6825     *pRC = SQLITE_CORRUPT_BKPT;
6826     return;
6827   }
6828   rc = freeSpace(pPage, pc, sz);
6829   if( rc ){
6830     *pRC = rc;
6831     return;
6832   }
6833   pPage->nCell--;
6834   if( pPage->nCell==0 ){
6835     memset(&data[hdr+1], 0, 4);
6836     data[hdr+7] = 0;
6837     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6838     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6839                        - pPage->childPtrSize - 8;
6840   }else{
6841     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6842     put2byte(&data[hdr+3], pPage->nCell);
6843     pPage->nFree += 2;
6844   }
6845 }
6846 
6847 /*
6848 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6849 ** content of the cell.
6850 **
6851 ** If the cell content will fit on the page, then put it there.  If it
6852 ** will not fit, then make a copy of the cell content into pTemp if
6853 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6854 ** in pPage->apOvfl[] and make it point to the cell content (either
6855 ** in pTemp or the original pCell) and also record its index.
6856 ** Allocating a new entry in pPage->aCell[] implies that
6857 ** pPage->nOverflow is incremented.
6858 **
6859 ** *pRC must be SQLITE_OK when this routine is called.
6860 */
6861 static void insertCell(
6862   MemPage *pPage,   /* Page into which we are copying */
6863   int i,            /* New cell becomes the i-th cell of the page */
6864   u8 *pCell,        /* Content of the new cell */
6865   int sz,           /* Bytes of content in pCell */
6866   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6867   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6868   int *pRC          /* Read and write return code from here */
6869 ){
6870   int idx = 0;      /* Where to write new cell content in data[] */
6871   int j;            /* Loop counter */
6872   u8 *data;         /* The content of the whole page */
6873   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6874 
6875   assert( *pRC==SQLITE_OK );
6876   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6877   assert( MX_CELL(pPage->pBt)<=10921 );
6878   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6879   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6880   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6881   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6882   assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6883   assert( pPage->nFree>=0 );
6884   if( pPage->nOverflow || sz+2>pPage->nFree ){
6885     if( pTemp ){
6886       memcpy(pTemp, pCell, sz);
6887       pCell = pTemp;
6888     }
6889     if( iChild ){
6890       put4byte(pCell, iChild);
6891     }
6892     j = pPage->nOverflow++;
6893     /* Comparison against ArraySize-1 since we hold back one extra slot
6894     ** as a contingency.  In other words, never need more than 3 overflow
6895     ** slots but 4 are allocated, just to be safe. */
6896     assert( j < ArraySize(pPage->apOvfl)-1 );
6897     pPage->apOvfl[j] = pCell;
6898     pPage->aiOvfl[j] = (u16)i;
6899 
6900     /* When multiple overflows occur, they are always sequential and in
6901     ** sorted order.  This invariants arise because multiple overflows can
6902     ** only occur when inserting divider cells into the parent page during
6903     ** balancing, and the dividers are adjacent and sorted.
6904     */
6905     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6906     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6907   }else{
6908     int rc = sqlite3PagerWrite(pPage->pDbPage);
6909     if( rc!=SQLITE_OK ){
6910       *pRC = rc;
6911       return;
6912     }
6913     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6914     data = pPage->aData;
6915     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6916     rc = allocateSpace(pPage, sz, &idx);
6917     if( rc ){ *pRC = rc; return; }
6918     /* The allocateSpace() routine guarantees the following properties
6919     ** if it returns successfully */
6920     assert( idx >= 0 );
6921     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6922     assert( idx+sz <= (int)pPage->pBt->usableSize );
6923     pPage->nFree -= (u16)(2 + sz);
6924     if( iChild ){
6925       /* In a corrupt database where an entry in the cell index section of
6926       ** a btree page has a value of 3 or less, the pCell value might point
6927       ** as many as 4 bytes in front of the start of the aData buffer for
6928       ** the source page.  Make sure this does not cause problems by not
6929       ** reading the first 4 bytes */
6930       memcpy(&data[idx+4], pCell+4, sz-4);
6931       put4byte(&data[idx], iChild);
6932     }else{
6933       memcpy(&data[idx], pCell, sz);
6934     }
6935     pIns = pPage->aCellIdx + i*2;
6936     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6937     put2byte(pIns, idx);
6938     pPage->nCell++;
6939     /* increment the cell count */
6940     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6941     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6942 #ifndef SQLITE_OMIT_AUTOVACUUM
6943     if( pPage->pBt->autoVacuum ){
6944       /* The cell may contain a pointer to an overflow page. If so, write
6945       ** the entry for the overflow page into the pointer map.
6946       */
6947       ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6948     }
6949 #endif
6950   }
6951 }
6952 
6953 /*
6954 ** The following parameters determine how many adjacent pages get involved
6955 ** in a balancing operation.  NN is the number of neighbors on either side
6956 ** of the page that participate in the balancing operation.  NB is the
6957 ** total number of pages that participate, including the target page and
6958 ** NN neighbors on either side.
6959 **
6960 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
6961 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6962 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6963 ** The value of NN appears to give the best results overall.
6964 **
6965 ** (Later:) The description above makes it seem as if these values are
6966 ** tunable - as if you could change them and recompile and it would all work.
6967 ** But that is unlikely.  NB has been 3 since the inception of SQLite and
6968 ** we have never tested any other value.
6969 */
6970 #define NN 1             /* Number of neighbors on either side of pPage */
6971 #define NB 3             /* (NN*2+1): Total pages involved in the balance */
6972 
6973 /*
6974 ** A CellArray object contains a cache of pointers and sizes for a
6975 ** consecutive sequence of cells that might be held on multiple pages.
6976 **
6977 ** The cells in this array are the divider cell or cells from the pParent
6978 ** page plus up to three child pages.  There are a total of nCell cells.
6979 **
6980 ** pRef is a pointer to one of the pages that contributes cells.  This is
6981 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6982 ** which should be common to all pages that contribute cells to this array.
6983 **
6984 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6985 ** cell and the size of each cell.  Some of the apCell[] pointers might refer
6986 ** to overflow cells.  In other words, some apCel[] pointers might not point
6987 ** to content area of the pages.
6988 **
6989 ** A szCell[] of zero means the size of that cell has not yet been computed.
6990 **
6991 ** The cells come from as many as four different pages:
6992 **
6993 **             -----------
6994 **             | Parent  |
6995 **             -----------
6996 **            /     |     \
6997 **           /      |      \
6998 **  ---------   ---------   ---------
6999 **  |Child-1|   |Child-2|   |Child-3|
7000 **  ---------   ---------   ---------
7001 **
7002 ** The order of cells is in the array is for an index btree is:
7003 **
7004 **       1.  All cells from Child-1 in order
7005 **       2.  The first divider cell from Parent
7006 **       3.  All cells from Child-2 in order
7007 **       4.  The second divider cell from Parent
7008 **       5.  All cells from Child-3 in order
7009 **
7010 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7011 ** content exists only in leaves and there are no divider cells.
7012 **
7013 ** For an index btree, the apEnd[] array holds pointer to the end of page
7014 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7015 ** respectively. The ixNx[] array holds the number of cells contained in
7016 ** each of these 5 stages, and all stages to the left.  Hence:
7017 **
7018 **    ixNx[0] = Number of cells in Child-1.
7019 **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7020 **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7021 **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7022 **    ixNx[4] = Total number of cells.
7023 **
7024 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7025 ** are used and they point to the leaf pages only, and the ixNx value are:
7026 **
7027 **    ixNx[0] = Number of cells in Child-1.
7028 **    ixNx[1] = Number of cells in Child-1 and Child-2.
7029 **    ixNx[2] = Total number of cells.
7030 **
7031 ** Sometimes when deleting, a child page can have zero cells.  In those
7032 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7033 ** entries, shift down.  The end result is that each ixNx[] entry should
7034 ** be larger than the previous
7035 */
7036 typedef struct CellArray CellArray;
7037 struct CellArray {
7038   int nCell;              /* Number of cells in apCell[] */
7039   MemPage *pRef;          /* Reference page */
7040   u8 **apCell;            /* All cells begin balanced */
7041   u16 *szCell;            /* Local size of all cells in apCell[] */
7042   u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
7043   int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
7044 };
7045 
7046 /*
7047 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7048 ** computed.
7049 */
7050 static void populateCellCache(CellArray *p, int idx, int N){
7051   assert( idx>=0 && idx+N<=p->nCell );
7052   while( N>0 ){
7053     assert( p->apCell[idx]!=0 );
7054     if( p->szCell[idx]==0 ){
7055       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
7056     }else{
7057       assert( CORRUPT_DB ||
7058               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
7059     }
7060     idx++;
7061     N--;
7062   }
7063 }
7064 
7065 /*
7066 ** Return the size of the Nth element of the cell array
7067 */
7068 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7069   assert( N>=0 && N<p->nCell );
7070   assert( p->szCell[N]==0 );
7071   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7072   return p->szCell[N];
7073 }
7074 static u16 cachedCellSize(CellArray *p, int N){
7075   assert( N>=0 && N<p->nCell );
7076   if( p->szCell[N] ) return p->szCell[N];
7077   return computeCellSize(p, N);
7078 }
7079 
7080 /*
7081 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7082 ** szCell[] array contains the size in bytes of each cell. This function
7083 ** replaces the current contents of page pPg with the contents of the cell
7084 ** array.
7085 **
7086 ** Some of the cells in apCell[] may currently be stored in pPg. This
7087 ** function works around problems caused by this by making a copy of any
7088 ** such cells before overwriting the page data.
7089 **
7090 ** The MemPage.nFree field is invalidated by this function. It is the
7091 ** responsibility of the caller to set it correctly.
7092 */
7093 static int rebuildPage(
7094   CellArray *pCArray,             /* Content to be added to page pPg */
7095   int iFirst,                     /* First cell in pCArray to use */
7096   int nCell,                      /* Final number of cells on page */
7097   MemPage *pPg                    /* The page to be reconstructed */
7098 ){
7099   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
7100   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
7101   const int usableSize = pPg->pBt->usableSize;
7102   u8 * const pEnd = &aData[usableSize];
7103   int i = iFirst;                 /* Which cell to copy from pCArray*/
7104   u32 j;                          /* Start of cell content area */
7105   int iEnd = i+nCell;             /* Loop terminator */
7106   u8 *pCellptr = pPg->aCellIdx;
7107   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7108   u8 *pData;
7109   int k;                          /* Current slot in pCArray->apEnd[] */
7110   u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
7111 
7112   assert( i<iEnd );
7113   j = get2byte(&aData[hdr+5]);
7114   if( NEVER(j>(u32)usableSize) ){ j = 0; }
7115   memcpy(&pTmp[j], &aData[j], usableSize - j);
7116 
7117   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7118   pSrcEnd = pCArray->apEnd[k];
7119 
7120   pData = pEnd;
7121   while( 1/*exit by break*/ ){
7122     u8 *pCell = pCArray->apCell[i];
7123     u16 sz = pCArray->szCell[i];
7124     assert( sz>0 );
7125     if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7126       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7127       pCell = &pTmp[pCell - aData];
7128     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7129            && (uptr)(pCell)<(uptr)pSrcEnd
7130     ){
7131       return SQLITE_CORRUPT_BKPT;
7132     }
7133 
7134     pData -= sz;
7135     put2byte(pCellptr, (pData - aData));
7136     pCellptr += 2;
7137     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7138     memmove(pData, pCell, sz);
7139     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7140     i++;
7141     if( i>=iEnd ) break;
7142     if( pCArray->ixNx[k]<=i ){
7143       k++;
7144       pSrcEnd = pCArray->apEnd[k];
7145     }
7146   }
7147 
7148   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7149   pPg->nCell = nCell;
7150   pPg->nOverflow = 0;
7151 
7152   put2byte(&aData[hdr+1], 0);
7153   put2byte(&aData[hdr+3], pPg->nCell);
7154   put2byte(&aData[hdr+5], pData - aData);
7155   aData[hdr+7] = 0x00;
7156   return SQLITE_OK;
7157 }
7158 
7159 /*
7160 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7161 ** This function attempts to add the cells stored in the array to page pPg.
7162 ** If it cannot (because the page needs to be defragmented before the cells
7163 ** will fit), non-zero is returned. Otherwise, if the cells are added
7164 ** successfully, zero is returned.
7165 **
7166 ** Argument pCellptr points to the first entry in the cell-pointer array
7167 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7168 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7169 ** cell in the array. It is the responsibility of the caller to ensure
7170 ** that it is safe to overwrite this part of the cell-pointer array.
7171 **
7172 ** When this function is called, *ppData points to the start of the
7173 ** content area on page pPg. If the size of the content area is extended,
7174 ** *ppData is updated to point to the new start of the content area
7175 ** before returning.
7176 **
7177 ** Finally, argument pBegin points to the byte immediately following the
7178 ** end of the space required by this page for the cell-pointer area (for
7179 ** all cells - not just those inserted by the current call). If the content
7180 ** area must be extended to before this point in order to accomodate all
7181 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7182 */
7183 static int pageInsertArray(
7184   MemPage *pPg,                   /* Page to add cells to */
7185   u8 *pBegin,                     /* End of cell-pointer array */
7186   u8 **ppData,                    /* IN/OUT: Page content-area pointer */
7187   u8 *pCellptr,                   /* Pointer to cell-pointer area */
7188   int iFirst,                     /* Index of first cell to add */
7189   int nCell,                      /* Number of cells to add to pPg */
7190   CellArray *pCArray              /* Array of cells */
7191 ){
7192   int i = iFirst;                 /* Loop counter - cell index to insert */
7193   u8 *aData = pPg->aData;         /* Complete page */
7194   u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
7195   int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
7196   int k;                          /* Current slot in pCArray->apEnd[] */
7197   u8 *pEnd;                       /* Maximum extent of cell data */
7198   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
7199   if( iEnd<=iFirst ) return 0;
7200   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7201   pEnd = pCArray->apEnd[k];
7202   while( 1 /*Exit by break*/ ){
7203     int sz, rc;
7204     u8 *pSlot;
7205     assert( pCArray->szCell[i]!=0 );
7206     sz = pCArray->szCell[i];
7207     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7208       if( (pData - pBegin)<sz ) return 1;
7209       pData -= sz;
7210       pSlot = pData;
7211     }
7212     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7213     ** database.  But they might for a corrupt database.  Hence use memmove()
7214     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7215     assert( (pSlot+sz)<=pCArray->apCell[i]
7216          || pSlot>=(pCArray->apCell[i]+sz)
7217          || CORRUPT_DB );
7218     if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7219      && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7220     ){
7221       assert( CORRUPT_DB );
7222       (void)SQLITE_CORRUPT_BKPT;
7223       return 1;
7224     }
7225     memmove(pSlot, pCArray->apCell[i], sz);
7226     put2byte(pCellptr, (pSlot - aData));
7227     pCellptr += 2;
7228     i++;
7229     if( i>=iEnd ) break;
7230     if( pCArray->ixNx[k]<=i ){
7231       k++;
7232       pEnd = pCArray->apEnd[k];
7233     }
7234   }
7235   *ppData = pData;
7236   return 0;
7237 }
7238 
7239 /*
7240 ** The pCArray object contains pointers to b-tree cells and their sizes.
7241 **
7242 ** This function adds the space associated with each cell in the array
7243 ** that is currently stored within the body of pPg to the pPg free-list.
7244 ** The cell-pointers and other fields of the page are not updated.
7245 **
7246 ** This function returns the total number of cells added to the free-list.
7247 */
7248 static int pageFreeArray(
7249   MemPage *pPg,                   /* Page to edit */
7250   int iFirst,                     /* First cell to delete */
7251   int nCell,                      /* Cells to delete */
7252   CellArray *pCArray              /* Array of cells */
7253 ){
7254   u8 * const aData = pPg->aData;
7255   u8 * const pEnd = &aData[pPg->pBt->usableSize];
7256   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7257   int nRet = 0;
7258   int i;
7259   int iEnd = iFirst + nCell;
7260   u8 *pFree = 0;
7261   int szFree = 0;
7262 
7263   for(i=iFirst; i<iEnd; i++){
7264     u8 *pCell = pCArray->apCell[i];
7265     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7266       int sz;
7267       /* No need to use cachedCellSize() here.  The sizes of all cells that
7268       ** are to be freed have already been computing while deciding which
7269       ** cells need freeing */
7270       sz = pCArray->szCell[i];  assert( sz>0 );
7271       if( pFree!=(pCell + sz) ){
7272         if( pFree ){
7273           assert( pFree>aData && (pFree - aData)<65536 );
7274           freeSpace(pPg, (u16)(pFree - aData), szFree);
7275         }
7276         pFree = pCell;
7277         szFree = sz;
7278         if( pFree+sz>pEnd ){
7279           return 0;
7280         }
7281       }else{
7282         pFree = pCell;
7283         szFree += sz;
7284       }
7285       nRet++;
7286     }
7287   }
7288   if( pFree ){
7289     assert( pFree>aData && (pFree - aData)<65536 );
7290     freeSpace(pPg, (u16)(pFree - aData), szFree);
7291   }
7292   return nRet;
7293 }
7294 
7295 /*
7296 ** pCArray contains pointers to and sizes of all cells in the page being
7297 ** balanced.  The current page, pPg, has pPg->nCell cells starting with
7298 ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
7299 ** starting at apCell[iNew].
7300 **
7301 ** This routine makes the necessary adjustments to pPg so that it contains
7302 ** the correct cells after being balanced.
7303 **
7304 ** The pPg->nFree field is invalid when this function returns. It is the
7305 ** responsibility of the caller to set it correctly.
7306 */
7307 static int editPage(
7308   MemPage *pPg,                   /* Edit this page */
7309   int iOld,                       /* Index of first cell currently on page */
7310   int iNew,                       /* Index of new first cell on page */
7311   int nNew,                       /* Final number of cells on page */
7312   CellArray *pCArray              /* Array of cells and sizes */
7313 ){
7314   u8 * const aData = pPg->aData;
7315   const int hdr = pPg->hdrOffset;
7316   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7317   int nCell = pPg->nCell;       /* Cells stored on pPg */
7318   u8 *pData;
7319   u8 *pCellptr;
7320   int i;
7321   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7322   int iNewEnd = iNew + nNew;
7323 
7324 #ifdef SQLITE_DEBUG
7325   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7326   memcpy(pTmp, aData, pPg->pBt->usableSize);
7327 #endif
7328 
7329   /* Remove cells from the start and end of the page */
7330   assert( nCell>=0 );
7331   if( iOld<iNew ){
7332     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7333     if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7334     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7335     nCell -= nShift;
7336   }
7337   if( iNewEnd < iOldEnd ){
7338     int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7339     assert( nCell>=nTail );
7340     nCell -= nTail;
7341   }
7342 
7343   pData = &aData[get2byteNotZero(&aData[hdr+5])];
7344   if( pData<pBegin ) goto editpage_fail;
7345   if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
7346 
7347   /* Add cells to the start of the page */
7348   if( iNew<iOld ){
7349     int nAdd = MIN(nNew,iOld-iNew);
7350     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7351     assert( nAdd>=0 );
7352     pCellptr = pPg->aCellIdx;
7353     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7354     if( pageInsertArray(
7355           pPg, pBegin, &pData, pCellptr,
7356           iNew, nAdd, pCArray
7357     ) ) goto editpage_fail;
7358     nCell += nAdd;
7359   }
7360 
7361   /* Add any overflow cells */
7362   for(i=0; i<pPg->nOverflow; i++){
7363     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7364     if( iCell>=0 && iCell<nNew ){
7365       pCellptr = &pPg->aCellIdx[iCell * 2];
7366       if( nCell>iCell ){
7367         memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7368       }
7369       nCell++;
7370       cachedCellSize(pCArray, iCell+iNew);
7371       if( pageInsertArray(
7372             pPg, pBegin, &pData, pCellptr,
7373             iCell+iNew, 1, pCArray
7374       ) ) goto editpage_fail;
7375     }
7376   }
7377 
7378   /* Append cells to the end of the page */
7379   assert( nCell>=0 );
7380   pCellptr = &pPg->aCellIdx[nCell*2];
7381   if( pageInsertArray(
7382         pPg, pBegin, &pData, pCellptr,
7383         iNew+nCell, nNew-nCell, pCArray
7384   ) ) goto editpage_fail;
7385 
7386   pPg->nCell = nNew;
7387   pPg->nOverflow = 0;
7388 
7389   put2byte(&aData[hdr+3], pPg->nCell);
7390   put2byte(&aData[hdr+5], pData - aData);
7391 
7392 #ifdef SQLITE_DEBUG
7393   for(i=0; i<nNew && !CORRUPT_DB; i++){
7394     u8 *pCell = pCArray->apCell[i+iNew];
7395     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7396     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7397       pCell = &pTmp[pCell - aData];
7398     }
7399     assert( 0==memcmp(pCell, &aData[iOff],
7400             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7401   }
7402 #endif
7403 
7404   return SQLITE_OK;
7405  editpage_fail:
7406   /* Unable to edit this page. Rebuild it from scratch instead. */
7407   populateCellCache(pCArray, iNew, nNew);
7408   return rebuildPage(pCArray, iNew, nNew, pPg);
7409 }
7410 
7411 
7412 #ifndef SQLITE_OMIT_QUICKBALANCE
7413 /*
7414 ** This version of balance() handles the common special case where
7415 ** a new entry is being inserted on the extreme right-end of the
7416 ** tree, in other words, when the new entry will become the largest
7417 ** entry in the tree.
7418 **
7419 ** Instead of trying to balance the 3 right-most leaf pages, just add
7420 ** a new page to the right-hand side and put the one new entry in
7421 ** that page.  This leaves the right side of the tree somewhat
7422 ** unbalanced.  But odds are that we will be inserting new entries
7423 ** at the end soon afterwards so the nearly empty page will quickly
7424 ** fill up.  On average.
7425 **
7426 ** pPage is the leaf page which is the right-most page in the tree.
7427 ** pParent is its parent.  pPage must have a single overflow entry
7428 ** which is also the right-most entry on the page.
7429 **
7430 ** The pSpace buffer is used to store a temporary copy of the divider
7431 ** cell that will be inserted into pParent. Such a cell consists of a 4
7432 ** byte page number followed by a variable length integer. In other
7433 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7434 ** least 13 bytes in size.
7435 */
7436 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7437   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7438   MemPage *pNew;                       /* Newly allocated page */
7439   int rc;                              /* Return Code */
7440   Pgno pgnoNew;                        /* Page number of pNew */
7441 
7442   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7443   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7444   assert( pPage->nOverflow==1 );
7445 
7446   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
7447   assert( pPage->nFree>=0 );
7448   assert( pParent->nFree>=0 );
7449 
7450   /* Allocate a new page. This page will become the right-sibling of
7451   ** pPage. Make the parent page writable, so that the new divider cell
7452   ** may be inserted. If both these operations are successful, proceed.
7453   */
7454   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7455 
7456   if( rc==SQLITE_OK ){
7457 
7458     u8 *pOut = &pSpace[4];
7459     u8 *pCell = pPage->apOvfl[0];
7460     u16 szCell = pPage->xCellSize(pPage, pCell);
7461     u8 *pStop;
7462     CellArray b;
7463 
7464     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7465     assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7466     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7467     b.nCell = 1;
7468     b.pRef = pPage;
7469     b.apCell = &pCell;
7470     b.szCell = &szCell;
7471     b.apEnd[0] = pPage->aDataEnd;
7472     b.ixNx[0] = 2;
7473     rc = rebuildPage(&b, 0, 1, pNew);
7474     if( NEVER(rc) ){
7475       releasePage(pNew);
7476       return rc;
7477     }
7478     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7479 
7480     /* If this is an auto-vacuum database, update the pointer map
7481     ** with entries for the new page, and any pointer from the
7482     ** cell on the page to an overflow page. If either of these
7483     ** operations fails, the return code is set, but the contents
7484     ** of the parent page are still manipulated by thh code below.
7485     ** That is Ok, at this point the parent page is guaranteed to
7486     ** be marked as dirty. Returning an error code will cause a
7487     ** rollback, undoing any changes made to the parent page.
7488     */
7489     if( ISAUTOVACUUM ){
7490       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7491       if( szCell>pNew->minLocal ){
7492         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7493       }
7494     }
7495 
7496     /* Create a divider cell to insert into pParent. The divider cell
7497     ** consists of a 4-byte page number (the page number of pPage) and
7498     ** a variable length key value (which must be the same value as the
7499     ** largest key on pPage).
7500     **
7501     ** To find the largest key value on pPage, first find the right-most
7502     ** cell on pPage. The first two fields of this cell are the
7503     ** record-length (a variable length integer at most 32-bits in size)
7504     ** and the key value (a variable length integer, may have any value).
7505     ** The first of the while(...) loops below skips over the record-length
7506     ** field. The second while(...) loop copies the key value from the
7507     ** cell on pPage into the pSpace buffer.
7508     */
7509     pCell = findCell(pPage, pPage->nCell-1);
7510     pStop = &pCell[9];
7511     while( (*(pCell++)&0x80) && pCell<pStop );
7512     pStop = &pCell[9];
7513     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7514 
7515     /* Insert the new divider cell into pParent. */
7516     if( rc==SQLITE_OK ){
7517       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7518                    0, pPage->pgno, &rc);
7519     }
7520 
7521     /* Set the right-child pointer of pParent to point to the new page. */
7522     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7523 
7524     /* Release the reference to the new page. */
7525     releasePage(pNew);
7526   }
7527 
7528   return rc;
7529 }
7530 #endif /* SQLITE_OMIT_QUICKBALANCE */
7531 
7532 #if 0
7533 /*
7534 ** This function does not contribute anything to the operation of SQLite.
7535 ** it is sometimes activated temporarily while debugging code responsible
7536 ** for setting pointer-map entries.
7537 */
7538 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7539   int i, j;
7540   for(i=0; i<nPage; i++){
7541     Pgno n;
7542     u8 e;
7543     MemPage *pPage = apPage[i];
7544     BtShared *pBt = pPage->pBt;
7545     assert( pPage->isInit );
7546 
7547     for(j=0; j<pPage->nCell; j++){
7548       CellInfo info;
7549       u8 *z;
7550 
7551       z = findCell(pPage, j);
7552       pPage->xParseCell(pPage, z, &info);
7553       if( info.nLocal<info.nPayload ){
7554         Pgno ovfl = get4byte(&z[info.nSize-4]);
7555         ptrmapGet(pBt, ovfl, &e, &n);
7556         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7557       }
7558       if( !pPage->leaf ){
7559         Pgno child = get4byte(z);
7560         ptrmapGet(pBt, child, &e, &n);
7561         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7562       }
7563     }
7564     if( !pPage->leaf ){
7565       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7566       ptrmapGet(pBt, child, &e, &n);
7567       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7568     }
7569   }
7570   return 1;
7571 }
7572 #endif
7573 
7574 /*
7575 ** This function is used to copy the contents of the b-tree node stored
7576 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7577 ** the pointer-map entries for each child page are updated so that the
7578 ** parent page stored in the pointer map is page pTo. If pFrom contained
7579 ** any cells with overflow page pointers, then the corresponding pointer
7580 ** map entries are also updated so that the parent page is page pTo.
7581 **
7582 ** If pFrom is currently carrying any overflow cells (entries in the
7583 ** MemPage.apOvfl[] array), they are not copied to pTo.
7584 **
7585 ** Before returning, page pTo is reinitialized using btreeInitPage().
7586 **
7587 ** The performance of this function is not critical. It is only used by
7588 ** the balance_shallower() and balance_deeper() procedures, neither of
7589 ** which are called often under normal circumstances.
7590 */
7591 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7592   if( (*pRC)==SQLITE_OK ){
7593     BtShared * const pBt = pFrom->pBt;
7594     u8 * const aFrom = pFrom->aData;
7595     u8 * const aTo = pTo->aData;
7596     int const iFromHdr = pFrom->hdrOffset;
7597     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7598     int rc;
7599     int iData;
7600 
7601 
7602     assert( pFrom->isInit );
7603     assert( pFrom->nFree>=iToHdr );
7604     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7605 
7606     /* Copy the b-tree node content from page pFrom to page pTo. */
7607     iData = get2byte(&aFrom[iFromHdr+5]);
7608     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7609     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7610 
7611     /* Reinitialize page pTo so that the contents of the MemPage structure
7612     ** match the new data. The initialization of pTo can actually fail under
7613     ** fairly obscure circumstances, even though it is a copy of initialized
7614     ** page pFrom.
7615     */
7616     pTo->isInit = 0;
7617     rc = btreeInitPage(pTo);
7618     if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7619     if( rc!=SQLITE_OK ){
7620       *pRC = rc;
7621       return;
7622     }
7623 
7624     /* If this is an auto-vacuum database, update the pointer-map entries
7625     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7626     */
7627     if( ISAUTOVACUUM ){
7628       *pRC = setChildPtrmaps(pTo);
7629     }
7630   }
7631 }
7632 
7633 /*
7634 ** This routine redistributes cells on the iParentIdx'th child of pParent
7635 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7636 ** same amount of free space. Usually a single sibling on either side of the
7637 ** page are used in the balancing, though both siblings might come from one
7638 ** side if the page is the first or last child of its parent. If the page
7639 ** has fewer than 2 siblings (something which can only happen if the page
7640 ** is a root page or a child of a root page) then all available siblings
7641 ** participate in the balancing.
7642 **
7643 ** The number of siblings of the page might be increased or decreased by
7644 ** one or two in an effort to keep pages nearly full but not over full.
7645 **
7646 ** Note that when this routine is called, some of the cells on the page
7647 ** might not actually be stored in MemPage.aData[]. This can happen
7648 ** if the page is overfull. This routine ensures that all cells allocated
7649 ** to the page and its siblings fit into MemPage.aData[] before returning.
7650 **
7651 ** In the course of balancing the page and its siblings, cells may be
7652 ** inserted into or removed from the parent page (pParent). Doing so
7653 ** may cause the parent page to become overfull or underfull. If this
7654 ** happens, it is the responsibility of the caller to invoke the correct
7655 ** balancing routine to fix this problem (see the balance() routine).
7656 **
7657 ** If this routine fails for any reason, it might leave the database
7658 ** in a corrupted state. So if this routine fails, the database should
7659 ** be rolled back.
7660 **
7661 ** The third argument to this function, aOvflSpace, is a pointer to a
7662 ** buffer big enough to hold one page. If while inserting cells into the parent
7663 ** page (pParent) the parent page becomes overfull, this buffer is
7664 ** used to store the parent's overflow cells. Because this function inserts
7665 ** a maximum of four divider cells into the parent page, and the maximum
7666 ** size of a cell stored within an internal node is always less than 1/4
7667 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7668 ** enough for all overflow cells.
7669 **
7670 ** If aOvflSpace is set to a null pointer, this function returns
7671 ** SQLITE_NOMEM.
7672 */
7673 static int balance_nonroot(
7674   MemPage *pParent,               /* Parent page of siblings being balanced */
7675   int iParentIdx,                 /* Index of "the page" in pParent */
7676   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7677   int isRoot,                     /* True if pParent is a root-page */
7678   int bBulk                       /* True if this call is part of a bulk load */
7679 ){
7680   BtShared *pBt;               /* The whole database */
7681   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7682   int nNew = 0;                /* Number of pages in apNew[] */
7683   int nOld;                    /* Number of pages in apOld[] */
7684   int i, j, k;                 /* Loop counters */
7685   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7686   int rc = SQLITE_OK;          /* The return code */
7687   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7688   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7689   int usableSpace;             /* Bytes in pPage beyond the header */
7690   int pageFlags;               /* Value of pPage->aData[0] */
7691   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7692   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7693   int szScratch;               /* Size of scratch memory requested */
7694   MemPage *apOld[NB];          /* pPage and up to two siblings */
7695   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7696   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7697   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7698   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7699   int cntOld[NB+2];            /* Old index in b.apCell[] */
7700   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7701   u8 *aSpace1;                 /* Space for copies of dividers cells */
7702   Pgno pgno;                   /* Temp var to store a page number in */
7703   u8 abDone[NB+2];             /* True after i'th new page is populated */
7704   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7705   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7706   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7707   CellArray b;                 /* Parsed information on cells being balanced */
7708 
7709   memset(abDone, 0, sizeof(abDone));
7710   memset(&b, 0, sizeof(b));
7711   pBt = pParent->pBt;
7712   assert( sqlite3_mutex_held(pBt->mutex) );
7713   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7714 
7715   /* At this point pParent may have at most one overflow cell. And if
7716   ** this overflow cell is present, it must be the cell with
7717   ** index iParentIdx. This scenario comes about when this function
7718   ** is called (indirectly) from sqlite3BtreeDelete().
7719   */
7720   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7721   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7722 
7723   if( !aOvflSpace ){
7724     return SQLITE_NOMEM_BKPT;
7725   }
7726   assert( pParent->nFree>=0 );
7727 
7728   /* Find the sibling pages to balance. Also locate the cells in pParent
7729   ** that divide the siblings. An attempt is made to find NN siblings on
7730   ** either side of pPage. More siblings are taken from one side, however,
7731   ** if there are fewer than NN siblings on the other side. If pParent
7732   ** has NB or fewer children then all children of pParent are taken.
7733   **
7734   ** This loop also drops the divider cells from the parent page. This
7735   ** way, the remainder of the function does not have to deal with any
7736   ** overflow cells in the parent page, since if any existed they will
7737   ** have already been removed.
7738   */
7739   i = pParent->nOverflow + pParent->nCell;
7740   if( i<2 ){
7741     nxDiv = 0;
7742   }else{
7743     assert( bBulk==0 || bBulk==1 );
7744     if( iParentIdx==0 ){
7745       nxDiv = 0;
7746     }else if( iParentIdx==i ){
7747       nxDiv = i-2+bBulk;
7748     }else{
7749       nxDiv = iParentIdx-1;
7750     }
7751     i = 2-bBulk;
7752   }
7753   nOld = i+1;
7754   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7755     pRight = &pParent->aData[pParent->hdrOffset+8];
7756   }else{
7757     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7758   }
7759   pgno = get4byte(pRight);
7760   while( 1 ){
7761     if( rc==SQLITE_OK ){
7762       rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7763     }
7764     if( rc ){
7765       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7766       goto balance_cleanup;
7767     }
7768     if( apOld[i]->nFree<0 ){
7769       rc = btreeComputeFreeSpace(apOld[i]);
7770       if( rc ){
7771         memset(apOld, 0, (i)*sizeof(MemPage*));
7772         goto balance_cleanup;
7773       }
7774     }
7775     nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
7776     if( (i--)==0 ) break;
7777 
7778     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7779       apDiv[i] = pParent->apOvfl[0];
7780       pgno = get4byte(apDiv[i]);
7781       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7782       pParent->nOverflow = 0;
7783     }else{
7784       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7785       pgno = get4byte(apDiv[i]);
7786       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7787 
7788       /* Drop the cell from the parent page. apDiv[i] still points to
7789       ** the cell within the parent, even though it has been dropped.
7790       ** This is safe because dropping a cell only overwrites the first
7791       ** four bytes of it, and this function does not need the first
7792       ** four bytes of the divider cell. So the pointer is safe to use
7793       ** later on.
7794       **
7795       ** But not if we are in secure-delete mode. In secure-delete mode,
7796       ** the dropCell() routine will overwrite the entire cell with zeroes.
7797       ** In this case, temporarily copy the cell into the aOvflSpace[]
7798       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7799       ** is allocated.  */
7800       if( pBt->btsFlags & BTS_FAST_SECURE ){
7801         int iOff;
7802 
7803         /* If the following if() condition is not true, the db is corrupted.
7804         ** The call to dropCell() below will detect this.  */
7805         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7806         if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7807           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7808           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7809         }
7810       }
7811       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7812     }
7813   }
7814 
7815   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7816   ** alignment */
7817   nMaxCells = (nMaxCells + 3)&~3;
7818 
7819   /*
7820   ** Allocate space for memory structures
7821   */
7822   szScratch =
7823        nMaxCells*sizeof(u8*)                       /* b.apCell */
7824      + nMaxCells*sizeof(u16)                       /* b.szCell */
7825      + pBt->pageSize;                              /* aSpace1 */
7826 
7827   assert( szScratch<=7*(int)pBt->pageSize );
7828   b.apCell = sqlite3StackAllocRaw(0, szScratch );
7829   if( b.apCell==0 ){
7830     rc = SQLITE_NOMEM_BKPT;
7831     goto balance_cleanup;
7832   }
7833   b.szCell = (u16*)&b.apCell[nMaxCells];
7834   aSpace1 = (u8*)&b.szCell[nMaxCells];
7835   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7836 
7837   /*
7838   ** Load pointers to all cells on sibling pages and the divider cells
7839   ** into the local b.apCell[] array.  Make copies of the divider cells
7840   ** into space obtained from aSpace1[]. The divider cells have already
7841   ** been removed from pParent.
7842   **
7843   ** If the siblings are on leaf pages, then the child pointers of the
7844   ** divider cells are stripped from the cells before they are copied
7845   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7846   ** child pointers.  If siblings are not leaves, then all cell in
7847   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7848   ** are alike.
7849   **
7850   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7851   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7852   */
7853   b.pRef = apOld[0];
7854   leafCorrection = b.pRef->leaf*4;
7855   leafData = b.pRef->intKeyLeaf;
7856   for(i=0; i<nOld; i++){
7857     MemPage *pOld = apOld[i];
7858     int limit = pOld->nCell;
7859     u8 *aData = pOld->aData;
7860     u16 maskPage = pOld->maskPage;
7861     u8 *piCell = aData + pOld->cellOffset;
7862     u8 *piEnd;
7863     VVA_ONLY( int nCellAtStart = b.nCell; )
7864 
7865     /* Verify that all sibling pages are of the same "type" (table-leaf,
7866     ** table-interior, index-leaf, or index-interior).
7867     */
7868     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7869       rc = SQLITE_CORRUPT_BKPT;
7870       goto balance_cleanup;
7871     }
7872 
7873     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7874     ** contains overflow cells, include them in the b.apCell[] array
7875     ** in the correct spot.
7876     **
7877     ** Note that when there are multiple overflow cells, it is always the
7878     ** case that they are sequential and adjacent.  This invariant arises
7879     ** because multiple overflows can only occurs when inserting divider
7880     ** cells into a parent on a prior balance, and divider cells are always
7881     ** adjacent and are inserted in order.  There is an assert() tagged
7882     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7883     ** invariant.
7884     **
7885     ** This must be done in advance.  Once the balance starts, the cell
7886     ** offset section of the btree page will be overwritten and we will no
7887     ** long be able to find the cells if a pointer to each cell is not saved
7888     ** first.
7889     */
7890     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7891     if( pOld->nOverflow>0 ){
7892       if( NEVER(limit<pOld->aiOvfl[0]) ){
7893         rc = SQLITE_CORRUPT_BKPT;
7894         goto balance_cleanup;
7895       }
7896       limit = pOld->aiOvfl[0];
7897       for(j=0; j<limit; j++){
7898         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7899         piCell += 2;
7900         b.nCell++;
7901       }
7902       for(k=0; k<pOld->nOverflow; k++){
7903         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7904         b.apCell[b.nCell] = pOld->apOvfl[k];
7905         b.nCell++;
7906       }
7907     }
7908     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7909     while( piCell<piEnd ){
7910       assert( b.nCell<nMaxCells );
7911       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7912       piCell += 2;
7913       b.nCell++;
7914     }
7915     assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7916 
7917     cntOld[i] = b.nCell;
7918     if( i<nOld-1 && !leafData){
7919       u16 sz = (u16)szNew[i];
7920       u8 *pTemp;
7921       assert( b.nCell<nMaxCells );
7922       b.szCell[b.nCell] = sz;
7923       pTemp = &aSpace1[iSpace1];
7924       iSpace1 += sz;
7925       assert( sz<=pBt->maxLocal+23 );
7926       assert( iSpace1 <= (int)pBt->pageSize );
7927       memcpy(pTemp, apDiv[i], sz);
7928       b.apCell[b.nCell] = pTemp+leafCorrection;
7929       assert( leafCorrection==0 || leafCorrection==4 );
7930       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7931       if( !pOld->leaf ){
7932         assert( leafCorrection==0 );
7933         assert( pOld->hdrOffset==0 || CORRUPT_DB );
7934         /* The right pointer of the child page pOld becomes the left
7935         ** pointer of the divider cell */
7936         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7937       }else{
7938         assert( leafCorrection==4 );
7939         while( b.szCell[b.nCell]<4 ){
7940           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7941           ** does exist, pad it with 0x00 bytes. */
7942           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7943           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7944           aSpace1[iSpace1++] = 0x00;
7945           b.szCell[b.nCell]++;
7946         }
7947       }
7948       b.nCell++;
7949     }
7950   }
7951 
7952   /*
7953   ** Figure out the number of pages needed to hold all b.nCell cells.
7954   ** Store this number in "k".  Also compute szNew[] which is the total
7955   ** size of all cells on the i-th page and cntNew[] which is the index
7956   ** in b.apCell[] of the cell that divides page i from page i+1.
7957   ** cntNew[k] should equal b.nCell.
7958   **
7959   ** Values computed by this block:
7960   **
7961   **           k: The total number of sibling pages
7962   **    szNew[i]: Spaced used on the i-th sibling page.
7963   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7964   **              the right of the i-th sibling page.
7965   ** usableSpace: Number of bytes of space available on each sibling.
7966   **
7967   */
7968   usableSpace = pBt->usableSize - 12 + leafCorrection;
7969   for(i=k=0; i<nOld; i++, k++){
7970     MemPage *p = apOld[i];
7971     b.apEnd[k] = p->aDataEnd;
7972     b.ixNx[k] = cntOld[i];
7973     if( k && b.ixNx[k]==b.ixNx[k-1] ){
7974       k--;  /* Omit b.ixNx[] entry for child pages with no cells */
7975     }
7976     if( !leafData ){
7977       k++;
7978       b.apEnd[k] = pParent->aDataEnd;
7979       b.ixNx[k] = cntOld[i]+1;
7980     }
7981     assert( p->nFree>=0 );
7982     szNew[i] = usableSpace - p->nFree;
7983     for(j=0; j<p->nOverflow; j++){
7984       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7985     }
7986     cntNew[i] = cntOld[i];
7987   }
7988   k = nOld;
7989   for(i=0; i<k; i++){
7990     int sz;
7991     while( szNew[i]>usableSpace ){
7992       if( i+1>=k ){
7993         k = i+2;
7994         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7995         szNew[k-1] = 0;
7996         cntNew[k-1] = b.nCell;
7997       }
7998       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7999       szNew[i] -= sz;
8000       if( !leafData ){
8001         if( cntNew[i]<b.nCell ){
8002           sz = 2 + cachedCellSize(&b, cntNew[i]);
8003         }else{
8004           sz = 0;
8005         }
8006       }
8007       szNew[i+1] += sz;
8008       cntNew[i]--;
8009     }
8010     while( cntNew[i]<b.nCell ){
8011       sz = 2 + cachedCellSize(&b, cntNew[i]);
8012       if( szNew[i]+sz>usableSpace ) break;
8013       szNew[i] += sz;
8014       cntNew[i]++;
8015       if( !leafData ){
8016         if( cntNew[i]<b.nCell ){
8017           sz = 2 + cachedCellSize(&b, cntNew[i]);
8018         }else{
8019           sz = 0;
8020         }
8021       }
8022       szNew[i+1] -= sz;
8023     }
8024     if( cntNew[i]>=b.nCell ){
8025       k = i+1;
8026     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8027       rc = SQLITE_CORRUPT_BKPT;
8028       goto balance_cleanup;
8029     }
8030   }
8031 
8032   /*
8033   ** The packing computed by the previous block is biased toward the siblings
8034   ** on the left side (siblings with smaller keys). The left siblings are
8035   ** always nearly full, while the right-most sibling might be nearly empty.
8036   ** The next block of code attempts to adjust the packing of siblings to
8037   ** get a better balance.
8038   **
8039   ** This adjustment is more than an optimization.  The packing above might
8040   ** be so out of balance as to be illegal.  For example, the right-most
8041   ** sibling might be completely empty.  This adjustment is not optional.
8042   */
8043   for(i=k-1; i>0; i--){
8044     int szRight = szNew[i];  /* Size of sibling on the right */
8045     int szLeft = szNew[i-1]; /* Size of sibling on the left */
8046     int r;              /* Index of right-most cell in left sibling */
8047     int d;              /* Index of first cell to the left of right sibling */
8048 
8049     r = cntNew[i-1] - 1;
8050     d = r + 1 - leafData;
8051     (void)cachedCellSize(&b, d);
8052     do{
8053       assert( d<nMaxCells );
8054       assert( r<nMaxCells );
8055       (void)cachedCellSize(&b, r);
8056       if( szRight!=0
8057        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
8058         break;
8059       }
8060       szRight += b.szCell[d] + 2;
8061       szLeft -= b.szCell[r] + 2;
8062       cntNew[i-1] = r;
8063       r--;
8064       d--;
8065     }while( r>=0 );
8066     szNew[i] = szRight;
8067     szNew[i-1] = szLeft;
8068     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8069       rc = SQLITE_CORRUPT_BKPT;
8070       goto balance_cleanup;
8071     }
8072   }
8073 
8074   /* Sanity check:  For a non-corrupt database file one of the follwing
8075   ** must be true:
8076   **    (1) We found one or more cells (cntNew[0])>0), or
8077   **    (2) pPage is a virtual root page.  A virtual root page is when
8078   **        the real root page is page 1 and we are the only child of
8079   **        that page.
8080   */
8081   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8082   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
8083     apOld[0]->pgno, apOld[0]->nCell,
8084     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8085     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8086   ));
8087 
8088   /*
8089   ** Allocate k new pages.  Reuse old pages where possible.
8090   */
8091   pageFlags = apOld[0]->aData[0];
8092   for(i=0; i<k; i++){
8093     MemPage *pNew;
8094     if( i<nOld ){
8095       pNew = apNew[i] = apOld[i];
8096       apOld[i] = 0;
8097       rc = sqlite3PagerWrite(pNew->pDbPage);
8098       nNew++;
8099       if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8100        && rc==SQLITE_OK
8101       ){
8102         rc = SQLITE_CORRUPT_BKPT;
8103       }
8104       if( rc ) goto balance_cleanup;
8105     }else{
8106       assert( i>0 );
8107       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8108       if( rc ) goto balance_cleanup;
8109       zeroPage(pNew, pageFlags);
8110       apNew[i] = pNew;
8111       nNew++;
8112       cntOld[i] = b.nCell;
8113 
8114       /* Set the pointer-map entry for the new sibling page. */
8115       if( ISAUTOVACUUM ){
8116         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8117         if( rc!=SQLITE_OK ){
8118           goto balance_cleanup;
8119         }
8120       }
8121     }
8122   }
8123 
8124   /*
8125   ** Reassign page numbers so that the new pages are in ascending order.
8126   ** This helps to keep entries in the disk file in order so that a scan
8127   ** of the table is closer to a linear scan through the file. That in turn
8128   ** helps the operating system to deliver pages from the disk more rapidly.
8129   **
8130   ** An O(n^2) insertion sort algorithm is used, but since n is never more
8131   ** than (NB+2) (a small constant), that should not be a problem.
8132   **
8133   ** When NB==3, this one optimization makes the database about 25% faster
8134   ** for large insertions and deletions.
8135   */
8136   for(i=0; i<nNew; i++){
8137     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8138     aPgFlags[i] = apNew[i]->pDbPage->flags;
8139     for(j=0; j<i; j++){
8140       if( NEVER(aPgno[j]==aPgno[i]) ){
8141         /* This branch is taken if the set of sibling pages somehow contains
8142         ** duplicate entries. This can happen if the database is corrupt.
8143         ** It would be simpler to detect this as part of the loop below, but
8144         ** we do the detection here in order to avoid populating the pager
8145         ** cache with two separate objects associated with the same
8146         ** page number.  */
8147         assert( CORRUPT_DB );
8148         rc = SQLITE_CORRUPT_BKPT;
8149         goto balance_cleanup;
8150       }
8151     }
8152   }
8153   for(i=0; i<nNew; i++){
8154     int iBest = 0;                /* aPgno[] index of page number to use */
8155     for(j=1; j<nNew; j++){
8156       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8157     }
8158     pgno = aPgOrder[iBest];
8159     aPgOrder[iBest] = 0xffffffff;
8160     if( iBest!=i ){
8161       if( iBest>i ){
8162         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8163       }
8164       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8165       apNew[i]->pgno = pgno;
8166     }
8167   }
8168 
8169   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8170          "%d(%d nc=%d) %d(%d nc=%d)\n",
8171     apNew[0]->pgno, szNew[0], cntNew[0],
8172     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8173     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8174     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8175     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8176     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8177     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8178     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8179     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8180   ));
8181 
8182   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8183   assert( nNew>=1 && nNew<=ArraySize(apNew) );
8184   assert( apNew[nNew-1]!=0 );
8185   put4byte(pRight, apNew[nNew-1]->pgno);
8186 
8187   /* If the sibling pages are not leaves, ensure that the right-child pointer
8188   ** of the right-most new sibling page is set to the value that was
8189   ** originally in the same field of the right-most old sibling page. */
8190   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8191     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8192     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8193   }
8194 
8195   /* Make any required updates to pointer map entries associated with
8196   ** cells stored on sibling pages following the balance operation. Pointer
8197   ** map entries associated with divider cells are set by the insertCell()
8198   ** routine. The associated pointer map entries are:
8199   **
8200   **   a) if the cell contains a reference to an overflow chain, the
8201   **      entry associated with the first page in the overflow chain, and
8202   **
8203   **   b) if the sibling pages are not leaves, the child page associated
8204   **      with the cell.
8205   **
8206   ** If the sibling pages are not leaves, then the pointer map entry
8207   ** associated with the right-child of each sibling may also need to be
8208   ** updated. This happens below, after the sibling pages have been
8209   ** populated, not here.
8210   */
8211   if( ISAUTOVACUUM ){
8212     MemPage *pOld;
8213     MemPage *pNew = pOld = apNew[0];
8214     int cntOldNext = pNew->nCell + pNew->nOverflow;
8215     int iNew = 0;
8216     int iOld = 0;
8217 
8218     for(i=0; i<b.nCell; i++){
8219       u8 *pCell = b.apCell[i];
8220       while( i==cntOldNext ){
8221         iOld++;
8222         assert( iOld<nNew || iOld<nOld );
8223         assert( iOld>=0 && iOld<NB );
8224         pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8225         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8226       }
8227       if( i==cntNew[iNew] ){
8228         pNew = apNew[++iNew];
8229         if( !leafData ) continue;
8230       }
8231 
8232       /* Cell pCell is destined for new sibling page pNew. Originally, it
8233       ** was either part of sibling page iOld (possibly an overflow cell),
8234       ** or else the divider cell to the left of sibling page iOld. So,
8235       ** if sibling page iOld had the same page number as pNew, and if
8236       ** pCell really was a part of sibling page iOld (not a divider or
8237       ** overflow cell), we can skip updating the pointer map entries.  */
8238       if( iOld>=nNew
8239        || pNew->pgno!=aPgno[iOld]
8240        || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8241       ){
8242         if( !leafCorrection ){
8243           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8244         }
8245         if( cachedCellSize(&b,i)>pNew->minLocal ){
8246           ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8247         }
8248         if( rc ) goto balance_cleanup;
8249       }
8250     }
8251   }
8252 
8253   /* Insert new divider cells into pParent. */
8254   for(i=0; i<nNew-1; i++){
8255     u8 *pCell;
8256     u8 *pTemp;
8257     int sz;
8258     u8 *pSrcEnd;
8259     MemPage *pNew = apNew[i];
8260     j = cntNew[i];
8261 
8262     assert( j<nMaxCells );
8263     assert( b.apCell[j]!=0 );
8264     pCell = b.apCell[j];
8265     sz = b.szCell[j] + leafCorrection;
8266     pTemp = &aOvflSpace[iOvflSpace];
8267     if( !pNew->leaf ){
8268       memcpy(&pNew->aData[8], pCell, 4);
8269     }else if( leafData ){
8270       /* If the tree is a leaf-data tree, and the siblings are leaves,
8271       ** then there is no divider cell in b.apCell[]. Instead, the divider
8272       ** cell consists of the integer key for the right-most cell of
8273       ** the sibling-page assembled above only.
8274       */
8275       CellInfo info;
8276       j--;
8277       pNew->xParseCell(pNew, b.apCell[j], &info);
8278       pCell = pTemp;
8279       sz = 4 + putVarint(&pCell[4], info.nKey);
8280       pTemp = 0;
8281     }else{
8282       pCell -= 4;
8283       /* Obscure case for non-leaf-data trees: If the cell at pCell was
8284       ** previously stored on a leaf node, and its reported size was 4
8285       ** bytes, then it may actually be smaller than this
8286       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8287       ** any cell). But it is important to pass the correct size to
8288       ** insertCell(), so reparse the cell now.
8289       **
8290       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8291       ** and WITHOUT ROWID tables with exactly one column which is the
8292       ** primary key.
8293       */
8294       if( b.szCell[j]==4 ){
8295         assert(leafCorrection==4);
8296         sz = pParent->xCellSize(pParent, pCell);
8297       }
8298     }
8299     iOvflSpace += sz;
8300     assert( sz<=pBt->maxLocal+23 );
8301     assert( iOvflSpace <= (int)pBt->pageSize );
8302     for(k=0; b.ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
8303     pSrcEnd = b.apEnd[k];
8304     if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8305       rc = SQLITE_CORRUPT_BKPT;
8306       goto balance_cleanup;
8307     }
8308     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8309     if( rc!=SQLITE_OK ) goto balance_cleanup;
8310     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8311   }
8312 
8313   /* Now update the actual sibling pages. The order in which they are updated
8314   ** is important, as this code needs to avoid disrupting any page from which
8315   ** cells may still to be read. In practice, this means:
8316   **
8317   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8318   **      then it is not safe to update page apNew[iPg] until after
8319   **      the left-hand sibling apNew[iPg-1] has been updated.
8320   **
8321   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8322   **      then it is not safe to update page apNew[iPg] until after
8323   **      the right-hand sibling apNew[iPg+1] has been updated.
8324   **
8325   ** If neither of the above apply, the page is safe to update.
8326   **
8327   ** The iPg value in the following loop starts at nNew-1 goes down
8328   ** to 0, then back up to nNew-1 again, thus making two passes over
8329   ** the pages.  On the initial downward pass, only condition (1) above
8330   ** needs to be tested because (2) will always be true from the previous
8331   ** step.  On the upward pass, both conditions are always true, so the
8332   ** upwards pass simply processes pages that were missed on the downward
8333   ** pass.
8334   */
8335   for(i=1-nNew; i<nNew; i++){
8336     int iPg = i<0 ? -i : i;
8337     assert( iPg>=0 && iPg<nNew );
8338     if( abDone[iPg] ) continue;         /* Skip pages already processed */
8339     if( i>=0                            /* On the upwards pass, or... */
8340      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
8341     ){
8342       int iNew;
8343       int iOld;
8344       int nNewCell;
8345 
8346       /* Verify condition (1):  If cells are moving left, update iPg
8347       ** only after iPg-1 has already been updated. */
8348       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8349 
8350       /* Verify condition (2):  If cells are moving right, update iPg
8351       ** only after iPg+1 has already been updated. */
8352       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8353 
8354       if( iPg==0 ){
8355         iNew = iOld = 0;
8356         nNewCell = cntNew[0];
8357       }else{
8358         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8359         iNew = cntNew[iPg-1] + !leafData;
8360         nNewCell = cntNew[iPg] - iNew;
8361       }
8362 
8363       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8364       if( rc ) goto balance_cleanup;
8365       abDone[iPg]++;
8366       apNew[iPg]->nFree = usableSpace-szNew[iPg];
8367       assert( apNew[iPg]->nOverflow==0 );
8368       assert( apNew[iPg]->nCell==nNewCell );
8369     }
8370   }
8371 
8372   /* All pages have been processed exactly once */
8373   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8374 
8375   assert( nOld>0 );
8376   assert( nNew>0 );
8377 
8378   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8379     /* The root page of the b-tree now contains no cells. The only sibling
8380     ** page is the right-child of the parent. Copy the contents of the
8381     ** child page into the parent, decreasing the overall height of the
8382     ** b-tree structure by one. This is described as the "balance-shallower"
8383     ** sub-algorithm in some documentation.
8384     **
8385     ** If this is an auto-vacuum database, the call to copyNodeContent()
8386     ** sets all pointer-map entries corresponding to database image pages
8387     ** for which the pointer is stored within the content being copied.
8388     **
8389     ** It is critical that the child page be defragmented before being
8390     ** copied into the parent, because if the parent is page 1 then it will
8391     ** by smaller than the child due to the database header, and so all the
8392     ** free space needs to be up front.
8393     */
8394     assert( nNew==1 || CORRUPT_DB );
8395     rc = defragmentPage(apNew[0], -1);
8396     testcase( rc!=SQLITE_OK );
8397     assert( apNew[0]->nFree ==
8398         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8399           - apNew[0]->nCell*2)
8400       || rc!=SQLITE_OK
8401     );
8402     copyNodeContent(apNew[0], pParent, &rc);
8403     freePage(apNew[0], &rc);
8404   }else if( ISAUTOVACUUM && !leafCorrection ){
8405     /* Fix the pointer map entries associated with the right-child of each
8406     ** sibling page. All other pointer map entries have already been taken
8407     ** care of.  */
8408     for(i=0; i<nNew; i++){
8409       u32 key = get4byte(&apNew[i]->aData[8]);
8410       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8411     }
8412   }
8413 
8414   assert( pParent->isInit );
8415   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8416           nOld, nNew, b.nCell));
8417 
8418   /* Free any old pages that were not reused as new pages.
8419   */
8420   for(i=nNew; i<nOld; i++){
8421     freePage(apOld[i], &rc);
8422   }
8423 
8424 #if 0
8425   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8426     /* The ptrmapCheckPages() contains assert() statements that verify that
8427     ** all pointer map pages are set correctly. This is helpful while
8428     ** debugging. This is usually disabled because a corrupt database may
8429     ** cause an assert() statement to fail.  */
8430     ptrmapCheckPages(apNew, nNew);
8431     ptrmapCheckPages(&pParent, 1);
8432   }
8433 #endif
8434 
8435   /*
8436   ** Cleanup before returning.
8437   */
8438 balance_cleanup:
8439   sqlite3StackFree(0, b.apCell);
8440   for(i=0; i<nOld; i++){
8441     releasePage(apOld[i]);
8442   }
8443   for(i=0; i<nNew; i++){
8444     releasePage(apNew[i]);
8445   }
8446 
8447   return rc;
8448 }
8449 
8450 
8451 /*
8452 ** This function is called when the root page of a b-tree structure is
8453 ** overfull (has one or more overflow pages).
8454 **
8455 ** A new child page is allocated and the contents of the current root
8456 ** page, including overflow cells, are copied into the child. The root
8457 ** page is then overwritten to make it an empty page with the right-child
8458 ** pointer pointing to the new page.
8459 **
8460 ** Before returning, all pointer-map entries corresponding to pages
8461 ** that the new child-page now contains pointers to are updated. The
8462 ** entry corresponding to the new right-child pointer of the root
8463 ** page is also updated.
8464 **
8465 ** If successful, *ppChild is set to contain a reference to the child
8466 ** page and SQLITE_OK is returned. In this case the caller is required
8467 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8468 ** an error code is returned and *ppChild is set to 0.
8469 */
8470 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8471   int rc;                        /* Return value from subprocedures */
8472   MemPage *pChild = 0;           /* Pointer to a new child page */
8473   Pgno pgnoChild = 0;            /* Page number of the new child page */
8474   BtShared *pBt = pRoot->pBt;    /* The BTree */
8475 
8476   assert( pRoot->nOverflow>0 );
8477   assert( sqlite3_mutex_held(pBt->mutex) );
8478 
8479   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8480   ** page that will become the new right-child of pPage. Copy the contents
8481   ** of the node stored on pRoot into the new child page.
8482   */
8483   rc = sqlite3PagerWrite(pRoot->pDbPage);
8484   if( rc==SQLITE_OK ){
8485     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8486     copyNodeContent(pRoot, pChild, &rc);
8487     if( ISAUTOVACUUM ){
8488       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8489     }
8490   }
8491   if( rc ){
8492     *ppChild = 0;
8493     releasePage(pChild);
8494     return rc;
8495   }
8496   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8497   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8498   assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8499 
8500   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8501 
8502   /* Copy the overflow cells from pRoot to pChild */
8503   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8504          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8505   memcpy(pChild->apOvfl, pRoot->apOvfl,
8506          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8507   pChild->nOverflow = pRoot->nOverflow;
8508 
8509   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8510   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8511   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8512 
8513   *ppChild = pChild;
8514   return SQLITE_OK;
8515 }
8516 
8517 /*
8518 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8519 ** on the same B-tree as pCur.
8520 **
8521 ** This can occur if a database is corrupt with two or more SQL tables
8522 ** pointing to the same b-tree.  If an insert occurs on one SQL table
8523 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8524 ** table linked to the same b-tree.  If the secondary insert causes a
8525 ** rebalance, that can change content out from under the cursor on the
8526 ** first SQL table, violating invariants on the first insert.
8527 */
8528 static int anotherValidCursor(BtCursor *pCur){
8529   BtCursor *pOther;
8530   for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8531     if( pOther!=pCur
8532      && pOther->eState==CURSOR_VALID
8533      && pOther->pPage==pCur->pPage
8534     ){
8535       return SQLITE_CORRUPT_BKPT;
8536     }
8537   }
8538   return SQLITE_OK;
8539 }
8540 
8541 /*
8542 ** The page that pCur currently points to has just been modified in
8543 ** some way. This function figures out if this modification means the
8544 ** tree needs to be balanced, and if so calls the appropriate balancing
8545 ** routine. Balancing routines are:
8546 **
8547 **   balance_quick()
8548 **   balance_deeper()
8549 **   balance_nonroot()
8550 */
8551 static int balance(BtCursor *pCur){
8552   int rc = SQLITE_OK;
8553   const int nMin = pCur->pBt->usableSize * 2 / 3;
8554   u8 aBalanceQuickSpace[13];
8555   u8 *pFree = 0;
8556 
8557   VVA_ONLY( int balance_quick_called = 0 );
8558   VVA_ONLY( int balance_deeper_called = 0 );
8559 
8560   do {
8561     int iPage;
8562     MemPage *pPage = pCur->pPage;
8563 
8564     if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8565     if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8566       break;
8567     }else if( (iPage = pCur->iPage)==0 ){
8568       if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8569         /* The root page of the b-tree is overfull. In this case call the
8570         ** balance_deeper() function to create a new child for the root-page
8571         ** and copy the current contents of the root-page to it. The
8572         ** next iteration of the do-loop will balance the child page.
8573         */
8574         assert( balance_deeper_called==0 );
8575         VVA_ONLY( balance_deeper_called++ );
8576         rc = balance_deeper(pPage, &pCur->apPage[1]);
8577         if( rc==SQLITE_OK ){
8578           pCur->iPage = 1;
8579           pCur->ix = 0;
8580           pCur->aiIdx[0] = 0;
8581           pCur->apPage[0] = pPage;
8582           pCur->pPage = pCur->apPage[1];
8583           assert( pCur->pPage->nOverflow );
8584         }
8585       }else{
8586         break;
8587       }
8588     }else{
8589       MemPage * const pParent = pCur->apPage[iPage-1];
8590       int const iIdx = pCur->aiIdx[iPage-1];
8591 
8592       rc = sqlite3PagerWrite(pParent->pDbPage);
8593       if( rc==SQLITE_OK && pParent->nFree<0 ){
8594         rc = btreeComputeFreeSpace(pParent);
8595       }
8596       if( rc==SQLITE_OK ){
8597 #ifndef SQLITE_OMIT_QUICKBALANCE
8598         if( pPage->intKeyLeaf
8599          && pPage->nOverflow==1
8600          && pPage->aiOvfl[0]==pPage->nCell
8601          && pParent->pgno!=1
8602          && pParent->nCell==iIdx
8603         ){
8604           /* Call balance_quick() to create a new sibling of pPage on which
8605           ** to store the overflow cell. balance_quick() inserts a new cell
8606           ** into pParent, which may cause pParent overflow. If this
8607           ** happens, the next iteration of the do-loop will balance pParent
8608           ** use either balance_nonroot() or balance_deeper(). Until this
8609           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8610           ** buffer.
8611           **
8612           ** The purpose of the following assert() is to check that only a
8613           ** single call to balance_quick() is made for each call to this
8614           ** function. If this were not verified, a subtle bug involving reuse
8615           ** of the aBalanceQuickSpace[] might sneak in.
8616           */
8617           assert( balance_quick_called==0 );
8618           VVA_ONLY( balance_quick_called++ );
8619           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8620         }else
8621 #endif
8622         {
8623           /* In this case, call balance_nonroot() to redistribute cells
8624           ** between pPage and up to 2 of its sibling pages. This involves
8625           ** modifying the contents of pParent, which may cause pParent to
8626           ** become overfull or underfull. The next iteration of the do-loop
8627           ** will balance the parent page to correct this.
8628           **
8629           ** If the parent page becomes overfull, the overflow cell or cells
8630           ** are stored in the pSpace buffer allocated immediately below.
8631           ** A subsequent iteration of the do-loop will deal with this by
8632           ** calling balance_nonroot() (balance_deeper() may be called first,
8633           ** but it doesn't deal with overflow cells - just moves them to a
8634           ** different page). Once this subsequent call to balance_nonroot()
8635           ** has completed, it is safe to release the pSpace buffer used by
8636           ** the previous call, as the overflow cell data will have been
8637           ** copied either into the body of a database page or into the new
8638           ** pSpace buffer passed to the latter call to balance_nonroot().
8639           */
8640           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8641           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8642                                pCur->hints&BTREE_BULKLOAD);
8643           if( pFree ){
8644             /* If pFree is not NULL, it points to the pSpace buffer used
8645             ** by a previous call to balance_nonroot(). Its contents are
8646             ** now stored either on real database pages or within the
8647             ** new pSpace buffer, so it may be safely freed here. */
8648             sqlite3PageFree(pFree);
8649           }
8650 
8651           /* The pSpace buffer will be freed after the next call to
8652           ** balance_nonroot(), or just before this function returns, whichever
8653           ** comes first. */
8654           pFree = pSpace;
8655         }
8656       }
8657 
8658       pPage->nOverflow = 0;
8659 
8660       /* The next iteration of the do-loop balances the parent page. */
8661       releasePage(pPage);
8662       pCur->iPage--;
8663       assert( pCur->iPage>=0 );
8664       pCur->pPage = pCur->apPage[pCur->iPage];
8665     }
8666   }while( rc==SQLITE_OK );
8667 
8668   if( pFree ){
8669     sqlite3PageFree(pFree);
8670   }
8671   return rc;
8672 }
8673 
8674 /* Overwrite content from pX into pDest.  Only do the write if the
8675 ** content is different from what is already there.
8676 */
8677 static int btreeOverwriteContent(
8678   MemPage *pPage,           /* MemPage on which writing will occur */
8679   u8 *pDest,                /* Pointer to the place to start writing */
8680   const BtreePayload *pX,   /* Source of data to write */
8681   int iOffset,              /* Offset of first byte to write */
8682   int iAmt                  /* Number of bytes to be written */
8683 ){
8684   int nData = pX->nData - iOffset;
8685   if( nData<=0 ){
8686     /* Overwritting with zeros */
8687     int i;
8688     for(i=0; i<iAmt && pDest[i]==0; i++){}
8689     if( i<iAmt ){
8690       int rc = sqlite3PagerWrite(pPage->pDbPage);
8691       if( rc ) return rc;
8692       memset(pDest + i, 0, iAmt - i);
8693     }
8694   }else{
8695     if( nData<iAmt ){
8696       /* Mixed read data and zeros at the end.  Make a recursive call
8697       ** to write the zeros then fall through to write the real data */
8698       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8699                                  iAmt-nData);
8700       if( rc ) return rc;
8701       iAmt = nData;
8702     }
8703     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8704       int rc = sqlite3PagerWrite(pPage->pDbPage);
8705       if( rc ) return rc;
8706       /* In a corrupt database, it is possible for the source and destination
8707       ** buffers to overlap.  This is harmless since the database is already
8708       ** corrupt but it does cause valgrind and ASAN warnings.  So use
8709       ** memmove(). */
8710       memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8711     }
8712   }
8713   return SQLITE_OK;
8714 }
8715 
8716 /*
8717 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8718 ** contained in pX.
8719 */
8720 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8721   int iOffset;                        /* Next byte of pX->pData to write */
8722   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8723   int rc;                             /* Return code */
8724   MemPage *pPage = pCur->pPage;       /* Page being written */
8725   BtShared *pBt;                      /* Btree */
8726   Pgno ovflPgno;                      /* Next overflow page to write */
8727   u32 ovflPageSize;                   /* Size to write on overflow page */
8728 
8729   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8730    || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8731   ){
8732     return SQLITE_CORRUPT_BKPT;
8733   }
8734   /* Overwrite the local portion first */
8735   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8736                              0, pCur->info.nLocal);
8737   if( rc ) return rc;
8738   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8739 
8740   /* Now overwrite the overflow pages */
8741   iOffset = pCur->info.nLocal;
8742   assert( nTotal>=0 );
8743   assert( iOffset>=0 );
8744   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8745   pBt = pPage->pBt;
8746   ovflPageSize = pBt->usableSize - 4;
8747   do{
8748     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8749     if( rc ) return rc;
8750     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
8751       rc = SQLITE_CORRUPT_BKPT;
8752     }else{
8753       if( iOffset+ovflPageSize<(u32)nTotal ){
8754         ovflPgno = get4byte(pPage->aData);
8755       }else{
8756         ovflPageSize = nTotal - iOffset;
8757       }
8758       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8759                                  iOffset, ovflPageSize);
8760     }
8761     sqlite3PagerUnref(pPage->pDbPage);
8762     if( rc ) return rc;
8763     iOffset += ovflPageSize;
8764   }while( iOffset<nTotal );
8765   return SQLITE_OK;
8766 }
8767 
8768 
8769 /*
8770 ** Insert a new record into the BTree.  The content of the new record
8771 ** is described by the pX object.  The pCur cursor is used only to
8772 ** define what table the record should be inserted into, and is left
8773 ** pointing at a random location.
8774 **
8775 ** For a table btree (used for rowid tables), only the pX.nKey value of
8776 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8777 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8778 ** hold the content of the row.
8779 **
8780 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8781 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8782 ** pX.pData,nData,nZero fields must be zero.
8783 **
8784 ** If the seekResult parameter is non-zero, then a successful call to
8785 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8786 ** been performed.  In other words, if seekResult!=0 then the cursor
8787 ** is currently pointing to a cell that will be adjacent to the cell
8788 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8789 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8790 ** that is larger than (pKey,nKey).
8791 **
8792 ** If seekResult==0, that means pCur is pointing at some unknown location.
8793 ** In that case, this routine must seek the cursor to the correct insertion
8794 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8795 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8796 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8797 ** to decode the key.
8798 */
8799 int sqlite3BtreeInsert(
8800   BtCursor *pCur,                /* Insert data into the table of this cursor */
8801   const BtreePayload *pX,        /* Content of the row to be inserted */
8802   int flags,                     /* True if this is likely an append */
8803   int seekResult                 /* Result of prior MovetoUnpacked() call */
8804 ){
8805   int rc;
8806   int loc = seekResult;          /* -1: before desired location  +1: after */
8807   int szNew = 0;
8808   int idx;
8809   MemPage *pPage;
8810   Btree *p = pCur->pBtree;
8811   BtShared *pBt = p->pBt;
8812   unsigned char *oldCell;
8813   unsigned char *newCell = 0;
8814 
8815   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8816   assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8817 
8818   if( pCur->eState==CURSOR_FAULT ){
8819     assert( pCur->skipNext!=SQLITE_OK );
8820     return pCur->skipNext;
8821   }
8822 
8823   assert( cursorOwnsBtShared(pCur) );
8824   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8825               && pBt->inTransaction==TRANS_WRITE
8826               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8827   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8828 
8829   /* Assert that the caller has been consistent. If this cursor was opened
8830   ** expecting an index b-tree, then the caller should be inserting blob
8831   ** keys with no associated data. If the cursor was opened expecting an
8832   ** intkey table, the caller should be inserting integer keys with a
8833   ** blob of associated data.  */
8834   assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
8835 
8836   /* Save the positions of any other cursors open on this table.
8837   **
8838   ** In some cases, the call to btreeMoveto() below is a no-op. For
8839   ** example, when inserting data into a table with auto-generated integer
8840   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8841   ** integer key to use. It then calls this function to actually insert the
8842   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8843   ** that the cursor is already where it needs to be and returns without
8844   ** doing any work. To avoid thwarting these optimizations, it is important
8845   ** not to clear the cursor here.
8846   */
8847   if( pCur->curFlags & BTCF_Multiple ){
8848     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8849     if( rc ) return rc;
8850     if( loc && pCur->iPage<0 ){
8851       /* This can only happen if the schema is corrupt such that there is more
8852       ** than one table or index with the same root page as used by the cursor.
8853       ** Which can only happen if the SQLITE_NoSchemaError flag was set when
8854       ** the schema was loaded. This cannot be asserted though, as a user might
8855       ** set the flag, load the schema, and then unset the flag.  */
8856       return SQLITE_CORRUPT_BKPT;
8857     }
8858   }
8859 
8860   if( pCur->pKeyInfo==0 ){
8861     assert( pX->pKey==0 );
8862     /* If this is an insert into a table b-tree, invalidate any incrblob
8863     ** cursors open on the row being replaced */
8864     if( p->hasIncrblobCur ){
8865       invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8866     }
8867 
8868     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8869     ** to a row with the same key as the new entry being inserted.
8870     */
8871 #ifdef SQLITE_DEBUG
8872     if( flags & BTREE_SAVEPOSITION ){
8873       assert( pCur->curFlags & BTCF_ValidNKey );
8874       assert( pX->nKey==pCur->info.nKey );
8875       assert( loc==0 );
8876     }
8877 #endif
8878 
8879     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8880     ** that the cursor is not pointing to a row to be overwritten.
8881     ** So do a complete check.
8882     */
8883     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8884       /* The cursor is pointing to the entry that is to be
8885       ** overwritten */
8886       assert( pX->nData>=0 && pX->nZero>=0 );
8887       if( pCur->info.nSize!=0
8888        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8889       ){
8890         /* New entry is the same size as the old.  Do an overwrite */
8891         return btreeOverwriteCell(pCur, pX);
8892       }
8893       assert( loc==0 );
8894     }else if( loc==0 ){
8895       /* The cursor is *not* pointing to the cell to be overwritten, nor
8896       ** to an adjacent cell.  Move the cursor so that it is pointing either
8897       ** to the cell to be overwritten or an adjacent cell.
8898       */
8899       rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
8900                (flags & BTREE_APPEND)!=0, &loc);
8901       if( rc ) return rc;
8902     }
8903   }else{
8904     /* This is an index or a WITHOUT ROWID table */
8905 
8906     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8907     ** to a row with the same key as the new entry being inserted.
8908     */
8909     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8910 
8911     /* If the cursor is not already pointing either to the cell to be
8912     ** overwritten, or if a new cell is being inserted, if the cursor is
8913     ** not pointing to an immediately adjacent cell, then move the cursor
8914     ** so that it does.
8915     */
8916     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8917       if( pX->nMem ){
8918         UnpackedRecord r;
8919         r.pKeyInfo = pCur->pKeyInfo;
8920         r.aMem = pX->aMem;
8921         r.nField = pX->nMem;
8922         r.default_rc = 0;
8923         r.eqSeen = 0;
8924         rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
8925       }else{
8926         rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
8927                     (flags & BTREE_APPEND)!=0, &loc);
8928       }
8929       if( rc ) return rc;
8930     }
8931 
8932     /* If the cursor is currently pointing to an entry to be overwritten
8933     ** and the new content is the same as as the old, then use the
8934     ** overwrite optimization.
8935     */
8936     if( loc==0 ){
8937       getCellInfo(pCur);
8938       if( pCur->info.nKey==pX->nKey ){
8939         BtreePayload x2;
8940         x2.pData = pX->pKey;
8941         x2.nData = pX->nKey;
8942         x2.nZero = 0;
8943         return btreeOverwriteCell(pCur, &x2);
8944       }
8945     }
8946   }
8947   assert( pCur->eState==CURSOR_VALID
8948        || (pCur->eState==CURSOR_INVALID && loc)
8949        || CORRUPT_DB );
8950 
8951   pPage = pCur->pPage;
8952   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8953   assert( pPage->leaf || !pPage->intKey );
8954   if( pPage->nFree<0 ){
8955     if( NEVER(pCur->eState>CURSOR_INVALID) ){
8956       rc = SQLITE_CORRUPT_BKPT;
8957     }else{
8958       rc = btreeComputeFreeSpace(pPage);
8959     }
8960     if( rc ) return rc;
8961   }
8962 
8963   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8964           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8965           loc==0 ? "overwrite" : "new entry"));
8966   assert( pPage->isInit );
8967   newCell = pBt->pTmpSpace;
8968   assert( newCell!=0 );
8969   if( flags & BTREE_PREFORMAT ){
8970     rc = SQLITE_OK;
8971     szNew = pBt->nPreformatSize;
8972     if( szNew<4 ) szNew = 4;
8973     if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
8974       CellInfo info;
8975       pPage->xParseCell(pPage, newCell, &info);
8976       if( info.nPayload!=info.nLocal ){
8977         Pgno ovfl = get4byte(&newCell[szNew-4]);
8978         ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
8979       }
8980     }
8981   }else{
8982     rc = fillInCell(pPage, newCell, pX, &szNew);
8983   }
8984   if( rc ) goto end_insert;
8985   assert( szNew==pPage->xCellSize(pPage, newCell) );
8986   assert( szNew <= MX_CELL_SIZE(pBt) );
8987   idx = pCur->ix;
8988   if( loc==0 ){
8989     CellInfo info;
8990     assert( idx>=0 );
8991     if( idx>=pPage->nCell ){
8992       return SQLITE_CORRUPT_BKPT;
8993     }
8994     rc = sqlite3PagerWrite(pPage->pDbPage);
8995     if( rc ){
8996       goto end_insert;
8997     }
8998     oldCell = findCell(pPage, idx);
8999     if( !pPage->leaf ){
9000       memcpy(newCell, oldCell, 4);
9001     }
9002     BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9003     testcase( pCur->curFlags & BTCF_ValidOvfl );
9004     invalidateOverflowCache(pCur);
9005     if( info.nSize==szNew && info.nLocal==info.nPayload
9006      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
9007     ){
9008       /* Overwrite the old cell with the new if they are the same size.
9009       ** We could also try to do this if the old cell is smaller, then add
9010       ** the leftover space to the free list.  But experiments show that
9011       ** doing that is no faster then skipping this optimization and just
9012       ** calling dropCell() and insertCell().
9013       **
9014       ** This optimization cannot be used on an autovacuum database if the
9015       ** new entry uses overflow pages, as the insertCell() call below is
9016       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
9017       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9018       if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9019         return SQLITE_CORRUPT_BKPT;
9020       }
9021       if( oldCell+szNew > pPage->aDataEnd ){
9022         return SQLITE_CORRUPT_BKPT;
9023       }
9024       memcpy(oldCell, newCell, szNew);
9025       return SQLITE_OK;
9026     }
9027     dropCell(pPage, idx, info.nSize, &rc);
9028     if( rc ) goto end_insert;
9029   }else if( loc<0 && pPage->nCell>0 ){
9030     assert( pPage->leaf );
9031     idx = ++pCur->ix;
9032     pCur->curFlags &= ~BTCF_ValidNKey;
9033   }else{
9034     assert( pPage->leaf );
9035   }
9036   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
9037   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9038   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9039 
9040   /* If no error has occurred and pPage has an overflow cell, call balance()
9041   ** to redistribute the cells within the tree. Since balance() may move
9042   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9043   ** variables.
9044   **
9045   ** Previous versions of SQLite called moveToRoot() to move the cursor
9046   ** back to the root page as balance() used to invalidate the contents
9047   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9048   ** set the cursor state to "invalid". This makes common insert operations
9049   ** slightly faster.
9050   **
9051   ** There is a subtle but important optimization here too. When inserting
9052   ** multiple records into an intkey b-tree using a single cursor (as can
9053   ** happen while processing an "INSERT INTO ... SELECT" statement), it
9054   ** is advantageous to leave the cursor pointing to the last entry in
9055   ** the b-tree if possible. If the cursor is left pointing to the last
9056   ** entry in the table, and the next row inserted has an integer key
9057   ** larger than the largest existing key, it is possible to insert the
9058   ** row without seeking the cursor. This can be a big performance boost.
9059   */
9060   pCur->info.nSize = 0;
9061   if( pPage->nOverflow ){
9062     assert( rc==SQLITE_OK );
9063     pCur->curFlags &= ~(BTCF_ValidNKey);
9064     rc = balance(pCur);
9065 
9066     /* Must make sure nOverflow is reset to zero even if the balance()
9067     ** fails. Internal data structure corruption will result otherwise.
9068     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9069     ** from trying to save the current position of the cursor.  */
9070     pCur->pPage->nOverflow = 0;
9071     pCur->eState = CURSOR_INVALID;
9072     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9073       btreeReleaseAllCursorPages(pCur);
9074       if( pCur->pKeyInfo ){
9075         assert( pCur->pKey==0 );
9076         pCur->pKey = sqlite3Malloc( pX->nKey );
9077         if( pCur->pKey==0 ){
9078           rc = SQLITE_NOMEM;
9079         }else{
9080           memcpy(pCur->pKey, pX->pKey, pX->nKey);
9081         }
9082       }
9083       pCur->eState = CURSOR_REQUIRESEEK;
9084       pCur->nKey = pX->nKey;
9085     }
9086   }
9087   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9088 
9089 end_insert:
9090   return rc;
9091 }
9092 
9093 /*
9094 ** This function is used as part of copying the current row from cursor
9095 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9096 ** parameter iKey is used as the rowid value when the record is copied
9097 ** into pDest. Otherwise, the record is copied verbatim.
9098 **
9099 ** This function does not actually write the new value to cursor pDest.
9100 ** Instead, it creates and populates any required overflow pages and
9101 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9102 ** for the destination database. The size of the cell, in bytes, is left
9103 ** in BtShared.nPreformatSize. The caller completes the insertion by
9104 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9105 **
9106 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9107 */
9108 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9109   int rc = SQLITE_OK;
9110   BtShared *pBt = pDest->pBt;
9111   u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
9112   const u8 *aIn;                /* Pointer to next input buffer */
9113   u32 nIn;                      /* Size of input buffer aIn[] */
9114   u32 nRem;                     /* Bytes of data still to copy */
9115 
9116   getCellInfo(pSrc);
9117   aOut += putVarint32(aOut, pSrc->info.nPayload);
9118   if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9119   nIn = pSrc->info.nLocal;
9120   aIn = pSrc->info.pPayload;
9121   if( aIn+nIn>pSrc->pPage->aDataEnd ){
9122     return SQLITE_CORRUPT_BKPT;
9123   }
9124   nRem = pSrc->info.nPayload;
9125   if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9126     memcpy(aOut, aIn, nIn);
9127     pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9128   }else{
9129     Pager *pSrcPager = pSrc->pBt->pPager;
9130     u8 *pPgnoOut = 0;
9131     Pgno ovflIn = 0;
9132     DbPage *pPageIn = 0;
9133     MemPage *pPageOut = 0;
9134     u32 nOut;                     /* Size of output buffer aOut[] */
9135 
9136     nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9137     pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9138     if( nOut<pSrc->info.nPayload ){
9139       pPgnoOut = &aOut[nOut];
9140       pBt->nPreformatSize += 4;
9141     }
9142 
9143     if( nRem>nIn ){
9144       if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9145         return SQLITE_CORRUPT_BKPT;
9146       }
9147       ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9148     }
9149 
9150     do {
9151       nRem -= nOut;
9152       do{
9153         assert( nOut>0 );
9154         if( nIn>0 ){
9155           int nCopy = MIN(nOut, nIn);
9156           memcpy(aOut, aIn, nCopy);
9157           nOut -= nCopy;
9158           nIn -= nCopy;
9159           aOut += nCopy;
9160           aIn += nCopy;
9161         }
9162         if( nOut>0 ){
9163           sqlite3PagerUnref(pPageIn);
9164           pPageIn = 0;
9165           rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9166           if( rc==SQLITE_OK ){
9167             aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9168             ovflIn = get4byte(aIn);
9169             aIn += 4;
9170             nIn = pSrc->pBt->usableSize - 4;
9171           }
9172         }
9173       }while( rc==SQLITE_OK && nOut>0 );
9174 
9175       if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9176         Pgno pgnoNew;
9177         MemPage *pNew = 0;
9178         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9179         put4byte(pPgnoOut, pgnoNew);
9180         if( ISAUTOVACUUM && pPageOut ){
9181           ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9182         }
9183         releasePage(pPageOut);
9184         pPageOut = pNew;
9185         if( pPageOut ){
9186           pPgnoOut = pPageOut->aData;
9187           put4byte(pPgnoOut, 0);
9188           aOut = &pPgnoOut[4];
9189           nOut = MIN(pBt->usableSize - 4, nRem);
9190         }
9191       }
9192     }while( nRem>0 && rc==SQLITE_OK );
9193 
9194     releasePage(pPageOut);
9195     sqlite3PagerUnref(pPageIn);
9196   }
9197 
9198   return rc;
9199 }
9200 
9201 /*
9202 ** Delete the entry that the cursor is pointing to.
9203 **
9204 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9205 ** the cursor is left pointing at an arbitrary location after the delete.
9206 ** But if that bit is set, then the cursor is left in a state such that
9207 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9208 ** as it would have been on if the call to BtreeDelete() had been omitted.
9209 **
9210 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9211 ** associated with a single table entry and its indexes.  Only one of those
9212 ** deletes is considered the "primary" delete.  The primary delete occurs
9213 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
9214 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9215 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9216 ** but which might be used by alternative storage engines.
9217 */
9218 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9219   Btree *p = pCur->pBtree;
9220   BtShared *pBt = p->pBt;
9221   int rc;                              /* Return code */
9222   MemPage *pPage;                      /* Page to delete cell from */
9223   unsigned char *pCell;                /* Pointer to cell to delete */
9224   int iCellIdx;                        /* Index of cell to delete */
9225   int iCellDepth;                      /* Depth of node containing pCell */
9226   CellInfo info;                       /* Size of the cell being deleted */
9227   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
9228   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
9229 
9230   assert( cursorOwnsBtShared(pCur) );
9231   assert( pBt->inTransaction==TRANS_WRITE );
9232   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9233   assert( pCur->curFlags & BTCF_WriteFlag );
9234   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9235   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9236   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9237   if( pCur->eState==CURSOR_REQUIRESEEK ){
9238     rc = btreeRestoreCursorPosition(pCur);
9239     assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9240     if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9241   }
9242   assert( CORRUPT_DB || pCur->eState==CURSOR_VALID );
9243 
9244   iCellDepth = pCur->iPage;
9245   iCellIdx = pCur->ix;
9246   pPage = pCur->pPage;
9247   pCell = findCell(pPage, iCellIdx);
9248   if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
9249 
9250   /* If the bPreserve flag is set to true, then the cursor position must
9251   ** be preserved following this delete operation. If the current delete
9252   ** will cause a b-tree rebalance, then this is done by saving the cursor
9253   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9254   ** returning.
9255   **
9256   ** Or, if the current delete will not cause a rebalance, then the cursor
9257   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9258   ** before or after the deleted entry. In this case set bSkipnext to true.  */
9259   if( bPreserve ){
9260     if( !pPage->leaf
9261      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9262      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
9263     ){
9264       /* A b-tree rebalance will be required after deleting this entry.
9265       ** Save the cursor key.  */
9266       rc = saveCursorKey(pCur);
9267       if( rc ) return rc;
9268     }else{
9269       bSkipnext = 1;
9270     }
9271   }
9272 
9273   /* If the page containing the entry to delete is not a leaf page, move
9274   ** the cursor to the largest entry in the tree that is smaller than
9275   ** the entry being deleted. This cell will replace the cell being deleted
9276   ** from the internal node. The 'previous' entry is used for this instead
9277   ** of the 'next' entry, as the previous entry is always a part of the
9278   ** sub-tree headed by the child page of the cell being deleted. This makes
9279   ** balancing the tree following the delete operation easier.  */
9280   if( !pPage->leaf ){
9281     rc = sqlite3BtreePrevious(pCur, 0);
9282     assert( rc!=SQLITE_DONE );
9283     if( rc ) return rc;
9284   }
9285 
9286   /* Save the positions of any other cursors open on this table before
9287   ** making any modifications.  */
9288   if( pCur->curFlags & BTCF_Multiple ){
9289     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9290     if( rc ) return rc;
9291   }
9292 
9293   /* If this is a delete operation to remove a row from a table b-tree,
9294   ** invalidate any incrblob cursors open on the row being deleted.  */
9295   if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9296     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9297   }
9298 
9299   /* Make the page containing the entry to be deleted writable. Then free any
9300   ** overflow pages associated with the entry and finally remove the cell
9301   ** itself from within the page.  */
9302   rc = sqlite3PagerWrite(pPage->pDbPage);
9303   if( rc ) return rc;
9304   BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9305   dropCell(pPage, iCellIdx, info.nSize, &rc);
9306   if( rc ) return rc;
9307 
9308   /* If the cell deleted was not located on a leaf page, then the cursor
9309   ** is currently pointing to the largest entry in the sub-tree headed
9310   ** by the child-page of the cell that was just deleted from an internal
9311   ** node. The cell from the leaf node needs to be moved to the internal
9312   ** node to replace the deleted cell.  */
9313   if( !pPage->leaf ){
9314     MemPage *pLeaf = pCur->pPage;
9315     int nCell;
9316     Pgno n;
9317     unsigned char *pTmp;
9318 
9319     if( pLeaf->nFree<0 ){
9320       rc = btreeComputeFreeSpace(pLeaf);
9321       if( rc ) return rc;
9322     }
9323     if( iCellDepth<pCur->iPage-1 ){
9324       n = pCur->apPage[iCellDepth+1]->pgno;
9325     }else{
9326       n = pCur->pPage->pgno;
9327     }
9328     pCell = findCell(pLeaf, pLeaf->nCell-1);
9329     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9330     nCell = pLeaf->xCellSize(pLeaf, pCell);
9331     assert( MX_CELL_SIZE(pBt) >= nCell );
9332     pTmp = pBt->pTmpSpace;
9333     assert( pTmp!=0 );
9334     rc = sqlite3PagerWrite(pLeaf->pDbPage);
9335     if( rc==SQLITE_OK ){
9336       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9337     }
9338     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9339     if( rc ) return rc;
9340   }
9341 
9342   /* Balance the tree. If the entry deleted was located on a leaf page,
9343   ** then the cursor still points to that page. In this case the first
9344   ** call to balance() repairs the tree, and the if(...) condition is
9345   ** never true.
9346   **
9347   ** Otherwise, if the entry deleted was on an internal node page, then
9348   ** pCur is pointing to the leaf page from which a cell was removed to
9349   ** replace the cell deleted from the internal node. This is slightly
9350   ** tricky as the leaf node may be underfull, and the internal node may
9351   ** be either under or overfull. In this case run the balancing algorithm
9352   ** on the leaf node first. If the balance proceeds far enough up the
9353   ** tree that we can be sure that any problem in the internal node has
9354   ** been corrected, so be it. Otherwise, after balancing the leaf node,
9355   ** walk the cursor up the tree to the internal node and balance it as
9356   ** well.  */
9357   rc = balance(pCur);
9358   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9359     releasePageNotNull(pCur->pPage);
9360     pCur->iPage--;
9361     while( pCur->iPage>iCellDepth ){
9362       releasePage(pCur->apPage[pCur->iPage--]);
9363     }
9364     pCur->pPage = pCur->apPage[pCur->iPage];
9365     rc = balance(pCur);
9366   }
9367 
9368   if( rc==SQLITE_OK ){
9369     if( bSkipnext ){
9370       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9371       assert( pPage==pCur->pPage || CORRUPT_DB );
9372       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9373       pCur->eState = CURSOR_SKIPNEXT;
9374       if( iCellIdx>=pPage->nCell ){
9375         pCur->skipNext = -1;
9376         pCur->ix = pPage->nCell-1;
9377       }else{
9378         pCur->skipNext = 1;
9379       }
9380     }else{
9381       rc = moveToRoot(pCur);
9382       if( bPreserve ){
9383         btreeReleaseAllCursorPages(pCur);
9384         pCur->eState = CURSOR_REQUIRESEEK;
9385       }
9386       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9387     }
9388   }
9389   return rc;
9390 }
9391 
9392 /*
9393 ** Create a new BTree table.  Write into *piTable the page
9394 ** number for the root page of the new table.
9395 **
9396 ** The type of type is determined by the flags parameter.  Only the
9397 ** following values of flags are currently in use.  Other values for
9398 ** flags might not work:
9399 **
9400 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
9401 **     BTREE_ZERODATA                  Used for SQL indices
9402 */
9403 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9404   BtShared *pBt = p->pBt;
9405   MemPage *pRoot;
9406   Pgno pgnoRoot;
9407   int rc;
9408   int ptfFlags;          /* Page-type flage for the root page of new table */
9409 
9410   assert( sqlite3BtreeHoldsMutex(p) );
9411   assert( pBt->inTransaction==TRANS_WRITE );
9412   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9413 
9414 #ifdef SQLITE_OMIT_AUTOVACUUM
9415   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9416   if( rc ){
9417     return rc;
9418   }
9419 #else
9420   if( pBt->autoVacuum ){
9421     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
9422     MemPage *pPageMove; /* The page to move to. */
9423 
9424     /* Creating a new table may probably require moving an existing database
9425     ** to make room for the new tables root page. In case this page turns
9426     ** out to be an overflow page, delete all overflow page-map caches
9427     ** held by open cursors.
9428     */
9429     invalidateAllOverflowCache(pBt);
9430 
9431     /* Read the value of meta[3] from the database to determine where the
9432     ** root page of the new table should go. meta[3] is the largest root-page
9433     ** created so far, so the new root-page is (meta[3]+1).
9434     */
9435     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9436     if( pgnoRoot>btreePagecount(pBt) ){
9437       return SQLITE_CORRUPT_BKPT;
9438     }
9439     pgnoRoot++;
9440 
9441     /* The new root-page may not be allocated on a pointer-map page, or the
9442     ** PENDING_BYTE page.
9443     */
9444     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9445         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9446       pgnoRoot++;
9447     }
9448     assert( pgnoRoot>=3 );
9449 
9450     /* Allocate a page. The page that currently resides at pgnoRoot will
9451     ** be moved to the allocated page (unless the allocated page happens
9452     ** to reside at pgnoRoot).
9453     */
9454     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9455     if( rc!=SQLITE_OK ){
9456       return rc;
9457     }
9458 
9459     if( pgnoMove!=pgnoRoot ){
9460       /* pgnoRoot is the page that will be used for the root-page of
9461       ** the new table (assuming an error did not occur). But we were
9462       ** allocated pgnoMove. If required (i.e. if it was not allocated
9463       ** by extending the file), the current page at position pgnoMove
9464       ** is already journaled.
9465       */
9466       u8 eType = 0;
9467       Pgno iPtrPage = 0;
9468 
9469       /* Save the positions of any open cursors. This is required in
9470       ** case they are holding a reference to an xFetch reference
9471       ** corresponding to page pgnoRoot.  */
9472       rc = saveAllCursors(pBt, 0, 0);
9473       releasePage(pPageMove);
9474       if( rc!=SQLITE_OK ){
9475         return rc;
9476       }
9477 
9478       /* Move the page currently at pgnoRoot to pgnoMove. */
9479       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9480       if( rc!=SQLITE_OK ){
9481         return rc;
9482       }
9483       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9484       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9485         rc = SQLITE_CORRUPT_BKPT;
9486       }
9487       if( rc!=SQLITE_OK ){
9488         releasePage(pRoot);
9489         return rc;
9490       }
9491       assert( eType!=PTRMAP_ROOTPAGE );
9492       assert( eType!=PTRMAP_FREEPAGE );
9493       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9494       releasePage(pRoot);
9495 
9496       /* Obtain the page at pgnoRoot */
9497       if( rc!=SQLITE_OK ){
9498         return rc;
9499       }
9500       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9501       if( rc!=SQLITE_OK ){
9502         return rc;
9503       }
9504       rc = sqlite3PagerWrite(pRoot->pDbPage);
9505       if( rc!=SQLITE_OK ){
9506         releasePage(pRoot);
9507         return rc;
9508       }
9509     }else{
9510       pRoot = pPageMove;
9511     }
9512 
9513     /* Update the pointer-map and meta-data with the new root-page number. */
9514     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9515     if( rc ){
9516       releasePage(pRoot);
9517       return rc;
9518     }
9519 
9520     /* When the new root page was allocated, page 1 was made writable in
9521     ** order either to increase the database filesize, or to decrement the
9522     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9523     */
9524     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9525     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9526     if( NEVER(rc) ){
9527       releasePage(pRoot);
9528       return rc;
9529     }
9530 
9531   }else{
9532     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9533     if( rc ) return rc;
9534   }
9535 #endif
9536   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9537   if( createTabFlags & BTREE_INTKEY ){
9538     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9539   }else{
9540     ptfFlags = PTF_ZERODATA | PTF_LEAF;
9541   }
9542   zeroPage(pRoot, ptfFlags);
9543   sqlite3PagerUnref(pRoot->pDbPage);
9544   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9545   *piTable = pgnoRoot;
9546   return SQLITE_OK;
9547 }
9548 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9549   int rc;
9550   sqlite3BtreeEnter(p);
9551   rc = btreeCreateTable(p, piTable, flags);
9552   sqlite3BtreeLeave(p);
9553   return rc;
9554 }
9555 
9556 /*
9557 ** Erase the given database page and all its children.  Return
9558 ** the page to the freelist.
9559 */
9560 static int clearDatabasePage(
9561   BtShared *pBt,           /* The BTree that contains the table */
9562   Pgno pgno,               /* Page number to clear */
9563   int freePageFlag,        /* Deallocate page if true */
9564   i64 *pnChange            /* Add number of Cells freed to this counter */
9565 ){
9566   MemPage *pPage;
9567   int rc;
9568   unsigned char *pCell;
9569   int i;
9570   int hdr;
9571   CellInfo info;
9572 
9573   assert( sqlite3_mutex_held(pBt->mutex) );
9574   if( pgno>btreePagecount(pBt) ){
9575     return SQLITE_CORRUPT_BKPT;
9576   }
9577   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9578   if( rc ) return rc;
9579   if( (pBt->openFlags & BTREE_SINGLE)==0
9580    && sqlite3PagerPageRefcount(pPage->pDbPage)!=1
9581   ){
9582     rc = SQLITE_CORRUPT_BKPT;
9583     goto cleardatabasepage_out;
9584   }
9585   hdr = pPage->hdrOffset;
9586   for(i=0; i<pPage->nCell; i++){
9587     pCell = findCell(pPage, i);
9588     if( !pPage->leaf ){
9589       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9590       if( rc ) goto cleardatabasepage_out;
9591     }
9592     BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9593     if( rc ) goto cleardatabasepage_out;
9594   }
9595   if( !pPage->leaf ){
9596     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9597     if( rc ) goto cleardatabasepage_out;
9598     if( pPage->intKey ) pnChange = 0;
9599   }
9600   if( pnChange ){
9601     testcase( !pPage->intKey );
9602     *pnChange += pPage->nCell;
9603   }
9604   if( freePageFlag ){
9605     freePage(pPage, &rc);
9606   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9607     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9608   }
9609 
9610 cleardatabasepage_out:
9611   releasePage(pPage);
9612   return rc;
9613 }
9614 
9615 /*
9616 ** Delete all information from a single table in the database.  iTable is
9617 ** the page number of the root of the table.  After this routine returns,
9618 ** the root page is empty, but still exists.
9619 **
9620 ** This routine will fail with SQLITE_LOCKED if there are any open
9621 ** read cursors on the table.  Open write cursors are moved to the
9622 ** root of the table.
9623 **
9624 ** If pnChange is not NULL, then the integer value pointed to by pnChange
9625 ** is incremented by the number of entries in the table.
9626 */
9627 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
9628   int rc;
9629   BtShared *pBt = p->pBt;
9630   sqlite3BtreeEnter(p);
9631   assert( p->inTrans==TRANS_WRITE );
9632 
9633   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9634 
9635   if( SQLITE_OK==rc ){
9636     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9637     ** is the root of a table b-tree - if it is not, the following call is
9638     ** a no-op).  */
9639     if( p->hasIncrblobCur ){
9640       invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9641     }
9642     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9643   }
9644   sqlite3BtreeLeave(p);
9645   return rc;
9646 }
9647 
9648 /*
9649 ** Delete all information from the single table that pCur is open on.
9650 **
9651 ** This routine only work for pCur on an ephemeral table.
9652 */
9653 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9654   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9655 }
9656 
9657 /*
9658 ** Erase all information in a table and add the root of the table to
9659 ** the freelist.  Except, the root of the principle table (the one on
9660 ** page 1) is never added to the freelist.
9661 **
9662 ** This routine will fail with SQLITE_LOCKED if there are any open
9663 ** cursors on the table.
9664 **
9665 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9666 ** root page in the database file, then the last root page
9667 ** in the database file is moved into the slot formerly occupied by
9668 ** iTable and that last slot formerly occupied by the last root page
9669 ** is added to the freelist instead of iTable.  In this say, all
9670 ** root pages are kept at the beginning of the database file, which
9671 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9672 ** page number that used to be the last root page in the file before
9673 ** the move.  If no page gets moved, *piMoved is set to 0.
9674 ** The last root page is recorded in meta[3] and the value of
9675 ** meta[3] is updated by this procedure.
9676 */
9677 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9678   int rc;
9679   MemPage *pPage = 0;
9680   BtShared *pBt = p->pBt;
9681 
9682   assert( sqlite3BtreeHoldsMutex(p) );
9683   assert( p->inTrans==TRANS_WRITE );
9684   assert( iTable>=2 );
9685   if( iTable>btreePagecount(pBt) ){
9686     return SQLITE_CORRUPT_BKPT;
9687   }
9688 
9689   rc = sqlite3BtreeClearTable(p, iTable, 0);
9690   if( rc ) return rc;
9691   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9692   if( NEVER(rc) ){
9693     releasePage(pPage);
9694     return rc;
9695   }
9696 
9697   *piMoved = 0;
9698 
9699 #ifdef SQLITE_OMIT_AUTOVACUUM
9700   freePage(pPage, &rc);
9701   releasePage(pPage);
9702 #else
9703   if( pBt->autoVacuum ){
9704     Pgno maxRootPgno;
9705     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9706 
9707     if( iTable==maxRootPgno ){
9708       /* If the table being dropped is the table with the largest root-page
9709       ** number in the database, put the root page on the free list.
9710       */
9711       freePage(pPage, &rc);
9712       releasePage(pPage);
9713       if( rc!=SQLITE_OK ){
9714         return rc;
9715       }
9716     }else{
9717       /* The table being dropped does not have the largest root-page
9718       ** number in the database. So move the page that does into the
9719       ** gap left by the deleted root-page.
9720       */
9721       MemPage *pMove;
9722       releasePage(pPage);
9723       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9724       if( rc!=SQLITE_OK ){
9725         return rc;
9726       }
9727       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9728       releasePage(pMove);
9729       if( rc!=SQLITE_OK ){
9730         return rc;
9731       }
9732       pMove = 0;
9733       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9734       freePage(pMove, &rc);
9735       releasePage(pMove);
9736       if( rc!=SQLITE_OK ){
9737         return rc;
9738       }
9739       *piMoved = maxRootPgno;
9740     }
9741 
9742     /* Set the new 'max-root-page' value in the database header. This
9743     ** is the old value less one, less one more if that happens to
9744     ** be a root-page number, less one again if that is the
9745     ** PENDING_BYTE_PAGE.
9746     */
9747     maxRootPgno--;
9748     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9749            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9750       maxRootPgno--;
9751     }
9752     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9753 
9754     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9755   }else{
9756     freePage(pPage, &rc);
9757     releasePage(pPage);
9758   }
9759 #endif
9760   return rc;
9761 }
9762 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9763   int rc;
9764   sqlite3BtreeEnter(p);
9765   rc = btreeDropTable(p, iTable, piMoved);
9766   sqlite3BtreeLeave(p);
9767   return rc;
9768 }
9769 
9770 
9771 /*
9772 ** This function may only be called if the b-tree connection already
9773 ** has a read or write transaction open on the database.
9774 **
9775 ** Read the meta-information out of a database file.  Meta[0]
9776 ** is the number of free pages currently in the database.  Meta[1]
9777 ** through meta[15] are available for use by higher layers.  Meta[0]
9778 ** is read-only, the others are read/write.
9779 **
9780 ** The schema layer numbers meta values differently.  At the schema
9781 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9782 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
9783 **
9784 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
9785 ** of reading the value out of the header, it instead loads the "DataVersion"
9786 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
9787 ** database file.  It is a number computed by the pager.  But its access
9788 ** pattern is the same as header meta values, and so it is convenient to
9789 ** read it from this routine.
9790 */
9791 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9792   BtShared *pBt = p->pBt;
9793 
9794   sqlite3BtreeEnter(p);
9795   assert( p->inTrans>TRANS_NONE );
9796   assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9797   assert( pBt->pPage1 );
9798   assert( idx>=0 && idx<=15 );
9799 
9800   if( idx==BTREE_DATA_VERSION ){
9801     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
9802   }else{
9803     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9804   }
9805 
9806   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9807   ** database, mark the database as read-only.  */
9808 #ifdef SQLITE_OMIT_AUTOVACUUM
9809   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9810     pBt->btsFlags |= BTS_READ_ONLY;
9811   }
9812 #endif
9813 
9814   sqlite3BtreeLeave(p);
9815 }
9816 
9817 /*
9818 ** Write meta-information back into the database.  Meta[0] is
9819 ** read-only and may not be written.
9820 */
9821 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9822   BtShared *pBt = p->pBt;
9823   unsigned char *pP1;
9824   int rc;
9825   assert( idx>=1 && idx<=15 );
9826   sqlite3BtreeEnter(p);
9827   assert( p->inTrans==TRANS_WRITE );
9828   assert( pBt->pPage1!=0 );
9829   pP1 = pBt->pPage1->aData;
9830   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9831   if( rc==SQLITE_OK ){
9832     put4byte(&pP1[36 + idx*4], iMeta);
9833 #ifndef SQLITE_OMIT_AUTOVACUUM
9834     if( idx==BTREE_INCR_VACUUM ){
9835       assert( pBt->autoVacuum || iMeta==0 );
9836       assert( iMeta==0 || iMeta==1 );
9837       pBt->incrVacuum = (u8)iMeta;
9838     }
9839 #endif
9840   }
9841   sqlite3BtreeLeave(p);
9842   return rc;
9843 }
9844 
9845 /*
9846 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9847 ** number of entries in the b-tree and write the result to *pnEntry.
9848 **
9849 ** SQLITE_OK is returned if the operation is successfully executed.
9850 ** Otherwise, if an error is encountered (i.e. an IO error or database
9851 ** corruption) an SQLite error code is returned.
9852 */
9853 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9854   i64 nEntry = 0;                      /* Value to return in *pnEntry */
9855   int rc;                              /* Return code */
9856 
9857   rc = moveToRoot(pCur);
9858   if( rc==SQLITE_EMPTY ){
9859     *pnEntry = 0;
9860     return SQLITE_OK;
9861   }
9862 
9863   /* Unless an error occurs, the following loop runs one iteration for each
9864   ** page in the B-Tree structure (not including overflow pages).
9865   */
9866   while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9867     int iIdx;                          /* Index of child node in parent */
9868     MemPage *pPage;                    /* Current page of the b-tree */
9869 
9870     /* If this is a leaf page or the tree is not an int-key tree, then
9871     ** this page contains countable entries. Increment the entry counter
9872     ** accordingly.
9873     */
9874     pPage = pCur->pPage;
9875     if( pPage->leaf || !pPage->intKey ){
9876       nEntry += pPage->nCell;
9877     }
9878 
9879     /* pPage is a leaf node. This loop navigates the cursor so that it
9880     ** points to the first interior cell that it points to the parent of
9881     ** the next page in the tree that has not yet been visited. The
9882     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9883     ** of the page, or to the number of cells in the page if the next page
9884     ** to visit is the right-child of its parent.
9885     **
9886     ** If all pages in the tree have been visited, return SQLITE_OK to the
9887     ** caller.
9888     */
9889     if( pPage->leaf ){
9890       do {
9891         if( pCur->iPage==0 ){
9892           /* All pages of the b-tree have been visited. Return successfully. */
9893           *pnEntry = nEntry;
9894           return moveToRoot(pCur);
9895         }
9896         moveToParent(pCur);
9897       }while ( pCur->ix>=pCur->pPage->nCell );
9898 
9899       pCur->ix++;
9900       pPage = pCur->pPage;
9901     }
9902 
9903     /* Descend to the child node of the cell that the cursor currently
9904     ** points at. This is the right-child if (iIdx==pPage->nCell).
9905     */
9906     iIdx = pCur->ix;
9907     if( iIdx==pPage->nCell ){
9908       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9909     }else{
9910       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9911     }
9912   }
9913 
9914   /* An error has occurred. Return an error code. */
9915   return rc;
9916 }
9917 
9918 /*
9919 ** Return the pager associated with a BTree.  This routine is used for
9920 ** testing and debugging only.
9921 */
9922 Pager *sqlite3BtreePager(Btree *p){
9923   return p->pBt->pPager;
9924 }
9925 
9926 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9927 /*
9928 ** Append a message to the error message string.
9929 */
9930 static void checkAppendMsg(
9931   IntegrityCk *pCheck,
9932   const char *zFormat,
9933   ...
9934 ){
9935   va_list ap;
9936   if( !pCheck->mxErr ) return;
9937   pCheck->mxErr--;
9938   pCheck->nErr++;
9939   va_start(ap, zFormat);
9940   if( pCheck->errMsg.nChar ){
9941     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9942   }
9943   if( pCheck->zPfx ){
9944     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9945   }
9946   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9947   va_end(ap);
9948   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9949     pCheck->bOomFault = 1;
9950   }
9951 }
9952 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9953 
9954 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9955 
9956 /*
9957 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9958 ** corresponds to page iPg is already set.
9959 */
9960 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9961   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9962   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9963 }
9964 
9965 /*
9966 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9967 */
9968 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9969   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9970   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9971 }
9972 
9973 
9974 /*
9975 ** Add 1 to the reference count for page iPage.  If this is the second
9976 ** reference to the page, add an error message to pCheck->zErrMsg.
9977 ** Return 1 if there are 2 or more references to the page and 0 if
9978 ** if this is the first reference to the page.
9979 **
9980 ** Also check that the page number is in bounds.
9981 */
9982 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9983   if( iPage>pCheck->nPage || iPage==0 ){
9984     checkAppendMsg(pCheck, "invalid page number %d", iPage);
9985     return 1;
9986   }
9987   if( getPageReferenced(pCheck, iPage) ){
9988     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9989     return 1;
9990   }
9991   if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9992   setPageReferenced(pCheck, iPage);
9993   return 0;
9994 }
9995 
9996 #ifndef SQLITE_OMIT_AUTOVACUUM
9997 /*
9998 ** Check that the entry in the pointer-map for page iChild maps to
9999 ** page iParent, pointer type ptrType. If not, append an error message
10000 ** to pCheck.
10001 */
10002 static void checkPtrmap(
10003   IntegrityCk *pCheck,   /* Integrity check context */
10004   Pgno iChild,           /* Child page number */
10005   u8 eType,              /* Expected pointer map type */
10006   Pgno iParent           /* Expected pointer map parent page number */
10007 ){
10008   int rc;
10009   u8 ePtrmapType;
10010   Pgno iPtrmapParent;
10011 
10012   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10013   if( rc!=SQLITE_OK ){
10014     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
10015     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
10016     return;
10017   }
10018 
10019   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10020     checkAppendMsg(pCheck,
10021       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
10022       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10023   }
10024 }
10025 #endif
10026 
10027 /*
10028 ** Check the integrity of the freelist or of an overflow page list.
10029 ** Verify that the number of pages on the list is N.
10030 */
10031 static void checkList(
10032   IntegrityCk *pCheck,  /* Integrity checking context */
10033   int isFreeList,       /* True for a freelist.  False for overflow page list */
10034   Pgno iPage,           /* Page number for first page in the list */
10035   u32 N                 /* Expected number of pages in the list */
10036 ){
10037   int i;
10038   u32 expected = N;
10039   int nErrAtStart = pCheck->nErr;
10040   while( iPage!=0 && pCheck->mxErr ){
10041     DbPage *pOvflPage;
10042     unsigned char *pOvflData;
10043     if( checkRef(pCheck, iPage) ) break;
10044     N--;
10045     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10046       checkAppendMsg(pCheck, "failed to get page %d", iPage);
10047       break;
10048     }
10049     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10050     if( isFreeList ){
10051       u32 n = (u32)get4byte(&pOvflData[4]);
10052 #ifndef SQLITE_OMIT_AUTOVACUUM
10053       if( pCheck->pBt->autoVacuum ){
10054         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10055       }
10056 #endif
10057       if( n>pCheck->pBt->usableSize/4-2 ){
10058         checkAppendMsg(pCheck,
10059            "freelist leaf count too big on page %d", iPage);
10060         N--;
10061       }else{
10062         for(i=0; i<(int)n; i++){
10063           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10064 #ifndef SQLITE_OMIT_AUTOVACUUM
10065           if( pCheck->pBt->autoVacuum ){
10066             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10067           }
10068 #endif
10069           checkRef(pCheck, iFreePage);
10070         }
10071         N -= n;
10072       }
10073     }
10074 #ifndef SQLITE_OMIT_AUTOVACUUM
10075     else{
10076       /* If this database supports auto-vacuum and iPage is not the last
10077       ** page in this overflow list, check that the pointer-map entry for
10078       ** the following page matches iPage.
10079       */
10080       if( pCheck->pBt->autoVacuum && N>0 ){
10081         i = get4byte(pOvflData);
10082         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10083       }
10084     }
10085 #endif
10086     iPage = get4byte(pOvflData);
10087     sqlite3PagerUnref(pOvflPage);
10088   }
10089   if( N && nErrAtStart==pCheck->nErr ){
10090     checkAppendMsg(pCheck,
10091       "%s is %d but should be %d",
10092       isFreeList ? "size" : "overflow list length",
10093       expected-N, expected);
10094   }
10095 }
10096 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10097 
10098 /*
10099 ** An implementation of a min-heap.
10100 **
10101 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
10102 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
10103 ** and aHeap[N*2+1].
10104 **
10105 ** The heap property is this:  Every node is less than or equal to both
10106 ** of its daughter nodes.  A consequence of the heap property is that the
10107 ** root node aHeap[1] is always the minimum value currently in the heap.
10108 **
10109 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10110 ** the heap, preserving the heap property.  The btreeHeapPull() routine
10111 ** removes the root element from the heap (the minimum value in the heap)
10112 ** and then moves other nodes around as necessary to preserve the heap
10113 ** property.
10114 **
10115 ** This heap is used for cell overlap and coverage testing.  Each u32
10116 ** entry represents the span of a cell or freeblock on a btree page.
10117 ** The upper 16 bits are the index of the first byte of a range and the
10118 ** lower 16 bits are the index of the last byte of that range.
10119 */
10120 static void btreeHeapInsert(u32 *aHeap, u32 x){
10121   u32 j, i = ++aHeap[0];
10122   aHeap[i] = x;
10123   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10124     x = aHeap[j];
10125     aHeap[j] = aHeap[i];
10126     aHeap[i] = x;
10127     i = j;
10128   }
10129 }
10130 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10131   u32 j, i, x;
10132   if( (x = aHeap[0])==0 ) return 0;
10133   *pOut = aHeap[1];
10134   aHeap[1] = aHeap[x];
10135   aHeap[x] = 0xffffffff;
10136   aHeap[0]--;
10137   i = 1;
10138   while( (j = i*2)<=aHeap[0] ){
10139     if( aHeap[j]>aHeap[j+1] ) j++;
10140     if( aHeap[i]<aHeap[j] ) break;
10141     x = aHeap[i];
10142     aHeap[i] = aHeap[j];
10143     aHeap[j] = x;
10144     i = j;
10145   }
10146   return 1;
10147 }
10148 
10149 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10150 /*
10151 ** Do various sanity checks on a single page of a tree.  Return
10152 ** the tree depth.  Root pages return 0.  Parents of root pages
10153 ** return 1, and so forth.
10154 **
10155 ** These checks are done:
10156 **
10157 **      1.  Make sure that cells and freeblocks do not overlap
10158 **          but combine to completely cover the page.
10159 **      2.  Make sure integer cell keys are in order.
10160 **      3.  Check the integrity of overflow pages.
10161 **      4.  Recursively call checkTreePage on all children.
10162 **      5.  Verify that the depth of all children is the same.
10163 */
10164 static int checkTreePage(
10165   IntegrityCk *pCheck,  /* Context for the sanity check */
10166   Pgno iPage,           /* Page number of the page to check */
10167   i64 *piMinKey,        /* Write minimum integer primary key here */
10168   i64 maxKey            /* Error if integer primary key greater than this */
10169 ){
10170   MemPage *pPage = 0;      /* The page being analyzed */
10171   int i;                   /* Loop counter */
10172   int rc;                  /* Result code from subroutine call */
10173   int depth = -1, d2;      /* Depth of a subtree */
10174   int pgno;                /* Page number */
10175   int nFrag;               /* Number of fragmented bytes on the page */
10176   int hdr;                 /* Offset to the page header */
10177   int cellStart;           /* Offset to the start of the cell pointer array */
10178   int nCell;               /* Number of cells */
10179   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10180   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
10181                            ** False if IPK must be strictly less than maxKey */
10182   u8 *data;                /* Page content */
10183   u8 *pCell;               /* Cell content */
10184   u8 *pCellIdx;            /* Next element of the cell pointer array */
10185   BtShared *pBt;           /* The BtShared object that owns pPage */
10186   u32 pc;                  /* Address of a cell */
10187   u32 usableSize;          /* Usable size of the page */
10188   u32 contentOffset;       /* Offset to the start of the cell content area */
10189   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
10190   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
10191   const char *saved_zPfx = pCheck->zPfx;
10192   int saved_v1 = pCheck->v1;
10193   int saved_v2 = pCheck->v2;
10194   u8 savedIsInit = 0;
10195 
10196   /* Check that the page exists
10197   */
10198   pBt = pCheck->pBt;
10199   usableSize = pBt->usableSize;
10200   if( iPage==0 ) return 0;
10201   if( checkRef(pCheck, iPage) ) return 0;
10202   pCheck->zPfx = "Page %u: ";
10203   pCheck->v1 = iPage;
10204   if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10205     checkAppendMsg(pCheck,
10206        "unable to get the page. error code=%d", rc);
10207     goto end_of_check;
10208   }
10209 
10210   /* Clear MemPage.isInit to make sure the corruption detection code in
10211   ** btreeInitPage() is executed.  */
10212   savedIsInit = pPage->isInit;
10213   pPage->isInit = 0;
10214   if( (rc = btreeInitPage(pPage))!=0 ){
10215     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
10216     checkAppendMsg(pCheck,
10217                    "btreeInitPage() returns error code %d", rc);
10218     goto end_of_check;
10219   }
10220   if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10221     assert( rc==SQLITE_CORRUPT );
10222     checkAppendMsg(pCheck, "free space corruption", rc);
10223     goto end_of_check;
10224   }
10225   data = pPage->aData;
10226   hdr = pPage->hdrOffset;
10227 
10228   /* Set up for cell analysis */
10229   pCheck->zPfx = "On tree page %u cell %d: ";
10230   contentOffset = get2byteNotZero(&data[hdr+5]);
10231   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
10232 
10233   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10234   ** number of cells on the page. */
10235   nCell = get2byte(&data[hdr+3]);
10236   assert( pPage->nCell==nCell );
10237 
10238   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10239   ** immediately follows the b-tree page header. */
10240   cellStart = hdr + 12 - 4*pPage->leaf;
10241   assert( pPage->aCellIdx==&data[cellStart] );
10242   pCellIdx = &data[cellStart + 2*(nCell-1)];
10243 
10244   if( !pPage->leaf ){
10245     /* Analyze the right-child page of internal pages */
10246     pgno = get4byte(&data[hdr+8]);
10247 #ifndef SQLITE_OMIT_AUTOVACUUM
10248     if( pBt->autoVacuum ){
10249       pCheck->zPfx = "On page %u at right child: ";
10250       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10251     }
10252 #endif
10253     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10254     keyCanBeEqual = 0;
10255   }else{
10256     /* For leaf pages, the coverage check will occur in the same loop
10257     ** as the other cell checks, so initialize the heap.  */
10258     heap = pCheck->heap;
10259     heap[0] = 0;
10260   }
10261 
10262   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10263   ** integer offsets to the cell contents. */
10264   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10265     CellInfo info;
10266 
10267     /* Check cell size */
10268     pCheck->v2 = i;
10269     assert( pCellIdx==&data[cellStart + i*2] );
10270     pc = get2byteAligned(pCellIdx);
10271     pCellIdx -= 2;
10272     if( pc<contentOffset || pc>usableSize-4 ){
10273       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10274                              pc, contentOffset, usableSize-4);
10275       doCoverageCheck = 0;
10276       continue;
10277     }
10278     pCell = &data[pc];
10279     pPage->xParseCell(pPage, pCell, &info);
10280     if( pc+info.nSize>usableSize ){
10281       checkAppendMsg(pCheck, "Extends off end of page");
10282       doCoverageCheck = 0;
10283       continue;
10284     }
10285 
10286     /* Check for integer primary key out of range */
10287     if( pPage->intKey ){
10288       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10289         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10290       }
10291       maxKey = info.nKey;
10292       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
10293     }
10294 
10295     /* Check the content overflow list */
10296     if( info.nPayload>info.nLocal ){
10297       u32 nPage;       /* Number of pages on the overflow chain */
10298       Pgno pgnoOvfl;   /* First page of the overflow chain */
10299       assert( pc + info.nSize - 4 <= usableSize );
10300       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10301       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10302 #ifndef SQLITE_OMIT_AUTOVACUUM
10303       if( pBt->autoVacuum ){
10304         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10305       }
10306 #endif
10307       checkList(pCheck, 0, pgnoOvfl, nPage);
10308     }
10309 
10310     if( !pPage->leaf ){
10311       /* Check sanity of left child page for internal pages */
10312       pgno = get4byte(pCell);
10313 #ifndef SQLITE_OMIT_AUTOVACUUM
10314       if( pBt->autoVacuum ){
10315         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10316       }
10317 #endif
10318       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10319       keyCanBeEqual = 0;
10320       if( d2!=depth ){
10321         checkAppendMsg(pCheck, "Child page depth differs");
10322         depth = d2;
10323       }
10324     }else{
10325       /* Populate the coverage-checking heap for leaf pages */
10326       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10327     }
10328   }
10329   *piMinKey = maxKey;
10330 
10331   /* Check for complete coverage of the page
10332   */
10333   pCheck->zPfx = 0;
10334   if( doCoverageCheck && pCheck->mxErr>0 ){
10335     /* For leaf pages, the min-heap has already been initialized and the
10336     ** cells have already been inserted.  But for internal pages, that has
10337     ** not yet been done, so do it now */
10338     if( !pPage->leaf ){
10339       heap = pCheck->heap;
10340       heap[0] = 0;
10341       for(i=nCell-1; i>=0; i--){
10342         u32 size;
10343         pc = get2byteAligned(&data[cellStart+i*2]);
10344         size = pPage->xCellSize(pPage, &data[pc]);
10345         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10346       }
10347     }
10348     /* Add the freeblocks to the min-heap
10349     **
10350     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10351     ** is the offset of the first freeblock, or zero if there are no
10352     ** freeblocks on the page.
10353     */
10354     i = get2byte(&data[hdr+1]);
10355     while( i>0 ){
10356       int size, j;
10357       assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10358       size = get2byte(&data[i+2]);
10359       assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10360       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10361       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10362       ** big-endian integer which is the offset in the b-tree page of the next
10363       ** freeblock in the chain, or zero if the freeblock is the last on the
10364       ** chain. */
10365       j = get2byte(&data[i]);
10366       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10367       ** increasing offset. */
10368       assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
10369       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10370       i = j;
10371     }
10372     /* Analyze the min-heap looking for overlap between cells and/or
10373     ** freeblocks, and counting the number of untracked bytes in nFrag.
10374     **
10375     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
10376     ** There is an implied first entry the covers the page header, the cell
10377     ** pointer index, and the gap between the cell pointer index and the start
10378     ** of cell content.
10379     **
10380     ** The loop below pulls entries from the min-heap in order and compares
10381     ** the start_address against the previous end_address.  If there is an
10382     ** overlap, that means bytes are used multiple times.  If there is a gap,
10383     ** that gap is added to the fragmentation count.
10384     */
10385     nFrag = 0;
10386     prev = contentOffset - 1;   /* Implied first min-heap entry */
10387     while( btreeHeapPull(heap,&x) ){
10388       if( (prev&0xffff)>=(x>>16) ){
10389         checkAppendMsg(pCheck,
10390           "Multiple uses for byte %u of page %u", x>>16, iPage);
10391         break;
10392       }else{
10393         nFrag += (x>>16) - (prev&0xffff) - 1;
10394         prev = x;
10395       }
10396     }
10397     nFrag += usableSize - (prev&0xffff) - 1;
10398     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10399     ** is stored in the fifth field of the b-tree page header.
10400     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10401     ** number of fragmented free bytes within the cell content area.
10402     */
10403     if( heap[0]==0 && nFrag!=data[hdr+7] ){
10404       checkAppendMsg(pCheck,
10405           "Fragmentation of %d bytes reported as %d on page %u",
10406           nFrag, data[hdr+7], iPage);
10407     }
10408   }
10409 
10410 end_of_check:
10411   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10412   releasePage(pPage);
10413   pCheck->zPfx = saved_zPfx;
10414   pCheck->v1 = saved_v1;
10415   pCheck->v2 = saved_v2;
10416   return depth+1;
10417 }
10418 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10419 
10420 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10421 /*
10422 ** This routine does a complete check of the given BTree file.  aRoot[] is
10423 ** an array of pages numbers were each page number is the root page of
10424 ** a table.  nRoot is the number of entries in aRoot.
10425 **
10426 ** A read-only or read-write transaction must be opened before calling
10427 ** this function.
10428 **
10429 ** Write the number of error seen in *pnErr.  Except for some memory
10430 ** allocation errors,  an error message held in memory obtained from
10431 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
10432 ** returned.  If a memory allocation error occurs, NULL is returned.
10433 **
10434 ** If the first entry in aRoot[] is 0, that indicates that the list of
10435 ** root pages is incomplete.  This is a "partial integrity-check".  This
10436 ** happens when performing an integrity check on a single table.  The
10437 ** zero is skipped, of course.  But in addition, the freelist checks
10438 ** and the checks to make sure every page is referenced are also skipped,
10439 ** since obviously it is not possible to know which pages are covered by
10440 ** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
10441 ** checks are still performed.
10442 */
10443 char *sqlite3BtreeIntegrityCheck(
10444   sqlite3 *db,  /* Database connection that is running the check */
10445   Btree *p,     /* The btree to be checked */
10446   Pgno *aRoot,  /* An array of root pages numbers for individual trees */
10447   int nRoot,    /* Number of entries in aRoot[] */
10448   int mxErr,    /* Stop reporting errors after this many */
10449   int *pnErr    /* Write number of errors seen to this variable */
10450 ){
10451   Pgno i;
10452   IntegrityCk sCheck;
10453   BtShared *pBt = p->pBt;
10454   u64 savedDbFlags = pBt->db->flags;
10455   char zErr[100];
10456   int bPartial = 0;            /* True if not checking all btrees */
10457   int bCkFreelist = 1;         /* True to scan the freelist */
10458   VVA_ONLY( int nRef );
10459   assert( nRoot>0 );
10460 
10461   /* aRoot[0]==0 means this is a partial check */
10462   if( aRoot[0]==0 ){
10463     assert( nRoot>1 );
10464     bPartial = 1;
10465     if( aRoot[1]!=1 ) bCkFreelist = 0;
10466   }
10467 
10468   sqlite3BtreeEnter(p);
10469   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10470   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10471   assert( nRef>=0 );
10472   sCheck.db = db;
10473   sCheck.pBt = pBt;
10474   sCheck.pPager = pBt->pPager;
10475   sCheck.nPage = btreePagecount(sCheck.pBt);
10476   sCheck.mxErr = mxErr;
10477   sCheck.nErr = 0;
10478   sCheck.bOomFault = 0;
10479   sCheck.zPfx = 0;
10480   sCheck.v1 = 0;
10481   sCheck.v2 = 0;
10482   sCheck.aPgRef = 0;
10483   sCheck.heap = 0;
10484   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10485   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10486   if( sCheck.nPage==0 ){
10487     goto integrity_ck_cleanup;
10488   }
10489 
10490   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10491   if( !sCheck.aPgRef ){
10492     sCheck.bOomFault = 1;
10493     goto integrity_ck_cleanup;
10494   }
10495   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10496   if( sCheck.heap==0 ){
10497     sCheck.bOomFault = 1;
10498     goto integrity_ck_cleanup;
10499   }
10500 
10501   i = PENDING_BYTE_PAGE(pBt);
10502   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10503 
10504   /* Check the integrity of the freelist
10505   */
10506   if( bCkFreelist ){
10507     sCheck.zPfx = "Main freelist: ";
10508     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10509               get4byte(&pBt->pPage1->aData[36]));
10510     sCheck.zPfx = 0;
10511   }
10512 
10513   /* Check all the tables.
10514   */
10515 #ifndef SQLITE_OMIT_AUTOVACUUM
10516   if( !bPartial ){
10517     if( pBt->autoVacuum ){
10518       Pgno mx = 0;
10519       Pgno mxInHdr;
10520       for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10521       mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10522       if( mx!=mxInHdr ){
10523         checkAppendMsg(&sCheck,
10524           "max rootpage (%d) disagrees with header (%d)",
10525           mx, mxInHdr
10526         );
10527       }
10528     }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10529       checkAppendMsg(&sCheck,
10530         "incremental_vacuum enabled with a max rootpage of zero"
10531       );
10532     }
10533   }
10534 #endif
10535   testcase( pBt->db->flags & SQLITE_CellSizeCk );
10536   pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10537   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10538     i64 notUsed;
10539     if( aRoot[i]==0 ) continue;
10540 #ifndef SQLITE_OMIT_AUTOVACUUM
10541     if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10542       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10543     }
10544 #endif
10545     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10546   }
10547   pBt->db->flags = savedDbFlags;
10548 
10549   /* Make sure every page in the file is referenced
10550   */
10551   if( !bPartial ){
10552     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10553 #ifdef SQLITE_OMIT_AUTOVACUUM
10554       if( getPageReferenced(&sCheck, i)==0 ){
10555         checkAppendMsg(&sCheck, "Page %d is never used", i);
10556       }
10557 #else
10558       /* If the database supports auto-vacuum, make sure no tables contain
10559       ** references to pointer-map pages.
10560       */
10561       if( getPageReferenced(&sCheck, i)==0 &&
10562          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10563         checkAppendMsg(&sCheck, "Page %d is never used", i);
10564       }
10565       if( getPageReferenced(&sCheck, i)!=0 &&
10566          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10567         checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10568       }
10569 #endif
10570     }
10571   }
10572 
10573   /* Clean  up and report errors.
10574   */
10575 integrity_ck_cleanup:
10576   sqlite3PageFree(sCheck.heap);
10577   sqlite3_free(sCheck.aPgRef);
10578   if( sCheck.bOomFault ){
10579     sqlite3_str_reset(&sCheck.errMsg);
10580     sCheck.nErr++;
10581   }
10582   *pnErr = sCheck.nErr;
10583   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10584   /* Make sure this analysis did not leave any unref() pages. */
10585   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10586   sqlite3BtreeLeave(p);
10587   return sqlite3StrAccumFinish(&sCheck.errMsg);
10588 }
10589 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10590 
10591 /*
10592 ** Return the full pathname of the underlying database file.  Return
10593 ** an empty string if the database is in-memory or a TEMP database.
10594 **
10595 ** The pager filename is invariant as long as the pager is
10596 ** open so it is safe to access without the BtShared mutex.
10597 */
10598 const char *sqlite3BtreeGetFilename(Btree *p){
10599   assert( p->pBt->pPager!=0 );
10600   return sqlite3PagerFilename(p->pBt->pPager, 1);
10601 }
10602 
10603 /*
10604 ** Return the pathname of the journal file for this database. The return
10605 ** value of this routine is the same regardless of whether the journal file
10606 ** has been created or not.
10607 **
10608 ** The pager journal filename is invariant as long as the pager is
10609 ** open so it is safe to access without the BtShared mutex.
10610 */
10611 const char *sqlite3BtreeGetJournalname(Btree *p){
10612   assert( p->pBt->pPager!=0 );
10613   return sqlite3PagerJournalname(p->pBt->pPager);
10614 }
10615 
10616 /*
10617 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10618 ** to describe the current transaction state of Btree p.
10619 */
10620 int sqlite3BtreeTxnState(Btree *p){
10621   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10622   return p ? p->inTrans : 0;
10623 }
10624 
10625 #ifndef SQLITE_OMIT_WAL
10626 /*
10627 ** Run a checkpoint on the Btree passed as the first argument.
10628 **
10629 ** Return SQLITE_LOCKED if this or any other connection has an open
10630 ** transaction on the shared-cache the argument Btree is connected to.
10631 **
10632 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10633 */
10634 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10635   int rc = SQLITE_OK;
10636   if( p ){
10637     BtShared *pBt = p->pBt;
10638     sqlite3BtreeEnter(p);
10639     if( pBt->inTransaction!=TRANS_NONE ){
10640       rc = SQLITE_LOCKED;
10641     }else{
10642       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10643     }
10644     sqlite3BtreeLeave(p);
10645   }
10646   return rc;
10647 }
10648 #endif
10649 
10650 /*
10651 ** Return true if there is currently a backup running on Btree p.
10652 */
10653 int sqlite3BtreeIsInBackup(Btree *p){
10654   assert( p );
10655   assert( sqlite3_mutex_held(p->db->mutex) );
10656   return p->nBackup!=0;
10657 }
10658 
10659 /*
10660 ** This function returns a pointer to a blob of memory associated with
10661 ** a single shared-btree. The memory is used by client code for its own
10662 ** purposes (for example, to store a high-level schema associated with
10663 ** the shared-btree). The btree layer manages reference counting issues.
10664 **
10665 ** The first time this is called on a shared-btree, nBytes bytes of memory
10666 ** are allocated, zeroed, and returned to the caller. For each subsequent
10667 ** call the nBytes parameter is ignored and a pointer to the same blob
10668 ** of memory returned.
10669 **
10670 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10671 ** allocated, a null pointer is returned. If the blob has already been
10672 ** allocated, it is returned as normal.
10673 **
10674 ** Just before the shared-btree is closed, the function passed as the
10675 ** xFree argument when the memory allocation was made is invoked on the
10676 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10677 ** on the memory, the btree layer does that.
10678 */
10679 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10680   BtShared *pBt = p->pBt;
10681   sqlite3BtreeEnter(p);
10682   if( !pBt->pSchema && nBytes ){
10683     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10684     pBt->xFreeSchema = xFree;
10685   }
10686   sqlite3BtreeLeave(p);
10687   return pBt->pSchema;
10688 }
10689 
10690 /*
10691 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10692 ** btree as the argument handle holds an exclusive lock on the
10693 ** sqlite_schema table. Otherwise SQLITE_OK.
10694 */
10695 int sqlite3BtreeSchemaLocked(Btree *p){
10696   int rc;
10697   assert( sqlite3_mutex_held(p->db->mutex) );
10698   sqlite3BtreeEnter(p);
10699   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10700   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10701   sqlite3BtreeLeave(p);
10702   return rc;
10703 }
10704 
10705 
10706 #ifndef SQLITE_OMIT_SHARED_CACHE
10707 /*
10708 ** Obtain a lock on the table whose root page is iTab.  The
10709 ** lock is a write lock if isWritelock is true or a read lock
10710 ** if it is false.
10711 */
10712 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10713   int rc = SQLITE_OK;
10714   assert( p->inTrans!=TRANS_NONE );
10715   if( p->sharable ){
10716     u8 lockType = READ_LOCK + isWriteLock;
10717     assert( READ_LOCK+1==WRITE_LOCK );
10718     assert( isWriteLock==0 || isWriteLock==1 );
10719 
10720     sqlite3BtreeEnter(p);
10721     rc = querySharedCacheTableLock(p, iTab, lockType);
10722     if( rc==SQLITE_OK ){
10723       rc = setSharedCacheTableLock(p, iTab, lockType);
10724     }
10725     sqlite3BtreeLeave(p);
10726   }
10727   return rc;
10728 }
10729 #endif
10730 
10731 #ifndef SQLITE_OMIT_INCRBLOB
10732 /*
10733 ** Argument pCsr must be a cursor opened for writing on an
10734 ** INTKEY table currently pointing at a valid table entry.
10735 ** This function modifies the data stored as part of that entry.
10736 **
10737 ** Only the data content may only be modified, it is not possible to
10738 ** change the length of the data stored. If this function is called with
10739 ** parameters that attempt to write past the end of the existing data,
10740 ** no modifications are made and SQLITE_CORRUPT is returned.
10741 */
10742 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10743   int rc;
10744   assert( cursorOwnsBtShared(pCsr) );
10745   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10746   assert( pCsr->curFlags & BTCF_Incrblob );
10747 
10748   rc = restoreCursorPosition(pCsr);
10749   if( rc!=SQLITE_OK ){
10750     return rc;
10751   }
10752   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10753   if( pCsr->eState!=CURSOR_VALID ){
10754     return SQLITE_ABORT;
10755   }
10756 
10757   /* Save the positions of all other cursors open on this table. This is
10758   ** required in case any of them are holding references to an xFetch
10759   ** version of the b-tree page modified by the accessPayload call below.
10760   **
10761   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10762   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10763   ** saveAllCursors can only return SQLITE_OK.
10764   */
10765   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10766   assert( rc==SQLITE_OK );
10767 
10768   /* Check some assumptions:
10769   **   (a) the cursor is open for writing,
10770   **   (b) there is a read/write transaction open,
10771   **   (c) the connection holds a write-lock on the table (if required),
10772   **   (d) there are no conflicting read-locks, and
10773   **   (e) the cursor points at a valid row of an intKey table.
10774   */
10775   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10776     return SQLITE_READONLY;
10777   }
10778   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10779               && pCsr->pBt->inTransaction==TRANS_WRITE );
10780   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10781   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10782   assert( pCsr->pPage->intKey );
10783 
10784   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10785 }
10786 
10787 /*
10788 ** Mark this cursor as an incremental blob cursor.
10789 */
10790 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10791   pCur->curFlags |= BTCF_Incrblob;
10792   pCur->pBtree->hasIncrblobCur = 1;
10793 }
10794 #endif
10795 
10796 /*
10797 ** Set both the "read version" (single byte at byte offset 18) and
10798 ** "write version" (single byte at byte offset 19) fields in the database
10799 ** header to iVersion.
10800 */
10801 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10802   BtShared *pBt = pBtree->pBt;
10803   int rc;                         /* Return code */
10804 
10805   assert( iVersion==1 || iVersion==2 );
10806 
10807   /* If setting the version fields to 1, do not automatically open the
10808   ** WAL connection, even if the version fields are currently set to 2.
10809   */
10810   pBt->btsFlags &= ~BTS_NO_WAL;
10811   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10812 
10813   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10814   if( rc==SQLITE_OK ){
10815     u8 *aData = pBt->pPage1->aData;
10816     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10817       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10818       if( rc==SQLITE_OK ){
10819         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10820         if( rc==SQLITE_OK ){
10821           aData[18] = (u8)iVersion;
10822           aData[19] = (u8)iVersion;
10823         }
10824       }
10825     }
10826   }
10827 
10828   pBt->btsFlags &= ~BTS_NO_WAL;
10829   return rc;
10830 }
10831 
10832 /*
10833 ** Return true if the cursor has a hint specified.  This routine is
10834 ** only used from within assert() statements
10835 */
10836 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10837   return (pCsr->hints & mask)!=0;
10838 }
10839 
10840 /*
10841 ** Return true if the given Btree is read-only.
10842 */
10843 int sqlite3BtreeIsReadonly(Btree *p){
10844   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10845 }
10846 
10847 /*
10848 ** Return the size of the header added to each page by this module.
10849 */
10850 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10851 
10852 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10853 /*
10854 ** Return true if the Btree passed as the only argument is sharable.
10855 */
10856 int sqlite3BtreeSharable(Btree *p){
10857   return p->sharable;
10858 }
10859 
10860 /*
10861 ** Return the number of connections to the BtShared object accessed by
10862 ** the Btree handle passed as the only argument. For private caches
10863 ** this is always 1. For shared caches it may be 1 or greater.
10864 */
10865 int sqlite3BtreeConnectionCount(Btree *p){
10866   testcase( p->sharable );
10867   return p->pBt->nRef;
10868 }
10869 #endif
10870