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