xref: /sqlite-3.40.0/src/btree.c (revision dedd51ae)
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 || CORRUPT_DB );
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( 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 #if 0  /* Not required.  Omit for efficiency */
6850   if( pc<hdr+pPage->nCell*2 ){
6851     *pRC = SQLITE_CORRUPT_BKPT;
6852     return;
6853   }
6854 #endif
6855   testcase( pc==(u32)get2byte(&data[hdr+5]) );
6856   testcase( pc+sz==pPage->pBt->usableSize );
6857   if( pc+sz > pPage->pBt->usableSize ){
6858     *pRC = SQLITE_CORRUPT_BKPT;
6859     return;
6860   }
6861   rc = freeSpace(pPage, pc, sz);
6862   if( rc ){
6863     *pRC = rc;
6864     return;
6865   }
6866   pPage->nCell--;
6867   if( pPage->nCell==0 ){
6868     memset(&data[hdr+1], 0, 4);
6869     data[hdr+7] = 0;
6870     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6871     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6872                        - pPage->childPtrSize - 8;
6873   }else{
6874     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6875     put2byte(&data[hdr+3], pPage->nCell);
6876     pPage->nFree += 2;
6877   }
6878 }
6879 
6880 /*
6881 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6882 ** content of the cell.
6883 **
6884 ** If the cell content will fit on the page, then put it there.  If it
6885 ** will not fit, then make a copy of the cell content into pTemp if
6886 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6887 ** in pPage->apOvfl[] and make it point to the cell content (either
6888 ** in pTemp or the original pCell) and also record its index.
6889 ** Allocating a new entry in pPage->aCell[] implies that
6890 ** pPage->nOverflow is incremented.
6891 **
6892 ** *pRC must be SQLITE_OK when this routine is called.
6893 */
6894 static void insertCell(
6895   MemPage *pPage,   /* Page into which we are copying */
6896   int i,            /* New cell becomes the i-th cell of the page */
6897   u8 *pCell,        /* Content of the new cell */
6898   int sz,           /* Bytes of content in pCell */
6899   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6900   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6901   int *pRC          /* Read and write return code from here */
6902 ){
6903   int idx = 0;      /* Where to write new cell content in data[] */
6904   int j;            /* Loop counter */
6905   u8 *data;         /* The content of the whole page */
6906   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6907 
6908   assert( *pRC==SQLITE_OK );
6909   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6910   assert( MX_CELL(pPage->pBt)<=10921 );
6911   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6912   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6913   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6914   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6915   assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6916   assert( pPage->nFree>=0 );
6917   if( pPage->nOverflow || sz+2>pPage->nFree ){
6918     if( pTemp ){
6919       memcpy(pTemp, pCell, sz);
6920       pCell = pTemp;
6921     }
6922     if( iChild ){
6923       put4byte(pCell, iChild);
6924     }
6925     j = pPage->nOverflow++;
6926     /* Comparison against ArraySize-1 since we hold back one extra slot
6927     ** as a contingency.  In other words, never need more than 3 overflow
6928     ** slots but 4 are allocated, just to be safe. */
6929     assert( j < ArraySize(pPage->apOvfl)-1 );
6930     pPage->apOvfl[j] = pCell;
6931     pPage->aiOvfl[j] = (u16)i;
6932 
6933     /* When multiple overflows occur, they are always sequential and in
6934     ** sorted order.  This invariants arise because multiple overflows can
6935     ** only occur when inserting divider cells into the parent page during
6936     ** balancing, and the dividers are adjacent and sorted.
6937     */
6938     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6939     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6940   }else{
6941     int rc = sqlite3PagerWrite(pPage->pDbPage);
6942     if( rc!=SQLITE_OK ){
6943       *pRC = rc;
6944       return;
6945     }
6946     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6947     data = pPage->aData;
6948     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6949     rc = allocateSpace(pPage, sz, &idx);
6950     if( rc ){ *pRC = rc; return; }
6951     /* The allocateSpace() routine guarantees the following properties
6952     ** if it returns successfully */
6953     assert( idx >= 0 );
6954     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6955     assert( idx+sz <= (int)pPage->pBt->usableSize );
6956     pPage->nFree -= (u16)(2 + sz);
6957     if( iChild ){
6958       /* In a corrupt database where an entry in the cell index section of
6959       ** a btree page has a value of 3 or less, the pCell value might point
6960       ** as many as 4 bytes in front of the start of the aData buffer for
6961       ** the source page.  Make sure this does not cause problems by not
6962       ** reading the first 4 bytes */
6963       memcpy(&data[idx+4], pCell+4, sz-4);
6964       put4byte(&data[idx], iChild);
6965     }else{
6966       memcpy(&data[idx], pCell, sz);
6967     }
6968     pIns = pPage->aCellIdx + i*2;
6969     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6970     put2byte(pIns, idx);
6971     pPage->nCell++;
6972     /* increment the cell count */
6973     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6974     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6975 #ifndef SQLITE_OMIT_AUTOVACUUM
6976     if( pPage->pBt->autoVacuum ){
6977       /* The cell may contain a pointer to an overflow page. If so, write
6978       ** the entry for the overflow page into the pointer map.
6979       */
6980       ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6981     }
6982 #endif
6983   }
6984 }
6985 
6986 /*
6987 ** The following parameters determine how many adjacent pages get involved
6988 ** in a balancing operation.  NN is the number of neighbors on either side
6989 ** of the page that participate in the balancing operation.  NB is the
6990 ** total number of pages that participate, including the target page and
6991 ** NN neighbors on either side.
6992 **
6993 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
6994 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6995 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6996 ** The value of NN appears to give the best results overall.
6997 **
6998 ** (Later:) The description above makes it seem as if these values are
6999 ** tunable - as if you could change them and recompile and it would all work.
7000 ** But that is unlikely.  NB has been 3 since the inception of SQLite and
7001 ** we have never tested any other value.
7002 */
7003 #define NN 1             /* Number of neighbors on either side of pPage */
7004 #define NB 3             /* (NN*2+1): Total pages involved in the balance */
7005 
7006 /*
7007 ** A CellArray object contains a cache of pointers and sizes for a
7008 ** consecutive sequence of cells that might be held on multiple pages.
7009 **
7010 ** The cells in this array are the divider cell or cells from the pParent
7011 ** page plus up to three child pages.  There are a total of nCell cells.
7012 **
7013 ** pRef is a pointer to one of the pages that contributes cells.  This is
7014 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7015 ** which should be common to all pages that contribute cells to this array.
7016 **
7017 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
7018 ** cell and the size of each cell.  Some of the apCell[] pointers might refer
7019 ** to overflow cells.  In other words, some apCel[] pointers might not point
7020 ** to content area of the pages.
7021 **
7022 ** A szCell[] of zero means the size of that cell has not yet been computed.
7023 **
7024 ** The cells come from as many as four different pages:
7025 **
7026 **             -----------
7027 **             | Parent  |
7028 **             -----------
7029 **            /     |     \
7030 **           /      |      \
7031 **  ---------   ---------   ---------
7032 **  |Child-1|   |Child-2|   |Child-3|
7033 **  ---------   ---------   ---------
7034 **
7035 ** The order of cells is in the array is for an index btree is:
7036 **
7037 **       1.  All cells from Child-1 in order
7038 **       2.  The first divider cell from Parent
7039 **       3.  All cells from Child-2 in order
7040 **       4.  The second divider cell from Parent
7041 **       5.  All cells from Child-3 in order
7042 **
7043 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7044 ** content exists only in leaves and there are no divider cells.
7045 **
7046 ** For an index btree, the apEnd[] array holds pointer to the end of page
7047 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7048 ** respectively. The ixNx[] array holds the number of cells contained in
7049 ** each of these 5 stages, and all stages to the left.  Hence:
7050 **
7051 **    ixNx[0] = Number of cells in Child-1.
7052 **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7053 **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7054 **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7055 **    ixNx[4] = Total number of cells.
7056 **
7057 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7058 ** are used and they point to the leaf pages only, and the ixNx value are:
7059 **
7060 **    ixNx[0] = Number of cells in Child-1.
7061 **    ixNx[1] = Number of cells in Child-1 and Child-2.
7062 **    ixNx[2] = Total number of cells.
7063 **
7064 ** Sometimes when deleting, a child page can have zero cells.  In those
7065 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7066 ** entries, shift down.  The end result is that each ixNx[] entry should
7067 ** be larger than the previous
7068 */
7069 typedef struct CellArray CellArray;
7070 struct CellArray {
7071   int nCell;              /* Number of cells in apCell[] */
7072   MemPage *pRef;          /* Reference page */
7073   u8 **apCell;            /* All cells begin balanced */
7074   u16 *szCell;            /* Local size of all cells in apCell[] */
7075   u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
7076   int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
7077 };
7078 
7079 /*
7080 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7081 ** computed.
7082 */
7083 static void populateCellCache(CellArray *p, int idx, int N){
7084   assert( idx>=0 && idx+N<=p->nCell );
7085   while( N>0 ){
7086     assert( p->apCell[idx]!=0 );
7087     if( p->szCell[idx]==0 ){
7088       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
7089     }else{
7090       assert( CORRUPT_DB ||
7091               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
7092     }
7093     idx++;
7094     N--;
7095   }
7096 }
7097 
7098 /*
7099 ** Return the size of the Nth element of the cell array
7100 */
7101 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7102   assert( N>=0 && N<p->nCell );
7103   assert( p->szCell[N]==0 );
7104   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7105   return p->szCell[N];
7106 }
7107 static u16 cachedCellSize(CellArray *p, int N){
7108   assert( N>=0 && N<p->nCell );
7109   if( p->szCell[N] ) return p->szCell[N];
7110   return computeCellSize(p, N);
7111 }
7112 
7113 /*
7114 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7115 ** szCell[] array contains the size in bytes of each cell. This function
7116 ** replaces the current contents of page pPg with the contents of the cell
7117 ** array.
7118 **
7119 ** Some of the cells in apCell[] may currently be stored in pPg. This
7120 ** function works around problems caused by this by making a copy of any
7121 ** such cells before overwriting the page data.
7122 **
7123 ** The MemPage.nFree field is invalidated by this function. It is the
7124 ** responsibility of the caller to set it correctly.
7125 */
7126 static int rebuildPage(
7127   CellArray *pCArray,             /* Content to be added to page pPg */
7128   int iFirst,                     /* First cell in pCArray to use */
7129   int nCell,                      /* Final number of cells on page */
7130   MemPage *pPg                    /* The page to be reconstructed */
7131 ){
7132   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
7133   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
7134   const int usableSize = pPg->pBt->usableSize;
7135   u8 * const pEnd = &aData[usableSize];
7136   int i = iFirst;                 /* Which cell to copy from pCArray*/
7137   u32 j;                          /* Start of cell content area */
7138   int iEnd = i+nCell;             /* Loop terminator */
7139   u8 *pCellptr = pPg->aCellIdx;
7140   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7141   u8 *pData;
7142   int k;                          /* Current slot in pCArray->apEnd[] */
7143   u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
7144 
7145   assert( i<iEnd );
7146   j = get2byte(&aData[hdr+5]);
7147   if( j>(u32)usableSize ){ j = 0; }
7148   memcpy(&pTmp[j], &aData[j], usableSize - j);
7149 
7150   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7151   pSrcEnd = pCArray->apEnd[k];
7152 
7153   pData = pEnd;
7154   while( 1/*exit by break*/ ){
7155     u8 *pCell = pCArray->apCell[i];
7156     u16 sz = pCArray->szCell[i];
7157     assert( sz>0 );
7158     if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7159       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7160       pCell = &pTmp[pCell - aData];
7161     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7162            && (uptr)(pCell)<(uptr)pSrcEnd
7163     ){
7164       return SQLITE_CORRUPT_BKPT;
7165     }
7166 
7167     pData -= sz;
7168     put2byte(pCellptr, (pData - aData));
7169     pCellptr += 2;
7170     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7171     memmove(pData, pCell, sz);
7172     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7173     i++;
7174     if( i>=iEnd ) break;
7175     if( pCArray->ixNx[k]<=i ){
7176       k++;
7177       pSrcEnd = pCArray->apEnd[k];
7178     }
7179   }
7180 
7181   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7182   pPg->nCell = nCell;
7183   pPg->nOverflow = 0;
7184 
7185   put2byte(&aData[hdr+1], 0);
7186   put2byte(&aData[hdr+3], pPg->nCell);
7187   put2byte(&aData[hdr+5], pData - aData);
7188   aData[hdr+7] = 0x00;
7189   return SQLITE_OK;
7190 }
7191 
7192 /*
7193 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7194 ** This function attempts to add the cells stored in the array to page pPg.
7195 ** If it cannot (because the page needs to be defragmented before the cells
7196 ** will fit), non-zero is returned. Otherwise, if the cells are added
7197 ** successfully, zero is returned.
7198 **
7199 ** Argument pCellptr points to the first entry in the cell-pointer array
7200 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7201 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7202 ** cell in the array. It is the responsibility of the caller to ensure
7203 ** that it is safe to overwrite this part of the cell-pointer array.
7204 **
7205 ** When this function is called, *ppData points to the start of the
7206 ** content area on page pPg. If the size of the content area is extended,
7207 ** *ppData is updated to point to the new start of the content area
7208 ** before returning.
7209 **
7210 ** Finally, argument pBegin points to the byte immediately following the
7211 ** end of the space required by this page for the cell-pointer area (for
7212 ** all cells - not just those inserted by the current call). If the content
7213 ** area must be extended to before this point in order to accomodate all
7214 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7215 */
7216 static int pageInsertArray(
7217   MemPage *pPg,                   /* Page to add cells to */
7218   u8 *pBegin,                     /* End of cell-pointer array */
7219   u8 **ppData,                    /* IN/OUT: Page content-area pointer */
7220   u8 *pCellptr,                   /* Pointer to cell-pointer area */
7221   int iFirst,                     /* Index of first cell to add */
7222   int nCell,                      /* Number of cells to add to pPg */
7223   CellArray *pCArray              /* Array of cells */
7224 ){
7225   int i = iFirst;                 /* Loop counter - cell index to insert */
7226   u8 *aData = pPg->aData;         /* Complete page */
7227   u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
7228   int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
7229   int k;                          /* Current slot in pCArray->apEnd[] */
7230   u8 *pEnd;                       /* Maximum extent of cell data */
7231   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
7232   if( iEnd<=iFirst ) return 0;
7233   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7234   pEnd = pCArray->apEnd[k];
7235   while( 1 /*Exit by break*/ ){
7236     int sz, rc;
7237     u8 *pSlot;
7238     assert( pCArray->szCell[i]!=0 );
7239     sz = pCArray->szCell[i];
7240     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7241       if( (pData - pBegin)<sz ) return 1;
7242       pData -= sz;
7243       pSlot = pData;
7244     }
7245     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7246     ** database.  But they might for a corrupt database.  Hence use memmove()
7247     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7248     assert( (pSlot+sz)<=pCArray->apCell[i]
7249          || pSlot>=(pCArray->apCell[i]+sz)
7250          || CORRUPT_DB );
7251     if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7252      && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7253     ){
7254       assert( CORRUPT_DB );
7255       (void)SQLITE_CORRUPT_BKPT;
7256       return 1;
7257     }
7258     memmove(pSlot, pCArray->apCell[i], sz);
7259     put2byte(pCellptr, (pSlot - aData));
7260     pCellptr += 2;
7261     i++;
7262     if( i>=iEnd ) break;
7263     if( pCArray->ixNx[k]<=i ){
7264       k++;
7265       pEnd = pCArray->apEnd[k];
7266     }
7267   }
7268   *ppData = pData;
7269   return 0;
7270 }
7271 
7272 /*
7273 ** The pCArray object contains pointers to b-tree cells and their sizes.
7274 **
7275 ** This function adds the space associated with each cell in the array
7276 ** that is currently stored within the body of pPg to the pPg free-list.
7277 ** The cell-pointers and other fields of the page are not updated.
7278 **
7279 ** This function returns the total number of cells added to the free-list.
7280 */
7281 static int pageFreeArray(
7282   MemPage *pPg,                   /* Page to edit */
7283   int iFirst,                     /* First cell to delete */
7284   int nCell,                      /* Cells to delete */
7285   CellArray *pCArray              /* Array of cells */
7286 ){
7287   u8 * const aData = pPg->aData;
7288   u8 * const pEnd = &aData[pPg->pBt->usableSize];
7289   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7290   int nRet = 0;
7291   int i;
7292   int iEnd = iFirst + nCell;
7293   u8 *pFree = 0;
7294   int szFree = 0;
7295 
7296   for(i=iFirst; i<iEnd; i++){
7297     u8 *pCell = pCArray->apCell[i];
7298     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7299       int sz;
7300       /* No need to use cachedCellSize() here.  The sizes of all cells that
7301       ** are to be freed have already been computing while deciding which
7302       ** cells need freeing */
7303       sz = pCArray->szCell[i];  assert( sz>0 );
7304       if( pFree!=(pCell + sz) ){
7305         if( pFree ){
7306           assert( pFree>aData && (pFree - aData)<65536 );
7307           freeSpace(pPg, (u16)(pFree - aData), szFree);
7308         }
7309         pFree = pCell;
7310         szFree = sz;
7311         if( pFree+sz>pEnd ){
7312           return 0;
7313         }
7314       }else{
7315         pFree = pCell;
7316         szFree += sz;
7317       }
7318       nRet++;
7319     }
7320   }
7321   if( pFree ){
7322     assert( pFree>aData && (pFree - aData)<65536 );
7323     freeSpace(pPg, (u16)(pFree - aData), szFree);
7324   }
7325   return nRet;
7326 }
7327 
7328 /*
7329 ** pCArray contains pointers to and sizes of all cells in the page being
7330 ** balanced.  The current page, pPg, has pPg->nCell cells starting with
7331 ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
7332 ** starting at apCell[iNew].
7333 **
7334 ** This routine makes the necessary adjustments to pPg so that it contains
7335 ** the correct cells after being balanced.
7336 **
7337 ** The pPg->nFree field is invalid when this function returns. It is the
7338 ** responsibility of the caller to set it correctly.
7339 */
7340 static int editPage(
7341   MemPage *pPg,                   /* Edit this page */
7342   int iOld,                       /* Index of first cell currently on page */
7343   int iNew,                       /* Index of new first cell on page */
7344   int nNew,                       /* Final number of cells on page */
7345   CellArray *pCArray              /* Array of cells and sizes */
7346 ){
7347   u8 * const aData = pPg->aData;
7348   const int hdr = pPg->hdrOffset;
7349   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7350   int nCell = pPg->nCell;       /* Cells stored on pPg */
7351   u8 *pData;
7352   u8 *pCellptr;
7353   int i;
7354   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7355   int iNewEnd = iNew + nNew;
7356 
7357 #ifdef SQLITE_DEBUG
7358   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7359   memcpy(pTmp, aData, pPg->pBt->usableSize);
7360 #endif
7361 
7362   /* Remove cells from the start and end of the page */
7363   assert( nCell>=0 );
7364   if( iOld<iNew ){
7365     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7366     if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7367     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7368     nCell -= nShift;
7369   }
7370   if( iNewEnd < iOldEnd ){
7371     int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7372     assert( nCell>=nTail );
7373     nCell -= nTail;
7374   }
7375 
7376   pData = &aData[get2byteNotZero(&aData[hdr+5])];
7377   if( pData<pBegin ) goto editpage_fail;
7378   if( pData>pPg->aDataEnd ) goto editpage_fail;
7379 
7380   /* Add cells to the start of the page */
7381   if( iNew<iOld ){
7382     int nAdd = MIN(nNew,iOld-iNew);
7383     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7384     assert( nAdd>=0 );
7385     pCellptr = pPg->aCellIdx;
7386     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7387     if( pageInsertArray(
7388           pPg, pBegin, &pData, pCellptr,
7389           iNew, nAdd, pCArray
7390     ) ) goto editpage_fail;
7391     nCell += nAdd;
7392   }
7393 
7394   /* Add any overflow cells */
7395   for(i=0; i<pPg->nOverflow; i++){
7396     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7397     if( iCell>=0 && iCell<nNew ){
7398       pCellptr = &pPg->aCellIdx[iCell * 2];
7399       if( nCell>iCell ){
7400         memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7401       }
7402       nCell++;
7403       cachedCellSize(pCArray, iCell+iNew);
7404       if( pageInsertArray(
7405             pPg, pBegin, &pData, pCellptr,
7406             iCell+iNew, 1, pCArray
7407       ) ) goto editpage_fail;
7408     }
7409   }
7410 
7411   /* Append cells to the end of the page */
7412   assert( nCell>=0 );
7413   pCellptr = &pPg->aCellIdx[nCell*2];
7414   if( pageInsertArray(
7415         pPg, pBegin, &pData, pCellptr,
7416         iNew+nCell, nNew-nCell, pCArray
7417   ) ) goto editpage_fail;
7418 
7419   pPg->nCell = nNew;
7420   pPg->nOverflow = 0;
7421 
7422   put2byte(&aData[hdr+3], pPg->nCell);
7423   put2byte(&aData[hdr+5], pData - aData);
7424 
7425 #ifdef SQLITE_DEBUG
7426   for(i=0; i<nNew && !CORRUPT_DB; i++){
7427     u8 *pCell = pCArray->apCell[i+iNew];
7428     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7429     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7430       pCell = &pTmp[pCell - aData];
7431     }
7432     assert( 0==memcmp(pCell, &aData[iOff],
7433             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7434   }
7435 #endif
7436 
7437   return SQLITE_OK;
7438  editpage_fail:
7439   /* Unable to edit this page. Rebuild it from scratch instead. */
7440   populateCellCache(pCArray, iNew, nNew);
7441   return rebuildPage(pCArray, iNew, nNew, pPg);
7442 }
7443 
7444 
7445 #ifndef SQLITE_OMIT_QUICKBALANCE
7446 /*
7447 ** This version of balance() handles the common special case where
7448 ** a new entry is being inserted on the extreme right-end of the
7449 ** tree, in other words, when the new entry will become the largest
7450 ** entry in the tree.
7451 **
7452 ** Instead of trying to balance the 3 right-most leaf pages, just add
7453 ** a new page to the right-hand side and put the one new entry in
7454 ** that page.  This leaves the right side of the tree somewhat
7455 ** unbalanced.  But odds are that we will be inserting new entries
7456 ** at the end soon afterwards so the nearly empty page will quickly
7457 ** fill up.  On average.
7458 **
7459 ** pPage is the leaf page which is the right-most page in the tree.
7460 ** pParent is its parent.  pPage must have a single overflow entry
7461 ** which is also the right-most entry on the page.
7462 **
7463 ** The pSpace buffer is used to store a temporary copy of the divider
7464 ** cell that will be inserted into pParent. Such a cell consists of a 4
7465 ** byte page number followed by a variable length integer. In other
7466 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7467 ** least 13 bytes in size.
7468 */
7469 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7470   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7471   MemPage *pNew;                       /* Newly allocated page */
7472   int rc;                              /* Return Code */
7473   Pgno pgnoNew;                        /* Page number of pNew */
7474 
7475   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7476   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7477   assert( pPage->nOverflow==1 );
7478 
7479   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
7480   assert( pPage->nFree>=0 );
7481   assert( pParent->nFree>=0 );
7482 
7483   /* Allocate a new page. This page will become the right-sibling of
7484   ** pPage. Make the parent page writable, so that the new divider cell
7485   ** may be inserted. If both these operations are successful, proceed.
7486   */
7487   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7488 
7489   if( rc==SQLITE_OK ){
7490 
7491     u8 *pOut = &pSpace[4];
7492     u8 *pCell = pPage->apOvfl[0];
7493     u16 szCell = pPage->xCellSize(pPage, pCell);
7494     u8 *pStop;
7495     CellArray b;
7496 
7497     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7498     assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7499     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7500     b.nCell = 1;
7501     b.pRef = pPage;
7502     b.apCell = &pCell;
7503     b.szCell = &szCell;
7504     b.apEnd[0] = pPage->aDataEnd;
7505     b.ixNx[0] = 2;
7506     rc = rebuildPage(&b, 0, 1, pNew);
7507     if( NEVER(rc) ){
7508       releasePage(pNew);
7509       return rc;
7510     }
7511     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7512 
7513     /* If this is an auto-vacuum database, update the pointer map
7514     ** with entries for the new page, and any pointer from the
7515     ** cell on the page to an overflow page. If either of these
7516     ** operations fails, the return code is set, but the contents
7517     ** of the parent page are still manipulated by thh code below.
7518     ** That is Ok, at this point the parent page is guaranteed to
7519     ** be marked as dirty. Returning an error code will cause a
7520     ** rollback, undoing any changes made to the parent page.
7521     */
7522     if( ISAUTOVACUUM ){
7523       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7524       if( szCell>pNew->minLocal ){
7525         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7526       }
7527     }
7528 
7529     /* Create a divider cell to insert into pParent. The divider cell
7530     ** consists of a 4-byte page number (the page number of pPage) and
7531     ** a variable length key value (which must be the same value as the
7532     ** largest key on pPage).
7533     **
7534     ** To find the largest key value on pPage, first find the right-most
7535     ** cell on pPage. The first two fields of this cell are the
7536     ** record-length (a variable length integer at most 32-bits in size)
7537     ** and the key value (a variable length integer, may have any value).
7538     ** The first of the while(...) loops below skips over the record-length
7539     ** field. The second while(...) loop copies the key value from the
7540     ** cell on pPage into the pSpace buffer.
7541     */
7542     pCell = findCell(pPage, pPage->nCell-1);
7543     pStop = &pCell[9];
7544     while( (*(pCell++)&0x80) && pCell<pStop );
7545     pStop = &pCell[9];
7546     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7547 
7548     /* Insert the new divider cell into pParent. */
7549     if( rc==SQLITE_OK ){
7550       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7551                    0, pPage->pgno, &rc);
7552     }
7553 
7554     /* Set the right-child pointer of pParent to point to the new page. */
7555     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7556 
7557     /* Release the reference to the new page. */
7558     releasePage(pNew);
7559   }
7560 
7561   return rc;
7562 }
7563 #endif /* SQLITE_OMIT_QUICKBALANCE */
7564 
7565 #if 0
7566 /*
7567 ** This function does not contribute anything to the operation of SQLite.
7568 ** it is sometimes activated temporarily while debugging code responsible
7569 ** for setting pointer-map entries.
7570 */
7571 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7572   int i, j;
7573   for(i=0; i<nPage; i++){
7574     Pgno n;
7575     u8 e;
7576     MemPage *pPage = apPage[i];
7577     BtShared *pBt = pPage->pBt;
7578     assert( pPage->isInit );
7579 
7580     for(j=0; j<pPage->nCell; j++){
7581       CellInfo info;
7582       u8 *z;
7583 
7584       z = findCell(pPage, j);
7585       pPage->xParseCell(pPage, z, &info);
7586       if( info.nLocal<info.nPayload ){
7587         Pgno ovfl = get4byte(&z[info.nSize-4]);
7588         ptrmapGet(pBt, ovfl, &e, &n);
7589         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7590       }
7591       if( !pPage->leaf ){
7592         Pgno child = get4byte(z);
7593         ptrmapGet(pBt, child, &e, &n);
7594         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7595       }
7596     }
7597     if( !pPage->leaf ){
7598       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7599       ptrmapGet(pBt, child, &e, &n);
7600       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7601     }
7602   }
7603   return 1;
7604 }
7605 #endif
7606 
7607 /*
7608 ** This function is used to copy the contents of the b-tree node stored
7609 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7610 ** the pointer-map entries for each child page are updated so that the
7611 ** parent page stored in the pointer map is page pTo. If pFrom contained
7612 ** any cells with overflow page pointers, then the corresponding pointer
7613 ** map entries are also updated so that the parent page is page pTo.
7614 **
7615 ** If pFrom is currently carrying any overflow cells (entries in the
7616 ** MemPage.apOvfl[] array), they are not copied to pTo.
7617 **
7618 ** Before returning, page pTo is reinitialized using btreeInitPage().
7619 **
7620 ** The performance of this function is not critical. It is only used by
7621 ** the balance_shallower() and balance_deeper() procedures, neither of
7622 ** which are called often under normal circumstances.
7623 */
7624 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7625   if( (*pRC)==SQLITE_OK ){
7626     BtShared * const pBt = pFrom->pBt;
7627     u8 * const aFrom = pFrom->aData;
7628     u8 * const aTo = pTo->aData;
7629     int const iFromHdr = pFrom->hdrOffset;
7630     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7631     int rc;
7632     int iData;
7633 
7634 
7635     assert( pFrom->isInit );
7636     assert( pFrom->nFree>=iToHdr );
7637     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7638 
7639     /* Copy the b-tree node content from page pFrom to page pTo. */
7640     iData = get2byte(&aFrom[iFromHdr+5]);
7641     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7642     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7643 
7644     /* Reinitialize page pTo so that the contents of the MemPage structure
7645     ** match the new data. The initialization of pTo can actually fail under
7646     ** fairly obscure circumstances, even though it is a copy of initialized
7647     ** page pFrom.
7648     */
7649     pTo->isInit = 0;
7650     rc = btreeInitPage(pTo);
7651     if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7652     if( rc!=SQLITE_OK ){
7653       *pRC = rc;
7654       return;
7655     }
7656 
7657     /* If this is an auto-vacuum database, update the pointer-map entries
7658     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7659     */
7660     if( ISAUTOVACUUM ){
7661       *pRC = setChildPtrmaps(pTo);
7662     }
7663   }
7664 }
7665 
7666 /*
7667 ** This routine redistributes cells on the iParentIdx'th child of pParent
7668 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7669 ** same amount of free space. Usually a single sibling on either side of the
7670 ** page are used in the balancing, though both siblings might come from one
7671 ** side if the page is the first or last child of its parent. If the page
7672 ** has fewer than 2 siblings (something which can only happen if the page
7673 ** is a root page or a child of a root page) then all available siblings
7674 ** participate in the balancing.
7675 **
7676 ** The number of siblings of the page might be increased or decreased by
7677 ** one or two in an effort to keep pages nearly full but not over full.
7678 **
7679 ** Note that when this routine is called, some of the cells on the page
7680 ** might not actually be stored in MemPage.aData[]. This can happen
7681 ** if the page is overfull. This routine ensures that all cells allocated
7682 ** to the page and its siblings fit into MemPage.aData[] before returning.
7683 **
7684 ** In the course of balancing the page and its siblings, cells may be
7685 ** inserted into or removed from the parent page (pParent). Doing so
7686 ** may cause the parent page to become overfull or underfull. If this
7687 ** happens, it is the responsibility of the caller to invoke the correct
7688 ** balancing routine to fix this problem (see the balance() routine).
7689 **
7690 ** If this routine fails for any reason, it might leave the database
7691 ** in a corrupted state. So if this routine fails, the database should
7692 ** be rolled back.
7693 **
7694 ** The third argument to this function, aOvflSpace, is a pointer to a
7695 ** buffer big enough to hold one page. If while inserting cells into the parent
7696 ** page (pParent) the parent page becomes overfull, this buffer is
7697 ** used to store the parent's overflow cells. Because this function inserts
7698 ** a maximum of four divider cells into the parent page, and the maximum
7699 ** size of a cell stored within an internal node is always less than 1/4
7700 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7701 ** enough for all overflow cells.
7702 **
7703 ** If aOvflSpace is set to a null pointer, this function returns
7704 ** SQLITE_NOMEM.
7705 */
7706 static int balance_nonroot(
7707   MemPage *pParent,               /* Parent page of siblings being balanced */
7708   int iParentIdx,                 /* Index of "the page" in pParent */
7709   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7710   int isRoot,                     /* True if pParent is a root-page */
7711   int bBulk                       /* True if this call is part of a bulk load */
7712 ){
7713   BtShared *pBt;               /* The whole database */
7714   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7715   int nNew = 0;                /* Number of pages in apNew[] */
7716   int nOld;                    /* Number of pages in apOld[] */
7717   int i, j, k;                 /* Loop counters */
7718   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7719   int rc = SQLITE_OK;          /* The return code */
7720   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7721   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7722   int usableSpace;             /* Bytes in pPage beyond the header */
7723   int pageFlags;               /* Value of pPage->aData[0] */
7724   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7725   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7726   int szScratch;               /* Size of scratch memory requested */
7727   MemPage *apOld[NB];          /* pPage and up to two siblings */
7728   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7729   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7730   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7731   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7732   int cntOld[NB+2];            /* Old index in b.apCell[] */
7733   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7734   u8 *aSpace1;                 /* Space for copies of dividers cells */
7735   Pgno pgno;                   /* Temp var to store a page number in */
7736   u8 abDone[NB+2];             /* True after i'th new page is populated */
7737   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7738   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7739   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7740   CellArray b;                 /* Parsed information on cells being balanced */
7741 
7742   memset(abDone, 0, sizeof(abDone));
7743   memset(&b, 0, sizeof(b));
7744   pBt = pParent->pBt;
7745   assert( sqlite3_mutex_held(pBt->mutex) );
7746   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7747 
7748   /* At this point pParent may have at most one overflow cell. And if
7749   ** this overflow cell is present, it must be the cell with
7750   ** index iParentIdx. This scenario comes about when this function
7751   ** is called (indirectly) from sqlite3BtreeDelete().
7752   */
7753   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7754   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7755 
7756   if( !aOvflSpace ){
7757     return SQLITE_NOMEM_BKPT;
7758   }
7759   assert( pParent->nFree>=0 );
7760 
7761   /* Find the sibling pages to balance. Also locate the cells in pParent
7762   ** that divide the siblings. An attempt is made to find NN siblings on
7763   ** either side of pPage. More siblings are taken from one side, however,
7764   ** if there are fewer than NN siblings on the other side. If pParent
7765   ** has NB or fewer children then all children of pParent are taken.
7766   **
7767   ** This loop also drops the divider cells from the parent page. This
7768   ** way, the remainder of the function does not have to deal with any
7769   ** overflow cells in the parent page, since if any existed they will
7770   ** have already been removed.
7771   */
7772   i = pParent->nOverflow + pParent->nCell;
7773   if( i<2 ){
7774     nxDiv = 0;
7775   }else{
7776     assert( bBulk==0 || bBulk==1 );
7777     if( iParentIdx==0 ){
7778       nxDiv = 0;
7779     }else if( iParentIdx==i ){
7780       nxDiv = i-2+bBulk;
7781     }else{
7782       nxDiv = iParentIdx-1;
7783     }
7784     i = 2-bBulk;
7785   }
7786   nOld = i+1;
7787   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7788     pRight = &pParent->aData[pParent->hdrOffset+8];
7789   }else{
7790     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7791   }
7792   pgno = get4byte(pRight);
7793   while( 1 ){
7794     if( rc==SQLITE_OK ){
7795       rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7796     }
7797     if( rc ){
7798       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7799       goto balance_cleanup;
7800     }
7801     if( apOld[i]->nFree<0 ){
7802       rc = btreeComputeFreeSpace(apOld[i]);
7803       if( rc ){
7804         memset(apOld, 0, (i)*sizeof(MemPage*));
7805         goto balance_cleanup;
7806       }
7807     }
7808     nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
7809     if( (i--)==0 ) break;
7810 
7811     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7812       apDiv[i] = pParent->apOvfl[0];
7813       pgno = get4byte(apDiv[i]);
7814       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7815       pParent->nOverflow = 0;
7816     }else{
7817       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7818       pgno = get4byte(apDiv[i]);
7819       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7820 
7821       /* Drop the cell from the parent page. apDiv[i] still points to
7822       ** the cell within the parent, even though it has been dropped.
7823       ** This is safe because dropping a cell only overwrites the first
7824       ** four bytes of it, and this function does not need the first
7825       ** four bytes of the divider cell. So the pointer is safe to use
7826       ** later on.
7827       **
7828       ** But not if we are in secure-delete mode. In secure-delete mode,
7829       ** the dropCell() routine will overwrite the entire cell with zeroes.
7830       ** In this case, temporarily copy the cell into the aOvflSpace[]
7831       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7832       ** is allocated.  */
7833       if( pBt->btsFlags & BTS_FAST_SECURE ){
7834         int iOff;
7835 
7836         /* If the following if() condition is not true, the db is corrupted.
7837         ** The call to dropCell() below will detect this.  */
7838         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7839         if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7840           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7841           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7842         }
7843       }
7844       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7845     }
7846   }
7847 
7848   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7849   ** alignment */
7850   nMaxCells = (nMaxCells + 3)&~3;
7851 
7852   /*
7853   ** Allocate space for memory structures
7854   */
7855   szScratch =
7856        nMaxCells*sizeof(u8*)                       /* b.apCell */
7857      + nMaxCells*sizeof(u16)                       /* b.szCell */
7858      + pBt->pageSize;                              /* aSpace1 */
7859 
7860   assert( szScratch<=7*(int)pBt->pageSize );
7861   b.apCell = sqlite3StackAllocRaw(0, szScratch );
7862   if( b.apCell==0 ){
7863     rc = SQLITE_NOMEM_BKPT;
7864     goto balance_cleanup;
7865   }
7866   b.szCell = (u16*)&b.apCell[nMaxCells];
7867   aSpace1 = (u8*)&b.szCell[nMaxCells];
7868   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7869 
7870   /*
7871   ** Load pointers to all cells on sibling pages and the divider cells
7872   ** into the local b.apCell[] array.  Make copies of the divider cells
7873   ** into space obtained from aSpace1[]. The divider cells have already
7874   ** been removed from pParent.
7875   **
7876   ** If the siblings are on leaf pages, then the child pointers of the
7877   ** divider cells are stripped from the cells before they are copied
7878   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7879   ** child pointers.  If siblings are not leaves, then all cell in
7880   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7881   ** are alike.
7882   **
7883   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7884   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7885   */
7886   b.pRef = apOld[0];
7887   leafCorrection = b.pRef->leaf*4;
7888   leafData = b.pRef->intKeyLeaf;
7889   for(i=0; i<nOld; i++){
7890     MemPage *pOld = apOld[i];
7891     int limit = pOld->nCell;
7892     u8 *aData = pOld->aData;
7893     u16 maskPage = pOld->maskPage;
7894     u8 *piCell = aData + pOld->cellOffset;
7895     u8 *piEnd;
7896     VVA_ONLY( int nCellAtStart = b.nCell; )
7897 
7898     /* Verify that all sibling pages are of the same "type" (table-leaf,
7899     ** table-interior, index-leaf, or index-interior).
7900     */
7901     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7902       rc = SQLITE_CORRUPT_BKPT;
7903       goto balance_cleanup;
7904     }
7905 
7906     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7907     ** contains overflow cells, include them in the b.apCell[] array
7908     ** in the correct spot.
7909     **
7910     ** Note that when there are multiple overflow cells, it is always the
7911     ** case that they are sequential and adjacent.  This invariant arises
7912     ** because multiple overflows can only occurs when inserting divider
7913     ** cells into a parent on a prior balance, and divider cells are always
7914     ** adjacent and are inserted in order.  There is an assert() tagged
7915     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7916     ** invariant.
7917     **
7918     ** This must be done in advance.  Once the balance starts, the cell
7919     ** offset section of the btree page will be overwritten and we will no
7920     ** long be able to find the cells if a pointer to each cell is not saved
7921     ** first.
7922     */
7923     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7924     if( pOld->nOverflow>0 ){
7925       if( NEVER(limit<pOld->aiOvfl[0]) ){
7926         rc = SQLITE_CORRUPT_BKPT;
7927         goto balance_cleanup;
7928       }
7929       limit = pOld->aiOvfl[0];
7930       for(j=0; j<limit; j++){
7931         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7932         piCell += 2;
7933         b.nCell++;
7934       }
7935       for(k=0; k<pOld->nOverflow; k++){
7936         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7937         b.apCell[b.nCell] = pOld->apOvfl[k];
7938         b.nCell++;
7939       }
7940     }
7941     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7942     while( piCell<piEnd ){
7943       assert( b.nCell<nMaxCells );
7944       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7945       piCell += 2;
7946       b.nCell++;
7947     }
7948     assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7949 
7950     cntOld[i] = b.nCell;
7951     if( i<nOld-1 && !leafData){
7952       u16 sz = (u16)szNew[i];
7953       u8 *pTemp;
7954       assert( b.nCell<nMaxCells );
7955       b.szCell[b.nCell] = sz;
7956       pTemp = &aSpace1[iSpace1];
7957       iSpace1 += sz;
7958       assert( sz<=pBt->maxLocal+23 );
7959       assert( iSpace1 <= (int)pBt->pageSize );
7960       memcpy(pTemp, apDiv[i], sz);
7961       b.apCell[b.nCell] = pTemp+leafCorrection;
7962       assert( leafCorrection==0 || leafCorrection==4 );
7963       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7964       if( !pOld->leaf ){
7965         assert( leafCorrection==0 );
7966         assert( pOld->hdrOffset==0 || CORRUPT_DB );
7967         /* The right pointer of the child page pOld becomes the left
7968         ** pointer of the divider cell */
7969         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7970       }else{
7971         assert( leafCorrection==4 );
7972         while( b.szCell[b.nCell]<4 ){
7973           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7974           ** does exist, pad it with 0x00 bytes. */
7975           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7976           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7977           aSpace1[iSpace1++] = 0x00;
7978           b.szCell[b.nCell]++;
7979         }
7980       }
7981       b.nCell++;
7982     }
7983   }
7984 
7985   /*
7986   ** Figure out the number of pages needed to hold all b.nCell cells.
7987   ** Store this number in "k".  Also compute szNew[] which is the total
7988   ** size of all cells on the i-th page and cntNew[] which is the index
7989   ** in b.apCell[] of the cell that divides page i from page i+1.
7990   ** cntNew[k] should equal b.nCell.
7991   **
7992   ** Values computed by this block:
7993   **
7994   **           k: The total number of sibling pages
7995   **    szNew[i]: Spaced used on the i-th sibling page.
7996   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7997   **              the right of the i-th sibling page.
7998   ** usableSpace: Number of bytes of space available on each sibling.
7999   **
8000   */
8001   usableSpace = pBt->usableSize - 12 + leafCorrection;
8002   for(i=k=0; i<nOld; i++, k++){
8003     MemPage *p = apOld[i];
8004     b.apEnd[k] = p->aDataEnd;
8005     b.ixNx[k] = cntOld[i];
8006     if( k && b.ixNx[k]==b.ixNx[k-1] ){
8007       k--;  /* Omit b.ixNx[] entry for child pages with no cells */
8008     }
8009     if( !leafData ){
8010       k++;
8011       b.apEnd[k] = pParent->aDataEnd;
8012       b.ixNx[k] = cntOld[i]+1;
8013     }
8014     assert( p->nFree>=0 );
8015     szNew[i] = usableSpace - p->nFree;
8016     for(j=0; j<p->nOverflow; j++){
8017       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8018     }
8019     cntNew[i] = cntOld[i];
8020   }
8021   k = nOld;
8022   for(i=0; i<k; i++){
8023     int sz;
8024     while( szNew[i]>usableSpace ){
8025       if( i+1>=k ){
8026         k = i+2;
8027         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8028         szNew[k-1] = 0;
8029         cntNew[k-1] = b.nCell;
8030       }
8031       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8032       szNew[i] -= sz;
8033       if( !leafData ){
8034         if( cntNew[i]<b.nCell ){
8035           sz = 2 + cachedCellSize(&b, cntNew[i]);
8036         }else{
8037           sz = 0;
8038         }
8039       }
8040       szNew[i+1] += sz;
8041       cntNew[i]--;
8042     }
8043     while( cntNew[i]<b.nCell ){
8044       sz = 2 + cachedCellSize(&b, cntNew[i]);
8045       if( szNew[i]+sz>usableSpace ) break;
8046       szNew[i] += sz;
8047       cntNew[i]++;
8048       if( !leafData ){
8049         if( cntNew[i]<b.nCell ){
8050           sz = 2 + cachedCellSize(&b, cntNew[i]);
8051         }else{
8052           sz = 0;
8053         }
8054       }
8055       szNew[i+1] -= sz;
8056     }
8057     if( cntNew[i]>=b.nCell ){
8058       k = i+1;
8059     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8060       rc = SQLITE_CORRUPT_BKPT;
8061       goto balance_cleanup;
8062     }
8063   }
8064 
8065   /*
8066   ** The packing computed by the previous block is biased toward the siblings
8067   ** on the left side (siblings with smaller keys). The left siblings are
8068   ** always nearly full, while the right-most sibling might be nearly empty.
8069   ** The next block of code attempts to adjust the packing of siblings to
8070   ** get a better balance.
8071   **
8072   ** This adjustment is more than an optimization.  The packing above might
8073   ** be so out of balance as to be illegal.  For example, the right-most
8074   ** sibling might be completely empty.  This adjustment is not optional.
8075   */
8076   for(i=k-1; i>0; i--){
8077     int szRight = szNew[i];  /* Size of sibling on the right */
8078     int szLeft = szNew[i-1]; /* Size of sibling on the left */
8079     int r;              /* Index of right-most cell in left sibling */
8080     int d;              /* Index of first cell to the left of right sibling */
8081 
8082     r = cntNew[i-1] - 1;
8083     d = r + 1 - leafData;
8084     (void)cachedCellSize(&b, d);
8085     do{
8086       assert( d<nMaxCells );
8087       assert( r<nMaxCells );
8088       (void)cachedCellSize(&b, r);
8089       if( szRight!=0
8090        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
8091         break;
8092       }
8093       szRight += b.szCell[d] + 2;
8094       szLeft -= b.szCell[r] + 2;
8095       cntNew[i-1] = r;
8096       r--;
8097       d--;
8098     }while( r>=0 );
8099     szNew[i] = szRight;
8100     szNew[i-1] = szLeft;
8101     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8102       rc = SQLITE_CORRUPT_BKPT;
8103       goto balance_cleanup;
8104     }
8105   }
8106 
8107   /* Sanity check:  For a non-corrupt database file one of the follwing
8108   ** must be true:
8109   **    (1) We found one or more cells (cntNew[0])>0), or
8110   **    (2) pPage is a virtual root page.  A virtual root page is when
8111   **        the real root page is page 1 and we are the only child of
8112   **        that page.
8113   */
8114   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8115   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
8116     apOld[0]->pgno, apOld[0]->nCell,
8117     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8118     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8119   ));
8120 
8121   /*
8122   ** Allocate k new pages.  Reuse old pages where possible.
8123   */
8124   pageFlags = apOld[0]->aData[0];
8125   for(i=0; i<k; i++){
8126     MemPage *pNew;
8127     if( i<nOld ){
8128       pNew = apNew[i] = apOld[i];
8129       apOld[i] = 0;
8130       rc = sqlite3PagerWrite(pNew->pDbPage);
8131       nNew++;
8132       if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8133        && rc==SQLITE_OK
8134       ){
8135         rc = SQLITE_CORRUPT_BKPT;
8136       }
8137       if( rc ) goto balance_cleanup;
8138     }else{
8139       assert( i>0 );
8140       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8141       if( rc ) goto balance_cleanup;
8142       zeroPage(pNew, pageFlags);
8143       apNew[i] = pNew;
8144       nNew++;
8145       cntOld[i] = b.nCell;
8146 
8147       /* Set the pointer-map entry for the new sibling page. */
8148       if( ISAUTOVACUUM ){
8149         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8150         if( rc!=SQLITE_OK ){
8151           goto balance_cleanup;
8152         }
8153       }
8154     }
8155   }
8156 
8157   /*
8158   ** Reassign page numbers so that the new pages are in ascending order.
8159   ** This helps to keep entries in the disk file in order so that a scan
8160   ** of the table is closer to a linear scan through the file. That in turn
8161   ** helps the operating system to deliver pages from the disk more rapidly.
8162   **
8163   ** An O(n^2) insertion sort algorithm is used, but since n is never more
8164   ** than (NB+2) (a small constant), that should not be a problem.
8165   **
8166   ** When NB==3, this one optimization makes the database about 25% faster
8167   ** for large insertions and deletions.
8168   */
8169   for(i=0; i<nNew; i++){
8170     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8171     aPgFlags[i] = apNew[i]->pDbPage->flags;
8172     for(j=0; j<i; j++){
8173       if( NEVER(aPgno[j]==aPgno[i]) ){
8174         /* This branch is taken if the set of sibling pages somehow contains
8175         ** duplicate entries. This can happen if the database is corrupt.
8176         ** It would be simpler to detect this as part of the loop below, but
8177         ** we do the detection here in order to avoid populating the pager
8178         ** cache with two separate objects associated with the same
8179         ** page number.  */
8180         assert( CORRUPT_DB );
8181         rc = SQLITE_CORRUPT_BKPT;
8182         goto balance_cleanup;
8183       }
8184     }
8185   }
8186   for(i=0; i<nNew; i++){
8187     int iBest = 0;                /* aPgno[] index of page number to use */
8188     for(j=1; j<nNew; j++){
8189       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8190     }
8191     pgno = aPgOrder[iBest];
8192     aPgOrder[iBest] = 0xffffffff;
8193     if( iBest!=i ){
8194       if( iBest>i ){
8195         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8196       }
8197       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8198       apNew[i]->pgno = pgno;
8199     }
8200   }
8201 
8202   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8203          "%d(%d nc=%d) %d(%d nc=%d)\n",
8204     apNew[0]->pgno, szNew[0], cntNew[0],
8205     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8206     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8207     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8208     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8209     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8210     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8211     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8212     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8213   ));
8214 
8215   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8216   assert( nNew>=1 && nNew<=ArraySize(apNew) );
8217   assert( apNew[nNew-1]!=0 );
8218   put4byte(pRight, apNew[nNew-1]->pgno);
8219 
8220   /* If the sibling pages are not leaves, ensure that the right-child pointer
8221   ** of the right-most new sibling page is set to the value that was
8222   ** originally in the same field of the right-most old sibling page. */
8223   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8224     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8225     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8226   }
8227 
8228   /* Make any required updates to pointer map entries associated with
8229   ** cells stored on sibling pages following the balance operation. Pointer
8230   ** map entries associated with divider cells are set by the insertCell()
8231   ** routine. The associated pointer map entries are:
8232   **
8233   **   a) if the cell contains a reference to an overflow chain, the
8234   **      entry associated with the first page in the overflow chain, and
8235   **
8236   **   b) if the sibling pages are not leaves, the child page associated
8237   **      with the cell.
8238   **
8239   ** If the sibling pages are not leaves, then the pointer map entry
8240   ** associated with the right-child of each sibling may also need to be
8241   ** updated. This happens below, after the sibling pages have been
8242   ** populated, not here.
8243   */
8244   if( ISAUTOVACUUM ){
8245     MemPage *pOld;
8246     MemPage *pNew = pOld = apNew[0];
8247     int cntOldNext = pNew->nCell + pNew->nOverflow;
8248     int iNew = 0;
8249     int iOld = 0;
8250 
8251     for(i=0; i<b.nCell; i++){
8252       u8 *pCell = b.apCell[i];
8253       while( i==cntOldNext ){
8254         iOld++;
8255         assert( iOld<nNew || iOld<nOld );
8256         assert( iOld>=0 && iOld<NB );
8257         pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8258         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8259       }
8260       if( i==cntNew[iNew] ){
8261         pNew = apNew[++iNew];
8262         if( !leafData ) continue;
8263       }
8264 
8265       /* Cell pCell is destined for new sibling page pNew. Originally, it
8266       ** was either part of sibling page iOld (possibly an overflow cell),
8267       ** or else the divider cell to the left of sibling page iOld. So,
8268       ** if sibling page iOld had the same page number as pNew, and if
8269       ** pCell really was a part of sibling page iOld (not a divider or
8270       ** overflow cell), we can skip updating the pointer map entries.  */
8271       if( iOld>=nNew
8272        || pNew->pgno!=aPgno[iOld]
8273        || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8274       ){
8275         if( !leafCorrection ){
8276           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8277         }
8278         if( cachedCellSize(&b,i)>pNew->minLocal ){
8279           ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8280         }
8281         if( rc ) goto balance_cleanup;
8282       }
8283     }
8284   }
8285 
8286   /* Insert new divider cells into pParent. */
8287   for(i=0; i<nNew-1; i++){
8288     u8 *pCell;
8289     u8 *pTemp;
8290     int sz;
8291     u8 *pSrcEnd;
8292     MemPage *pNew = apNew[i];
8293     j = cntNew[i];
8294 
8295     assert( j<nMaxCells );
8296     assert( b.apCell[j]!=0 );
8297     pCell = b.apCell[j];
8298     sz = b.szCell[j] + leafCorrection;
8299     pTemp = &aOvflSpace[iOvflSpace];
8300     if( !pNew->leaf ){
8301       memcpy(&pNew->aData[8], pCell, 4);
8302     }else if( leafData ){
8303       /* If the tree is a leaf-data tree, and the siblings are leaves,
8304       ** then there is no divider cell in b.apCell[]. Instead, the divider
8305       ** cell consists of the integer key for the right-most cell of
8306       ** the sibling-page assembled above only.
8307       */
8308       CellInfo info;
8309       j--;
8310       pNew->xParseCell(pNew, b.apCell[j], &info);
8311       pCell = pTemp;
8312       sz = 4 + putVarint(&pCell[4], info.nKey);
8313       pTemp = 0;
8314     }else{
8315       pCell -= 4;
8316       /* Obscure case for non-leaf-data trees: If the cell at pCell was
8317       ** previously stored on a leaf node, and its reported size was 4
8318       ** bytes, then it may actually be smaller than this
8319       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8320       ** any cell). But it is important to pass the correct size to
8321       ** insertCell(), so reparse the cell now.
8322       **
8323       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8324       ** and WITHOUT ROWID tables with exactly one column which is the
8325       ** primary key.
8326       */
8327       if( b.szCell[j]==4 ){
8328         assert(leafCorrection==4);
8329         sz = pParent->xCellSize(pParent, pCell);
8330       }
8331     }
8332     iOvflSpace += sz;
8333     assert( sz<=pBt->maxLocal+23 );
8334     assert( iOvflSpace <= (int)pBt->pageSize );
8335     for(k=0; b.ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
8336     pSrcEnd = b.apEnd[k];
8337     if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8338       rc = SQLITE_CORRUPT_BKPT;
8339       goto balance_cleanup;
8340     }
8341     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8342     if( rc!=SQLITE_OK ) goto balance_cleanup;
8343     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8344   }
8345 
8346   /* Now update the actual sibling pages. The order in which they are updated
8347   ** is important, as this code needs to avoid disrupting any page from which
8348   ** cells may still to be read. In practice, this means:
8349   **
8350   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8351   **      then it is not safe to update page apNew[iPg] until after
8352   **      the left-hand sibling apNew[iPg-1] has been updated.
8353   **
8354   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8355   **      then it is not safe to update page apNew[iPg] until after
8356   **      the right-hand sibling apNew[iPg+1] has been updated.
8357   **
8358   ** If neither of the above apply, the page is safe to update.
8359   **
8360   ** The iPg value in the following loop starts at nNew-1 goes down
8361   ** to 0, then back up to nNew-1 again, thus making two passes over
8362   ** the pages.  On the initial downward pass, only condition (1) above
8363   ** needs to be tested because (2) will always be true from the previous
8364   ** step.  On the upward pass, both conditions are always true, so the
8365   ** upwards pass simply processes pages that were missed on the downward
8366   ** pass.
8367   */
8368   for(i=1-nNew; i<nNew; i++){
8369     int iPg = i<0 ? -i : i;
8370     assert( iPg>=0 && iPg<nNew );
8371     if( abDone[iPg] ) continue;         /* Skip pages already processed */
8372     if( i>=0                            /* On the upwards pass, or... */
8373      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
8374     ){
8375       int iNew;
8376       int iOld;
8377       int nNewCell;
8378 
8379       /* Verify condition (1):  If cells are moving left, update iPg
8380       ** only after iPg-1 has already been updated. */
8381       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8382 
8383       /* Verify condition (2):  If cells are moving right, update iPg
8384       ** only after iPg+1 has already been updated. */
8385       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8386 
8387       if( iPg==0 ){
8388         iNew = iOld = 0;
8389         nNewCell = cntNew[0];
8390       }else{
8391         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8392         iNew = cntNew[iPg-1] + !leafData;
8393         nNewCell = cntNew[iPg] - iNew;
8394       }
8395 
8396       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8397       if( rc ) goto balance_cleanup;
8398       abDone[iPg]++;
8399       apNew[iPg]->nFree = usableSpace-szNew[iPg];
8400       assert( apNew[iPg]->nOverflow==0 );
8401       assert( apNew[iPg]->nCell==nNewCell );
8402     }
8403   }
8404 
8405   /* All pages have been processed exactly once */
8406   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8407 
8408   assert( nOld>0 );
8409   assert( nNew>0 );
8410 
8411   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8412     /* The root page of the b-tree now contains no cells. The only sibling
8413     ** page is the right-child of the parent. Copy the contents of the
8414     ** child page into the parent, decreasing the overall height of the
8415     ** b-tree structure by one. This is described as the "balance-shallower"
8416     ** sub-algorithm in some documentation.
8417     **
8418     ** If this is an auto-vacuum database, the call to copyNodeContent()
8419     ** sets all pointer-map entries corresponding to database image pages
8420     ** for which the pointer is stored within the content being copied.
8421     **
8422     ** It is critical that the child page be defragmented before being
8423     ** copied into the parent, because if the parent is page 1 then it will
8424     ** by smaller than the child due to the database header, and so all the
8425     ** free space needs to be up front.
8426     */
8427     assert( nNew==1 || CORRUPT_DB );
8428     rc = defragmentPage(apNew[0], -1);
8429     testcase( rc!=SQLITE_OK );
8430     assert( apNew[0]->nFree ==
8431         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8432           - apNew[0]->nCell*2)
8433       || rc!=SQLITE_OK
8434     );
8435     copyNodeContent(apNew[0], pParent, &rc);
8436     freePage(apNew[0], &rc);
8437   }else if( ISAUTOVACUUM && !leafCorrection ){
8438     /* Fix the pointer map entries associated with the right-child of each
8439     ** sibling page. All other pointer map entries have already been taken
8440     ** care of.  */
8441     for(i=0; i<nNew; i++){
8442       u32 key = get4byte(&apNew[i]->aData[8]);
8443       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8444     }
8445   }
8446 
8447   assert( pParent->isInit );
8448   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8449           nOld, nNew, b.nCell));
8450 
8451   /* Free any old pages that were not reused as new pages.
8452   */
8453   for(i=nNew; i<nOld; i++){
8454     freePage(apOld[i], &rc);
8455   }
8456 
8457 #if 0
8458   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8459     /* The ptrmapCheckPages() contains assert() statements that verify that
8460     ** all pointer map pages are set correctly. This is helpful while
8461     ** debugging. This is usually disabled because a corrupt database may
8462     ** cause an assert() statement to fail.  */
8463     ptrmapCheckPages(apNew, nNew);
8464     ptrmapCheckPages(&pParent, 1);
8465   }
8466 #endif
8467 
8468   /*
8469   ** Cleanup before returning.
8470   */
8471 balance_cleanup:
8472   sqlite3StackFree(0, b.apCell);
8473   for(i=0; i<nOld; i++){
8474     releasePage(apOld[i]);
8475   }
8476   for(i=0; i<nNew; i++){
8477     releasePage(apNew[i]);
8478   }
8479 
8480   return rc;
8481 }
8482 
8483 
8484 /*
8485 ** This function is called when the root page of a b-tree structure is
8486 ** overfull (has one or more overflow pages).
8487 **
8488 ** A new child page is allocated and the contents of the current root
8489 ** page, including overflow cells, are copied into the child. The root
8490 ** page is then overwritten to make it an empty page with the right-child
8491 ** pointer pointing to the new page.
8492 **
8493 ** Before returning, all pointer-map entries corresponding to pages
8494 ** that the new child-page now contains pointers to are updated. The
8495 ** entry corresponding to the new right-child pointer of the root
8496 ** page is also updated.
8497 **
8498 ** If successful, *ppChild is set to contain a reference to the child
8499 ** page and SQLITE_OK is returned. In this case the caller is required
8500 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8501 ** an error code is returned and *ppChild is set to 0.
8502 */
8503 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8504   int rc;                        /* Return value from subprocedures */
8505   MemPage *pChild = 0;           /* Pointer to a new child page */
8506   Pgno pgnoChild = 0;            /* Page number of the new child page */
8507   BtShared *pBt = pRoot->pBt;    /* The BTree */
8508 
8509   assert( pRoot->nOverflow>0 );
8510   assert( sqlite3_mutex_held(pBt->mutex) );
8511 
8512   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8513   ** page that will become the new right-child of pPage. Copy the contents
8514   ** of the node stored on pRoot into the new child page.
8515   */
8516   rc = sqlite3PagerWrite(pRoot->pDbPage);
8517   if( rc==SQLITE_OK ){
8518     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8519     copyNodeContent(pRoot, pChild, &rc);
8520     if( ISAUTOVACUUM ){
8521       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8522     }
8523   }
8524   if( rc ){
8525     *ppChild = 0;
8526     releasePage(pChild);
8527     return rc;
8528   }
8529   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8530   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8531   assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8532 
8533   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8534 
8535   /* Copy the overflow cells from pRoot to pChild */
8536   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8537          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8538   memcpy(pChild->apOvfl, pRoot->apOvfl,
8539          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8540   pChild->nOverflow = pRoot->nOverflow;
8541 
8542   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8543   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8544   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8545 
8546   *ppChild = pChild;
8547   return SQLITE_OK;
8548 }
8549 
8550 /*
8551 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8552 ** on the same B-tree as pCur.
8553 **
8554 ** This can occur if a database is corrupt with two or more SQL tables
8555 ** pointing to the same b-tree.  If an insert occurs on one SQL table
8556 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8557 ** table linked to the same b-tree.  If the secondary insert causes a
8558 ** rebalance, that can change content out from under the cursor on the
8559 ** first SQL table, violating invariants on the first insert.
8560 */
8561 static int anotherValidCursor(BtCursor *pCur){
8562   BtCursor *pOther;
8563   for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8564     if( pOther!=pCur
8565      && pOther->eState==CURSOR_VALID
8566      && pOther->pPage==pCur->pPage
8567     ){
8568       return SQLITE_CORRUPT_BKPT;
8569     }
8570   }
8571   return SQLITE_OK;
8572 }
8573 
8574 /*
8575 ** The page that pCur currently points to has just been modified in
8576 ** some way. This function figures out if this modification means the
8577 ** tree needs to be balanced, and if so calls the appropriate balancing
8578 ** routine. Balancing routines are:
8579 **
8580 **   balance_quick()
8581 **   balance_deeper()
8582 **   balance_nonroot()
8583 */
8584 static int balance(BtCursor *pCur){
8585   int rc = SQLITE_OK;
8586   const int nMin = pCur->pBt->usableSize * 2 / 3;
8587   u8 aBalanceQuickSpace[13];
8588   u8 *pFree = 0;
8589 
8590   VVA_ONLY( int balance_quick_called = 0 );
8591   VVA_ONLY( int balance_deeper_called = 0 );
8592 
8593   do {
8594     int iPage;
8595     MemPage *pPage = pCur->pPage;
8596 
8597     if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8598     if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8599       break;
8600     }else if( (iPage = pCur->iPage)==0 ){
8601       if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8602         /* The root page of the b-tree is overfull. In this case call the
8603         ** balance_deeper() function to create a new child for the root-page
8604         ** and copy the current contents of the root-page to it. The
8605         ** next iteration of the do-loop will balance the child page.
8606         */
8607         assert( balance_deeper_called==0 );
8608         VVA_ONLY( balance_deeper_called++ );
8609         rc = balance_deeper(pPage, &pCur->apPage[1]);
8610         if( rc==SQLITE_OK ){
8611           pCur->iPage = 1;
8612           pCur->ix = 0;
8613           pCur->aiIdx[0] = 0;
8614           pCur->apPage[0] = pPage;
8615           pCur->pPage = pCur->apPage[1];
8616           assert( pCur->pPage->nOverflow );
8617         }
8618       }else{
8619         break;
8620       }
8621     }else{
8622       MemPage * const pParent = pCur->apPage[iPage-1];
8623       int const iIdx = pCur->aiIdx[iPage-1];
8624 
8625       rc = sqlite3PagerWrite(pParent->pDbPage);
8626       if( rc==SQLITE_OK && pParent->nFree<0 ){
8627         rc = btreeComputeFreeSpace(pParent);
8628       }
8629       if( rc==SQLITE_OK ){
8630 #ifndef SQLITE_OMIT_QUICKBALANCE
8631         if( pPage->intKeyLeaf
8632          && pPage->nOverflow==1
8633          && pPage->aiOvfl[0]==pPage->nCell
8634          && pParent->pgno!=1
8635          && pParent->nCell==iIdx
8636         ){
8637           /* Call balance_quick() to create a new sibling of pPage on which
8638           ** to store the overflow cell. balance_quick() inserts a new cell
8639           ** into pParent, which may cause pParent overflow. If this
8640           ** happens, the next iteration of the do-loop will balance pParent
8641           ** use either balance_nonroot() or balance_deeper(). Until this
8642           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8643           ** buffer.
8644           **
8645           ** The purpose of the following assert() is to check that only a
8646           ** single call to balance_quick() is made for each call to this
8647           ** function. If this were not verified, a subtle bug involving reuse
8648           ** of the aBalanceQuickSpace[] might sneak in.
8649           */
8650           assert( balance_quick_called==0 );
8651           VVA_ONLY( balance_quick_called++ );
8652           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8653         }else
8654 #endif
8655         {
8656           /* In this case, call balance_nonroot() to redistribute cells
8657           ** between pPage and up to 2 of its sibling pages. This involves
8658           ** modifying the contents of pParent, which may cause pParent to
8659           ** become overfull or underfull. The next iteration of the do-loop
8660           ** will balance the parent page to correct this.
8661           **
8662           ** If the parent page becomes overfull, the overflow cell or cells
8663           ** are stored in the pSpace buffer allocated immediately below.
8664           ** A subsequent iteration of the do-loop will deal with this by
8665           ** calling balance_nonroot() (balance_deeper() may be called first,
8666           ** but it doesn't deal with overflow cells - just moves them to a
8667           ** different page). Once this subsequent call to balance_nonroot()
8668           ** has completed, it is safe to release the pSpace buffer used by
8669           ** the previous call, as the overflow cell data will have been
8670           ** copied either into the body of a database page or into the new
8671           ** pSpace buffer passed to the latter call to balance_nonroot().
8672           */
8673           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8674           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8675                                pCur->hints&BTREE_BULKLOAD);
8676           if( pFree ){
8677             /* If pFree is not NULL, it points to the pSpace buffer used
8678             ** by a previous call to balance_nonroot(). Its contents are
8679             ** now stored either on real database pages or within the
8680             ** new pSpace buffer, so it may be safely freed here. */
8681             sqlite3PageFree(pFree);
8682           }
8683 
8684           /* The pSpace buffer will be freed after the next call to
8685           ** balance_nonroot(), or just before this function returns, whichever
8686           ** comes first. */
8687           pFree = pSpace;
8688         }
8689       }
8690 
8691       pPage->nOverflow = 0;
8692 
8693       /* The next iteration of the do-loop balances the parent page. */
8694       releasePage(pPage);
8695       pCur->iPage--;
8696       assert( pCur->iPage>=0 );
8697       pCur->pPage = pCur->apPage[pCur->iPage];
8698     }
8699   }while( rc==SQLITE_OK );
8700 
8701   if( pFree ){
8702     sqlite3PageFree(pFree);
8703   }
8704   return rc;
8705 }
8706 
8707 /* Overwrite content from pX into pDest.  Only do the write if the
8708 ** content is different from what is already there.
8709 */
8710 static int btreeOverwriteContent(
8711   MemPage *pPage,           /* MemPage on which writing will occur */
8712   u8 *pDest,                /* Pointer to the place to start writing */
8713   const BtreePayload *pX,   /* Source of data to write */
8714   int iOffset,              /* Offset of first byte to write */
8715   int iAmt                  /* Number of bytes to be written */
8716 ){
8717   int nData = pX->nData - iOffset;
8718   if( nData<=0 ){
8719     /* Overwritting with zeros */
8720     int i;
8721     for(i=0; i<iAmt && pDest[i]==0; i++){}
8722     if( i<iAmt ){
8723       int rc = sqlite3PagerWrite(pPage->pDbPage);
8724       if( rc ) return rc;
8725       memset(pDest + i, 0, iAmt - i);
8726     }
8727   }else{
8728     if( nData<iAmt ){
8729       /* Mixed read data and zeros at the end.  Make a recursive call
8730       ** to write the zeros then fall through to write the real data */
8731       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8732                                  iAmt-nData);
8733       if( rc ) return rc;
8734       iAmt = nData;
8735     }
8736     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8737       int rc = sqlite3PagerWrite(pPage->pDbPage);
8738       if( rc ) return rc;
8739       /* In a corrupt database, it is possible for the source and destination
8740       ** buffers to overlap.  This is harmless since the database is already
8741       ** corrupt but it does cause valgrind and ASAN warnings.  So use
8742       ** memmove(). */
8743       memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8744     }
8745   }
8746   return SQLITE_OK;
8747 }
8748 
8749 /*
8750 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8751 ** contained in pX.
8752 */
8753 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8754   int iOffset;                        /* Next byte of pX->pData to write */
8755   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8756   int rc;                             /* Return code */
8757   MemPage *pPage = pCur->pPage;       /* Page being written */
8758   BtShared *pBt;                      /* Btree */
8759   Pgno ovflPgno;                      /* Next overflow page to write */
8760   u32 ovflPageSize;                   /* Size to write on overflow page */
8761 
8762   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8763    || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8764   ){
8765     return SQLITE_CORRUPT_BKPT;
8766   }
8767   /* Overwrite the local portion first */
8768   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8769                              0, pCur->info.nLocal);
8770   if( rc ) return rc;
8771   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8772 
8773   /* Now overwrite the overflow pages */
8774   iOffset = pCur->info.nLocal;
8775   assert( nTotal>=0 );
8776   assert( iOffset>=0 );
8777   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8778   pBt = pPage->pBt;
8779   ovflPageSize = pBt->usableSize - 4;
8780   do{
8781     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8782     if( rc ) return rc;
8783     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
8784       rc = SQLITE_CORRUPT_BKPT;
8785     }else{
8786       if( iOffset+ovflPageSize<(u32)nTotal ){
8787         ovflPgno = get4byte(pPage->aData);
8788       }else{
8789         ovflPageSize = nTotal - iOffset;
8790       }
8791       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8792                                  iOffset, ovflPageSize);
8793     }
8794     sqlite3PagerUnref(pPage->pDbPage);
8795     if( rc ) return rc;
8796     iOffset += ovflPageSize;
8797   }while( iOffset<nTotal );
8798   return SQLITE_OK;
8799 }
8800 
8801 
8802 /*
8803 ** Insert a new record into the BTree.  The content of the new record
8804 ** is described by the pX object.  The pCur cursor is used only to
8805 ** define what table the record should be inserted into, and is left
8806 ** pointing at a random location.
8807 **
8808 ** For a table btree (used for rowid tables), only the pX.nKey value of
8809 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8810 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8811 ** hold the content of the row.
8812 **
8813 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8814 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8815 ** pX.pData,nData,nZero fields must be zero.
8816 **
8817 ** If the seekResult parameter is non-zero, then a successful call to
8818 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8819 ** been performed.  In other words, if seekResult!=0 then the cursor
8820 ** is currently pointing to a cell that will be adjacent to the cell
8821 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8822 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8823 ** that is larger than (pKey,nKey).
8824 **
8825 ** If seekResult==0, that means pCur is pointing at some unknown location.
8826 ** In that case, this routine must seek the cursor to the correct insertion
8827 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8828 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8829 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8830 ** to decode the key.
8831 */
8832 int sqlite3BtreeInsert(
8833   BtCursor *pCur,                /* Insert data into the table of this cursor */
8834   const BtreePayload *pX,        /* Content of the row to be inserted */
8835   int flags,                     /* True if this is likely an append */
8836   int seekResult                 /* Result of prior MovetoUnpacked() call */
8837 ){
8838   int rc;
8839   int loc = seekResult;          /* -1: before desired location  +1: after */
8840   int szNew = 0;
8841   int idx;
8842   MemPage *pPage;
8843   Btree *p = pCur->pBtree;
8844   BtShared *pBt = p->pBt;
8845   unsigned char *oldCell;
8846   unsigned char *newCell = 0;
8847 
8848   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8849   assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8850 
8851   if( pCur->eState==CURSOR_FAULT ){
8852     assert( pCur->skipNext!=SQLITE_OK );
8853     return pCur->skipNext;
8854   }
8855 
8856   assert( cursorOwnsBtShared(pCur) );
8857   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8858               && pBt->inTransaction==TRANS_WRITE
8859               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8860   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8861 
8862   /* Assert that the caller has been consistent. If this cursor was opened
8863   ** expecting an index b-tree, then the caller should be inserting blob
8864   ** keys with no associated data. If the cursor was opened expecting an
8865   ** intkey table, the caller should be inserting integer keys with a
8866   ** blob of associated data.  */
8867   assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
8868 
8869   /* Save the positions of any other cursors open on this table.
8870   **
8871   ** In some cases, the call to btreeMoveto() below is a no-op. For
8872   ** example, when inserting data into a table with auto-generated integer
8873   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8874   ** integer key to use. It then calls this function to actually insert the
8875   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8876   ** that the cursor is already where it needs to be and returns without
8877   ** doing any work. To avoid thwarting these optimizations, it is important
8878   ** not to clear the cursor here.
8879   */
8880   if( pCur->curFlags & BTCF_Multiple ){
8881     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8882     if( rc ) return rc;
8883     if( loc && pCur->iPage<0 ){
8884       /* This can only happen if the schema is corrupt such that there is more
8885       ** than one table or index with the same root page as used by the cursor.
8886       ** Which can only happen if the SQLITE_NoSchemaError flag was set when
8887       ** the schema was loaded. This cannot be asserted though, as a user might
8888       ** set the flag, load the schema, and then unset the flag.  */
8889       return SQLITE_CORRUPT_BKPT;
8890     }
8891   }
8892 
8893   if( pCur->pKeyInfo==0 ){
8894     assert( pX->pKey==0 );
8895     /* If this is an insert into a table b-tree, invalidate any incrblob
8896     ** cursors open on the row being replaced */
8897     if( p->hasIncrblobCur ){
8898       invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8899     }
8900 
8901     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8902     ** to a row with the same key as the new entry being inserted.
8903     */
8904 #ifdef SQLITE_DEBUG
8905     if( flags & BTREE_SAVEPOSITION ){
8906       assert( pCur->curFlags & BTCF_ValidNKey );
8907       assert( pX->nKey==pCur->info.nKey );
8908       assert( loc==0 );
8909     }
8910 #endif
8911 
8912     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8913     ** that the cursor is not pointing to a row to be overwritten.
8914     ** So do a complete check.
8915     */
8916     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8917       /* The cursor is pointing to the entry that is to be
8918       ** overwritten */
8919       assert( pX->nData>=0 && pX->nZero>=0 );
8920       if( pCur->info.nSize!=0
8921        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8922       ){
8923         /* New entry is the same size as the old.  Do an overwrite */
8924         return btreeOverwriteCell(pCur, pX);
8925       }
8926       assert( loc==0 );
8927     }else if( loc==0 ){
8928       /* The cursor is *not* pointing to the cell to be overwritten, nor
8929       ** to an adjacent cell.  Move the cursor so that it is pointing either
8930       ** to the cell to be overwritten or an adjacent cell.
8931       */
8932       rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
8933                (flags & BTREE_APPEND)!=0, &loc);
8934       if( rc ) return rc;
8935     }
8936   }else{
8937     /* This is an index or a WITHOUT ROWID table */
8938 
8939     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8940     ** to a row with the same key as the new entry being inserted.
8941     */
8942     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8943 
8944     /* If the cursor is not already pointing either to the cell to be
8945     ** overwritten, or if a new cell is being inserted, if the cursor is
8946     ** not pointing to an immediately adjacent cell, then move the cursor
8947     ** so that it does.
8948     */
8949     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8950       if( pX->nMem ){
8951         UnpackedRecord r;
8952         r.pKeyInfo = pCur->pKeyInfo;
8953         r.aMem = pX->aMem;
8954         r.nField = pX->nMem;
8955         r.default_rc = 0;
8956         r.eqSeen = 0;
8957         rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
8958       }else{
8959         rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
8960                     (flags & BTREE_APPEND)!=0, &loc);
8961       }
8962       if( rc ) return rc;
8963     }
8964 
8965     /* If the cursor is currently pointing to an entry to be overwritten
8966     ** and the new content is the same as as the old, then use the
8967     ** overwrite optimization.
8968     */
8969     if( loc==0 ){
8970       getCellInfo(pCur);
8971       if( pCur->info.nKey==pX->nKey ){
8972         BtreePayload x2;
8973         x2.pData = pX->pKey;
8974         x2.nData = pX->nKey;
8975         x2.nZero = 0;
8976         return btreeOverwriteCell(pCur, &x2);
8977       }
8978     }
8979   }
8980   assert( pCur->eState==CURSOR_VALID
8981        || (pCur->eState==CURSOR_INVALID && loc)
8982        || CORRUPT_DB );
8983 
8984   pPage = pCur->pPage;
8985   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8986   assert( pPage->leaf || !pPage->intKey );
8987   if( pPage->nFree<0 ){
8988     if( NEVER(pCur->eState>CURSOR_INVALID) ){
8989       rc = SQLITE_CORRUPT_BKPT;
8990     }else{
8991       rc = btreeComputeFreeSpace(pPage);
8992     }
8993     if( rc ) return rc;
8994   }
8995 
8996   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8997           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8998           loc==0 ? "overwrite" : "new entry"));
8999   assert( pPage->isInit );
9000   newCell = pBt->pTmpSpace;
9001   assert( newCell!=0 );
9002   if( flags & BTREE_PREFORMAT ){
9003     rc = SQLITE_OK;
9004     szNew = pBt->nPreformatSize;
9005     if( szNew<4 ) szNew = 4;
9006     if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
9007       CellInfo info;
9008       pPage->xParseCell(pPage, newCell, &info);
9009       if( info.nPayload!=info.nLocal ){
9010         Pgno ovfl = get4byte(&newCell[szNew-4]);
9011         ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9012       }
9013     }
9014   }else{
9015     rc = fillInCell(pPage, newCell, pX, &szNew);
9016   }
9017   if( rc ) goto end_insert;
9018   assert( szNew==pPage->xCellSize(pPage, newCell) );
9019   assert( szNew <= MX_CELL_SIZE(pBt) );
9020   idx = pCur->ix;
9021   if( loc==0 ){
9022     CellInfo info;
9023     assert( idx>=0 );
9024     if( idx>=pPage->nCell ){
9025       return SQLITE_CORRUPT_BKPT;
9026     }
9027     rc = sqlite3PagerWrite(pPage->pDbPage);
9028     if( rc ){
9029       goto end_insert;
9030     }
9031     oldCell = findCell(pPage, idx);
9032     if( !pPage->leaf ){
9033       memcpy(newCell, oldCell, 4);
9034     }
9035     BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9036     testcase( pCur->curFlags & BTCF_ValidOvfl );
9037     invalidateOverflowCache(pCur);
9038     if( info.nSize==szNew && info.nLocal==info.nPayload
9039      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
9040     ){
9041       /* Overwrite the old cell with the new if they are the same size.
9042       ** We could also try to do this if the old cell is smaller, then add
9043       ** the leftover space to the free list.  But experiments show that
9044       ** doing that is no faster then skipping this optimization and just
9045       ** calling dropCell() and insertCell().
9046       **
9047       ** This optimization cannot be used on an autovacuum database if the
9048       ** new entry uses overflow pages, as the insertCell() call below is
9049       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
9050       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9051       if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9052         return SQLITE_CORRUPT_BKPT;
9053       }
9054       if( oldCell+szNew > pPage->aDataEnd ){
9055         return SQLITE_CORRUPT_BKPT;
9056       }
9057       memcpy(oldCell, newCell, szNew);
9058       return SQLITE_OK;
9059     }
9060     dropCell(pPage, idx, info.nSize, &rc);
9061     if( rc ) goto end_insert;
9062   }else if( loc<0 && pPage->nCell>0 ){
9063     assert( pPage->leaf );
9064     idx = ++pCur->ix;
9065     pCur->curFlags &= ~BTCF_ValidNKey;
9066   }else{
9067     assert( pPage->leaf );
9068   }
9069   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
9070   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9071   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9072 
9073   /* If no error has occurred and pPage has an overflow cell, call balance()
9074   ** to redistribute the cells within the tree. Since balance() may move
9075   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9076   ** variables.
9077   **
9078   ** Previous versions of SQLite called moveToRoot() to move the cursor
9079   ** back to the root page as balance() used to invalidate the contents
9080   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9081   ** set the cursor state to "invalid". This makes common insert operations
9082   ** slightly faster.
9083   **
9084   ** There is a subtle but important optimization here too. When inserting
9085   ** multiple records into an intkey b-tree using a single cursor (as can
9086   ** happen while processing an "INSERT INTO ... SELECT" statement), it
9087   ** is advantageous to leave the cursor pointing to the last entry in
9088   ** the b-tree if possible. If the cursor is left pointing to the last
9089   ** entry in the table, and the next row inserted has an integer key
9090   ** larger than the largest existing key, it is possible to insert the
9091   ** row without seeking the cursor. This can be a big performance boost.
9092   */
9093   pCur->info.nSize = 0;
9094   if( pPage->nOverflow ){
9095     assert( rc==SQLITE_OK );
9096     pCur->curFlags &= ~(BTCF_ValidNKey);
9097     rc = balance(pCur);
9098 
9099     /* Must make sure nOverflow is reset to zero even if the balance()
9100     ** fails. Internal data structure corruption will result otherwise.
9101     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9102     ** from trying to save the current position of the cursor.  */
9103     pCur->pPage->nOverflow = 0;
9104     pCur->eState = CURSOR_INVALID;
9105     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9106       btreeReleaseAllCursorPages(pCur);
9107       if( pCur->pKeyInfo ){
9108         assert( pCur->pKey==0 );
9109         pCur->pKey = sqlite3Malloc( pX->nKey );
9110         if( pCur->pKey==0 ){
9111           rc = SQLITE_NOMEM;
9112         }else{
9113           memcpy(pCur->pKey, pX->pKey, pX->nKey);
9114         }
9115       }
9116       pCur->eState = CURSOR_REQUIRESEEK;
9117       pCur->nKey = pX->nKey;
9118     }
9119   }
9120   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9121 
9122 end_insert:
9123   return rc;
9124 }
9125 
9126 /*
9127 ** This function is used as part of copying the current row from cursor
9128 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9129 ** parameter iKey is used as the rowid value when the record is copied
9130 ** into pDest. Otherwise, the record is copied verbatim.
9131 **
9132 ** This function does not actually write the new value to cursor pDest.
9133 ** Instead, it creates and populates any required overflow pages and
9134 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9135 ** for the destination database. The size of the cell, in bytes, is left
9136 ** in BtShared.nPreformatSize. The caller completes the insertion by
9137 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9138 **
9139 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9140 */
9141 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9142   int rc = SQLITE_OK;
9143   BtShared *pBt = pDest->pBt;
9144   u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
9145   const u8 *aIn;                /* Pointer to next input buffer */
9146   u32 nIn;                      /* Size of input buffer aIn[] */
9147   u32 nRem;                     /* Bytes of data still to copy */
9148 
9149   getCellInfo(pSrc);
9150   aOut += putVarint32(aOut, pSrc->info.nPayload);
9151   if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9152   nIn = pSrc->info.nLocal;
9153   aIn = pSrc->info.pPayload;
9154   if( aIn+nIn>pSrc->pPage->aDataEnd ){
9155     return SQLITE_CORRUPT_BKPT;
9156   }
9157   nRem = pSrc->info.nPayload;
9158   if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9159     memcpy(aOut, aIn, nIn);
9160     pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9161   }else{
9162     Pager *pSrcPager = pSrc->pBt->pPager;
9163     u8 *pPgnoOut = 0;
9164     Pgno ovflIn = 0;
9165     DbPage *pPageIn = 0;
9166     MemPage *pPageOut = 0;
9167     u32 nOut;                     /* Size of output buffer aOut[] */
9168 
9169     nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9170     pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9171     if( nOut<pSrc->info.nPayload ){
9172       pPgnoOut = &aOut[nOut];
9173       pBt->nPreformatSize += 4;
9174     }
9175 
9176     if( nRem>nIn ){
9177       if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9178         return SQLITE_CORRUPT_BKPT;
9179       }
9180       ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9181     }
9182 
9183     do {
9184       nRem -= nOut;
9185       do{
9186         assert( nOut>0 );
9187         if( nIn>0 ){
9188           int nCopy = MIN(nOut, nIn);
9189           memcpy(aOut, aIn, nCopy);
9190           nOut -= nCopy;
9191           nIn -= nCopy;
9192           aOut += nCopy;
9193           aIn += nCopy;
9194         }
9195         if( nOut>0 ){
9196           sqlite3PagerUnref(pPageIn);
9197           pPageIn = 0;
9198           rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9199           if( rc==SQLITE_OK ){
9200             aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9201             ovflIn = get4byte(aIn);
9202             aIn += 4;
9203             nIn = pSrc->pBt->usableSize - 4;
9204           }
9205         }
9206       }while( rc==SQLITE_OK && nOut>0 );
9207 
9208       if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9209         Pgno pgnoNew;
9210         MemPage *pNew = 0;
9211         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9212         put4byte(pPgnoOut, pgnoNew);
9213         if( ISAUTOVACUUM && pPageOut ){
9214           ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9215         }
9216         releasePage(pPageOut);
9217         pPageOut = pNew;
9218         if( pPageOut ){
9219           pPgnoOut = pPageOut->aData;
9220           put4byte(pPgnoOut, 0);
9221           aOut = &pPgnoOut[4];
9222           nOut = MIN(pBt->usableSize - 4, nRem);
9223         }
9224       }
9225     }while( nRem>0 && rc==SQLITE_OK );
9226 
9227     releasePage(pPageOut);
9228     sqlite3PagerUnref(pPageIn);
9229   }
9230 
9231   return rc;
9232 }
9233 
9234 /*
9235 ** Delete the entry that the cursor is pointing to.
9236 **
9237 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9238 ** the cursor is left pointing at an arbitrary location after the delete.
9239 ** But if that bit is set, then the cursor is left in a state such that
9240 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9241 ** as it would have been on if the call to BtreeDelete() had been omitted.
9242 **
9243 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9244 ** associated with a single table entry and its indexes.  Only one of those
9245 ** deletes is considered the "primary" delete.  The primary delete occurs
9246 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
9247 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9248 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9249 ** but which might be used by alternative storage engines.
9250 */
9251 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9252   Btree *p = pCur->pBtree;
9253   BtShared *pBt = p->pBt;
9254   int rc;                    /* Return code */
9255   MemPage *pPage;            /* Page to delete cell from */
9256   unsigned char *pCell;      /* Pointer to cell to delete */
9257   int iCellIdx;              /* Index of cell to delete */
9258   int iCellDepth;            /* Depth of node containing pCell */
9259   CellInfo info;             /* Size of the cell being deleted */
9260   u8 bPreserve;              /* Keep cursor valid.  2 for CURSOR_SKIPNEXT */
9261 
9262   assert( cursorOwnsBtShared(pCur) );
9263   assert( pBt->inTransaction==TRANS_WRITE );
9264   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9265   assert( pCur->curFlags & BTCF_WriteFlag );
9266   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9267   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9268   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9269   if( pCur->eState==CURSOR_REQUIRESEEK ){
9270     rc = btreeRestoreCursorPosition(pCur);
9271     assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9272     if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9273   }
9274   assert( CORRUPT_DB || pCur->eState==CURSOR_VALID );
9275 
9276   iCellDepth = pCur->iPage;
9277   iCellIdx = pCur->ix;
9278   pPage = pCur->pPage;
9279   if( pPage->nCell<=iCellIdx ){
9280     return SQLITE_CORRUPT_BKPT;
9281   }
9282   pCell = findCell(pPage, iCellIdx);
9283   if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9284     return SQLITE_CORRUPT_BKPT;
9285   }
9286 
9287   /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9288   ** be preserved following this delete operation. If the current delete
9289   ** will cause a b-tree rebalance, then this is done by saving the cursor
9290   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9291   ** returning.
9292   **
9293   ** If the current delete will not cause a rebalance, then the cursor
9294   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9295   ** before or after the deleted entry.
9296   **
9297   ** The bPreserve value records which path is required:
9298   **
9299   **    bPreserve==0         Not necessary to save the cursor position
9300   **    bPreserve==1         Use CURSOR_REQUIRESEEK to save the cursor position
9301   **    bPreserve==2         Cursor won't move.  Set CURSOR_SKIPNEXT.
9302   */
9303   bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9304   if( bPreserve ){
9305     if( !pPage->leaf
9306      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9307      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
9308     ){
9309       /* A b-tree rebalance will be required after deleting this entry.
9310       ** Save the cursor key.  */
9311       rc = saveCursorKey(pCur);
9312       if( rc ) return rc;
9313     }else{
9314       bPreserve = 2;
9315     }
9316   }
9317 
9318   /* If the page containing the entry to delete is not a leaf page, move
9319   ** the cursor to the largest entry in the tree that is smaller than
9320   ** the entry being deleted. This cell will replace the cell being deleted
9321   ** from the internal node. The 'previous' entry is used for this instead
9322   ** of the 'next' entry, as the previous entry is always a part of the
9323   ** sub-tree headed by the child page of the cell being deleted. This makes
9324   ** balancing the tree following the delete operation easier.  */
9325   if( !pPage->leaf ){
9326     rc = sqlite3BtreePrevious(pCur, 0);
9327     assert( rc!=SQLITE_DONE );
9328     if( rc ) return rc;
9329   }
9330 
9331   /* Save the positions of any other cursors open on this table before
9332   ** making any modifications.  */
9333   if( pCur->curFlags & BTCF_Multiple ){
9334     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9335     if( rc ) return rc;
9336   }
9337 
9338   /* If this is a delete operation to remove a row from a table b-tree,
9339   ** invalidate any incrblob cursors open on the row being deleted.  */
9340   if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9341     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9342   }
9343 
9344   /* Make the page containing the entry to be deleted writable. Then free any
9345   ** overflow pages associated with the entry and finally remove the cell
9346   ** itself from within the page.  */
9347   rc = sqlite3PagerWrite(pPage->pDbPage);
9348   if( rc ) return rc;
9349   BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9350   dropCell(pPage, iCellIdx, info.nSize, &rc);
9351   if( rc ) return rc;
9352 
9353   /* If the cell deleted was not located on a leaf page, then the cursor
9354   ** is currently pointing to the largest entry in the sub-tree headed
9355   ** by the child-page of the cell that was just deleted from an internal
9356   ** node. The cell from the leaf node needs to be moved to the internal
9357   ** node to replace the deleted cell.  */
9358   if( !pPage->leaf ){
9359     MemPage *pLeaf = pCur->pPage;
9360     int nCell;
9361     Pgno n;
9362     unsigned char *pTmp;
9363 
9364     if( pLeaf->nFree<0 ){
9365       rc = btreeComputeFreeSpace(pLeaf);
9366       if( rc ) return rc;
9367     }
9368     if( iCellDepth<pCur->iPage-1 ){
9369       n = pCur->apPage[iCellDepth+1]->pgno;
9370     }else{
9371       n = pCur->pPage->pgno;
9372     }
9373     pCell = findCell(pLeaf, pLeaf->nCell-1);
9374     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9375     nCell = pLeaf->xCellSize(pLeaf, pCell);
9376     assert( MX_CELL_SIZE(pBt) >= nCell );
9377     pTmp = pBt->pTmpSpace;
9378     assert( pTmp!=0 );
9379     rc = sqlite3PagerWrite(pLeaf->pDbPage);
9380     if( rc==SQLITE_OK ){
9381       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9382     }
9383     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9384     if( rc ) return rc;
9385   }
9386 
9387   /* Balance the tree. If the entry deleted was located on a leaf page,
9388   ** then the cursor still points to that page. In this case the first
9389   ** call to balance() repairs the tree, and the if(...) condition is
9390   ** never true.
9391   **
9392   ** Otherwise, if the entry deleted was on an internal node page, then
9393   ** pCur is pointing to the leaf page from which a cell was removed to
9394   ** replace the cell deleted from the internal node. This is slightly
9395   ** tricky as the leaf node may be underfull, and the internal node may
9396   ** be either under or overfull. In this case run the balancing algorithm
9397   ** on the leaf node first. If the balance proceeds far enough up the
9398   ** tree that we can be sure that any problem in the internal node has
9399   ** been corrected, so be it. Otherwise, after balancing the leaf node,
9400   ** walk the cursor up the tree to the internal node and balance it as
9401   ** well.  */
9402   rc = balance(pCur);
9403   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9404     releasePageNotNull(pCur->pPage);
9405     pCur->iPage--;
9406     while( pCur->iPage>iCellDepth ){
9407       releasePage(pCur->apPage[pCur->iPage--]);
9408     }
9409     pCur->pPage = pCur->apPage[pCur->iPage];
9410     rc = balance(pCur);
9411   }
9412 
9413   if( rc==SQLITE_OK ){
9414     if( bPreserve>1 ){
9415       assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
9416       assert( pPage==pCur->pPage || CORRUPT_DB );
9417       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9418       pCur->eState = CURSOR_SKIPNEXT;
9419       if( iCellIdx>=pPage->nCell ){
9420         pCur->skipNext = -1;
9421         pCur->ix = pPage->nCell-1;
9422       }else{
9423         pCur->skipNext = 1;
9424       }
9425     }else{
9426       rc = moveToRoot(pCur);
9427       if( bPreserve ){
9428         btreeReleaseAllCursorPages(pCur);
9429         pCur->eState = CURSOR_REQUIRESEEK;
9430       }
9431       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9432     }
9433   }
9434   return rc;
9435 }
9436 
9437 /*
9438 ** Create a new BTree table.  Write into *piTable the page
9439 ** number for the root page of the new table.
9440 **
9441 ** The type of type is determined by the flags parameter.  Only the
9442 ** following values of flags are currently in use.  Other values for
9443 ** flags might not work:
9444 **
9445 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
9446 **     BTREE_ZERODATA                  Used for SQL indices
9447 */
9448 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9449   BtShared *pBt = p->pBt;
9450   MemPage *pRoot;
9451   Pgno pgnoRoot;
9452   int rc;
9453   int ptfFlags;          /* Page-type flage for the root page of new table */
9454 
9455   assert( sqlite3BtreeHoldsMutex(p) );
9456   assert( pBt->inTransaction==TRANS_WRITE );
9457   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9458 
9459 #ifdef SQLITE_OMIT_AUTOVACUUM
9460   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9461   if( rc ){
9462     return rc;
9463   }
9464 #else
9465   if( pBt->autoVacuum ){
9466     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
9467     MemPage *pPageMove; /* The page to move to. */
9468 
9469     /* Creating a new table may probably require moving an existing database
9470     ** to make room for the new tables root page. In case this page turns
9471     ** out to be an overflow page, delete all overflow page-map caches
9472     ** held by open cursors.
9473     */
9474     invalidateAllOverflowCache(pBt);
9475 
9476     /* Read the value of meta[3] from the database to determine where the
9477     ** root page of the new table should go. meta[3] is the largest root-page
9478     ** created so far, so the new root-page is (meta[3]+1).
9479     */
9480     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9481     if( pgnoRoot>btreePagecount(pBt) ){
9482       return SQLITE_CORRUPT_BKPT;
9483     }
9484     pgnoRoot++;
9485 
9486     /* The new root-page may not be allocated on a pointer-map page, or the
9487     ** PENDING_BYTE page.
9488     */
9489     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9490         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9491       pgnoRoot++;
9492     }
9493     assert( pgnoRoot>=3 );
9494 
9495     /* Allocate a page. The page that currently resides at pgnoRoot will
9496     ** be moved to the allocated page (unless the allocated page happens
9497     ** to reside at pgnoRoot).
9498     */
9499     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9500     if( rc!=SQLITE_OK ){
9501       return rc;
9502     }
9503 
9504     if( pgnoMove!=pgnoRoot ){
9505       /* pgnoRoot is the page that will be used for the root-page of
9506       ** the new table (assuming an error did not occur). But we were
9507       ** allocated pgnoMove. If required (i.e. if it was not allocated
9508       ** by extending the file), the current page at position pgnoMove
9509       ** is already journaled.
9510       */
9511       u8 eType = 0;
9512       Pgno iPtrPage = 0;
9513 
9514       /* Save the positions of any open cursors. This is required in
9515       ** case they are holding a reference to an xFetch reference
9516       ** corresponding to page pgnoRoot.  */
9517       rc = saveAllCursors(pBt, 0, 0);
9518       releasePage(pPageMove);
9519       if( rc!=SQLITE_OK ){
9520         return rc;
9521       }
9522 
9523       /* Move the page currently at pgnoRoot to pgnoMove. */
9524       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9525       if( rc!=SQLITE_OK ){
9526         return rc;
9527       }
9528       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9529       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9530         rc = SQLITE_CORRUPT_BKPT;
9531       }
9532       if( rc!=SQLITE_OK ){
9533         releasePage(pRoot);
9534         return rc;
9535       }
9536       assert( eType!=PTRMAP_ROOTPAGE );
9537       assert( eType!=PTRMAP_FREEPAGE );
9538       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9539       releasePage(pRoot);
9540 
9541       /* Obtain the page at pgnoRoot */
9542       if( rc!=SQLITE_OK ){
9543         return rc;
9544       }
9545       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9546       if( rc!=SQLITE_OK ){
9547         return rc;
9548       }
9549       rc = sqlite3PagerWrite(pRoot->pDbPage);
9550       if( rc!=SQLITE_OK ){
9551         releasePage(pRoot);
9552         return rc;
9553       }
9554     }else{
9555       pRoot = pPageMove;
9556     }
9557 
9558     /* Update the pointer-map and meta-data with the new root-page number. */
9559     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9560     if( rc ){
9561       releasePage(pRoot);
9562       return rc;
9563     }
9564 
9565     /* When the new root page was allocated, page 1 was made writable in
9566     ** order either to increase the database filesize, or to decrement the
9567     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9568     */
9569     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9570     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9571     if( NEVER(rc) ){
9572       releasePage(pRoot);
9573       return rc;
9574     }
9575 
9576   }else{
9577     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9578     if( rc ) return rc;
9579   }
9580 #endif
9581   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9582   if( createTabFlags & BTREE_INTKEY ){
9583     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9584   }else{
9585     ptfFlags = PTF_ZERODATA | PTF_LEAF;
9586   }
9587   zeroPage(pRoot, ptfFlags);
9588   sqlite3PagerUnref(pRoot->pDbPage);
9589   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9590   *piTable = pgnoRoot;
9591   return SQLITE_OK;
9592 }
9593 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9594   int rc;
9595   sqlite3BtreeEnter(p);
9596   rc = btreeCreateTable(p, piTable, flags);
9597   sqlite3BtreeLeave(p);
9598   return rc;
9599 }
9600 
9601 /*
9602 ** Erase the given database page and all its children.  Return
9603 ** the page to the freelist.
9604 */
9605 static int clearDatabasePage(
9606   BtShared *pBt,           /* The BTree that contains the table */
9607   Pgno pgno,               /* Page number to clear */
9608   int freePageFlag,        /* Deallocate page if true */
9609   i64 *pnChange            /* Add number of Cells freed to this counter */
9610 ){
9611   MemPage *pPage;
9612   int rc;
9613   unsigned char *pCell;
9614   int i;
9615   int hdr;
9616   CellInfo info;
9617 
9618   assert( sqlite3_mutex_held(pBt->mutex) );
9619   if( pgno>btreePagecount(pBt) ){
9620     return SQLITE_CORRUPT_BKPT;
9621   }
9622   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9623   if( rc ) return rc;
9624   if( (pBt->openFlags & BTREE_SINGLE)==0
9625    && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
9626   ){
9627     rc = SQLITE_CORRUPT_BKPT;
9628     goto cleardatabasepage_out;
9629   }
9630   hdr = pPage->hdrOffset;
9631   for(i=0; i<pPage->nCell; i++){
9632     pCell = findCell(pPage, i);
9633     if( !pPage->leaf ){
9634       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9635       if( rc ) goto cleardatabasepage_out;
9636     }
9637     BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9638     if( rc ) goto cleardatabasepage_out;
9639   }
9640   if( !pPage->leaf ){
9641     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9642     if( rc ) goto cleardatabasepage_out;
9643     if( pPage->intKey ) pnChange = 0;
9644   }
9645   if( pnChange ){
9646     testcase( !pPage->intKey );
9647     *pnChange += pPage->nCell;
9648   }
9649   if( freePageFlag ){
9650     freePage(pPage, &rc);
9651   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9652     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9653   }
9654 
9655 cleardatabasepage_out:
9656   releasePage(pPage);
9657   return rc;
9658 }
9659 
9660 /*
9661 ** Delete all information from a single table in the database.  iTable is
9662 ** the page number of the root of the table.  After this routine returns,
9663 ** the root page is empty, but still exists.
9664 **
9665 ** This routine will fail with SQLITE_LOCKED if there are any open
9666 ** read cursors on the table.  Open write cursors are moved to the
9667 ** root of the table.
9668 **
9669 ** If pnChange is not NULL, then the integer value pointed to by pnChange
9670 ** is incremented by the number of entries in the table.
9671 */
9672 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
9673   int rc;
9674   BtShared *pBt = p->pBt;
9675   sqlite3BtreeEnter(p);
9676   assert( p->inTrans==TRANS_WRITE );
9677 
9678   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9679 
9680   if( SQLITE_OK==rc ){
9681     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9682     ** is the root of a table b-tree - if it is not, the following call is
9683     ** a no-op).  */
9684     if( p->hasIncrblobCur ){
9685       invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9686     }
9687     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9688   }
9689   sqlite3BtreeLeave(p);
9690   return rc;
9691 }
9692 
9693 /*
9694 ** Delete all information from the single table that pCur is open on.
9695 **
9696 ** This routine only work for pCur on an ephemeral table.
9697 */
9698 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9699   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9700 }
9701 
9702 /*
9703 ** Erase all information in a table and add the root of the table to
9704 ** the freelist.  Except, the root of the principle table (the one on
9705 ** page 1) is never added to the freelist.
9706 **
9707 ** This routine will fail with SQLITE_LOCKED if there are any open
9708 ** cursors on the table.
9709 **
9710 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9711 ** root page in the database file, then the last root page
9712 ** in the database file is moved into the slot formerly occupied by
9713 ** iTable and that last slot formerly occupied by the last root page
9714 ** is added to the freelist instead of iTable.  In this say, all
9715 ** root pages are kept at the beginning of the database file, which
9716 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9717 ** page number that used to be the last root page in the file before
9718 ** the move.  If no page gets moved, *piMoved is set to 0.
9719 ** The last root page is recorded in meta[3] and the value of
9720 ** meta[3] is updated by this procedure.
9721 */
9722 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9723   int rc;
9724   MemPage *pPage = 0;
9725   BtShared *pBt = p->pBt;
9726 
9727   assert( sqlite3BtreeHoldsMutex(p) );
9728   assert( p->inTrans==TRANS_WRITE );
9729   assert( iTable>=2 );
9730   if( iTable>btreePagecount(pBt) ){
9731     return SQLITE_CORRUPT_BKPT;
9732   }
9733 
9734   rc = sqlite3BtreeClearTable(p, iTable, 0);
9735   if( rc ) return rc;
9736   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9737   if( NEVER(rc) ){
9738     releasePage(pPage);
9739     return rc;
9740   }
9741 
9742   *piMoved = 0;
9743 
9744 #ifdef SQLITE_OMIT_AUTOVACUUM
9745   freePage(pPage, &rc);
9746   releasePage(pPage);
9747 #else
9748   if( pBt->autoVacuum ){
9749     Pgno maxRootPgno;
9750     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9751 
9752     if( iTable==maxRootPgno ){
9753       /* If the table being dropped is the table with the largest root-page
9754       ** number in the database, put the root page on the free list.
9755       */
9756       freePage(pPage, &rc);
9757       releasePage(pPage);
9758       if( rc!=SQLITE_OK ){
9759         return rc;
9760       }
9761     }else{
9762       /* The table being dropped does not have the largest root-page
9763       ** number in the database. So move the page that does into the
9764       ** gap left by the deleted root-page.
9765       */
9766       MemPage *pMove;
9767       releasePage(pPage);
9768       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9769       if( rc!=SQLITE_OK ){
9770         return rc;
9771       }
9772       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9773       releasePage(pMove);
9774       if( rc!=SQLITE_OK ){
9775         return rc;
9776       }
9777       pMove = 0;
9778       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9779       freePage(pMove, &rc);
9780       releasePage(pMove);
9781       if( rc!=SQLITE_OK ){
9782         return rc;
9783       }
9784       *piMoved = maxRootPgno;
9785     }
9786 
9787     /* Set the new 'max-root-page' value in the database header. This
9788     ** is the old value less one, less one more if that happens to
9789     ** be a root-page number, less one again if that is the
9790     ** PENDING_BYTE_PAGE.
9791     */
9792     maxRootPgno--;
9793     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9794            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9795       maxRootPgno--;
9796     }
9797     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9798 
9799     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9800   }else{
9801     freePage(pPage, &rc);
9802     releasePage(pPage);
9803   }
9804 #endif
9805   return rc;
9806 }
9807 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9808   int rc;
9809   sqlite3BtreeEnter(p);
9810   rc = btreeDropTable(p, iTable, piMoved);
9811   sqlite3BtreeLeave(p);
9812   return rc;
9813 }
9814 
9815 
9816 /*
9817 ** This function may only be called if the b-tree connection already
9818 ** has a read or write transaction open on the database.
9819 **
9820 ** Read the meta-information out of a database file.  Meta[0]
9821 ** is the number of free pages currently in the database.  Meta[1]
9822 ** through meta[15] are available for use by higher layers.  Meta[0]
9823 ** is read-only, the others are read/write.
9824 **
9825 ** The schema layer numbers meta values differently.  At the schema
9826 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9827 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
9828 **
9829 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
9830 ** of reading the value out of the header, it instead loads the "DataVersion"
9831 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
9832 ** database file.  It is a number computed by the pager.  But its access
9833 ** pattern is the same as header meta values, and so it is convenient to
9834 ** read it from this routine.
9835 */
9836 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9837   BtShared *pBt = p->pBt;
9838 
9839   sqlite3BtreeEnter(p);
9840   assert( p->inTrans>TRANS_NONE );
9841   assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9842   assert( pBt->pPage1 );
9843   assert( idx>=0 && idx<=15 );
9844 
9845   if( idx==BTREE_DATA_VERSION ){
9846     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
9847   }else{
9848     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9849   }
9850 
9851   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9852   ** database, mark the database as read-only.  */
9853 #ifdef SQLITE_OMIT_AUTOVACUUM
9854   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9855     pBt->btsFlags |= BTS_READ_ONLY;
9856   }
9857 #endif
9858 
9859   sqlite3BtreeLeave(p);
9860 }
9861 
9862 /*
9863 ** Write meta-information back into the database.  Meta[0] is
9864 ** read-only and may not be written.
9865 */
9866 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9867   BtShared *pBt = p->pBt;
9868   unsigned char *pP1;
9869   int rc;
9870   assert( idx>=1 && idx<=15 );
9871   sqlite3BtreeEnter(p);
9872   assert( p->inTrans==TRANS_WRITE );
9873   assert( pBt->pPage1!=0 );
9874   pP1 = pBt->pPage1->aData;
9875   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9876   if( rc==SQLITE_OK ){
9877     put4byte(&pP1[36 + idx*4], iMeta);
9878 #ifndef SQLITE_OMIT_AUTOVACUUM
9879     if( idx==BTREE_INCR_VACUUM ){
9880       assert( pBt->autoVacuum || iMeta==0 );
9881       assert( iMeta==0 || iMeta==1 );
9882       pBt->incrVacuum = (u8)iMeta;
9883     }
9884 #endif
9885   }
9886   sqlite3BtreeLeave(p);
9887   return rc;
9888 }
9889 
9890 /*
9891 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9892 ** number of entries in the b-tree and write the result to *pnEntry.
9893 **
9894 ** SQLITE_OK is returned if the operation is successfully executed.
9895 ** Otherwise, if an error is encountered (i.e. an IO error or database
9896 ** corruption) an SQLite error code is returned.
9897 */
9898 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9899   i64 nEntry = 0;                      /* Value to return in *pnEntry */
9900   int rc;                              /* Return code */
9901 
9902   rc = moveToRoot(pCur);
9903   if( rc==SQLITE_EMPTY ){
9904     *pnEntry = 0;
9905     return SQLITE_OK;
9906   }
9907 
9908   /* Unless an error occurs, the following loop runs one iteration for each
9909   ** page in the B-Tree structure (not including overflow pages).
9910   */
9911   while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9912     int iIdx;                          /* Index of child node in parent */
9913     MemPage *pPage;                    /* Current page of the b-tree */
9914 
9915     /* If this is a leaf page or the tree is not an int-key tree, then
9916     ** this page contains countable entries. Increment the entry counter
9917     ** accordingly.
9918     */
9919     pPage = pCur->pPage;
9920     if( pPage->leaf || !pPage->intKey ){
9921       nEntry += pPage->nCell;
9922     }
9923 
9924     /* pPage is a leaf node. This loop navigates the cursor so that it
9925     ** points to the first interior cell that it points to the parent of
9926     ** the next page in the tree that has not yet been visited. The
9927     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9928     ** of the page, or to the number of cells in the page if the next page
9929     ** to visit is the right-child of its parent.
9930     **
9931     ** If all pages in the tree have been visited, return SQLITE_OK to the
9932     ** caller.
9933     */
9934     if( pPage->leaf ){
9935       do {
9936         if( pCur->iPage==0 ){
9937           /* All pages of the b-tree have been visited. Return successfully. */
9938           *pnEntry = nEntry;
9939           return moveToRoot(pCur);
9940         }
9941         moveToParent(pCur);
9942       }while ( pCur->ix>=pCur->pPage->nCell );
9943 
9944       pCur->ix++;
9945       pPage = pCur->pPage;
9946     }
9947 
9948     /* Descend to the child node of the cell that the cursor currently
9949     ** points at. This is the right-child if (iIdx==pPage->nCell).
9950     */
9951     iIdx = pCur->ix;
9952     if( iIdx==pPage->nCell ){
9953       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9954     }else{
9955       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9956     }
9957   }
9958 
9959   /* An error has occurred. Return an error code. */
9960   return rc;
9961 }
9962 
9963 /*
9964 ** Return the pager associated with a BTree.  This routine is used for
9965 ** testing and debugging only.
9966 */
9967 Pager *sqlite3BtreePager(Btree *p){
9968   return p->pBt->pPager;
9969 }
9970 
9971 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9972 /*
9973 ** Append a message to the error message string.
9974 */
9975 static void checkAppendMsg(
9976   IntegrityCk *pCheck,
9977   const char *zFormat,
9978   ...
9979 ){
9980   va_list ap;
9981   if( !pCheck->mxErr ) return;
9982   pCheck->mxErr--;
9983   pCheck->nErr++;
9984   va_start(ap, zFormat);
9985   if( pCheck->errMsg.nChar ){
9986     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9987   }
9988   if( pCheck->zPfx ){
9989     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9990   }
9991   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9992   va_end(ap);
9993   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9994     pCheck->bOomFault = 1;
9995   }
9996 }
9997 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9998 
9999 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10000 
10001 /*
10002 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10003 ** corresponds to page iPg is already set.
10004 */
10005 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10006   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10007   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10008 }
10009 
10010 /*
10011 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10012 */
10013 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10014   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10015   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10016 }
10017 
10018 
10019 /*
10020 ** Add 1 to the reference count for page iPage.  If this is the second
10021 ** reference to the page, add an error message to pCheck->zErrMsg.
10022 ** Return 1 if there are 2 or more references to the page and 0 if
10023 ** if this is the first reference to the page.
10024 **
10025 ** Also check that the page number is in bounds.
10026 */
10027 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10028   if( iPage>pCheck->nPage || iPage==0 ){
10029     checkAppendMsg(pCheck, "invalid page number %d", iPage);
10030     return 1;
10031   }
10032   if( getPageReferenced(pCheck, iPage) ){
10033     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
10034     return 1;
10035   }
10036   if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
10037   setPageReferenced(pCheck, iPage);
10038   return 0;
10039 }
10040 
10041 #ifndef SQLITE_OMIT_AUTOVACUUM
10042 /*
10043 ** Check that the entry in the pointer-map for page iChild maps to
10044 ** page iParent, pointer type ptrType. If not, append an error message
10045 ** to pCheck.
10046 */
10047 static void checkPtrmap(
10048   IntegrityCk *pCheck,   /* Integrity check context */
10049   Pgno iChild,           /* Child page number */
10050   u8 eType,              /* Expected pointer map type */
10051   Pgno iParent           /* Expected pointer map parent page number */
10052 ){
10053   int rc;
10054   u8 ePtrmapType;
10055   Pgno iPtrmapParent;
10056 
10057   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10058   if( rc!=SQLITE_OK ){
10059     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
10060     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
10061     return;
10062   }
10063 
10064   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10065     checkAppendMsg(pCheck,
10066       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
10067       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10068   }
10069 }
10070 #endif
10071 
10072 /*
10073 ** Check the integrity of the freelist or of an overflow page list.
10074 ** Verify that the number of pages on the list is N.
10075 */
10076 static void checkList(
10077   IntegrityCk *pCheck,  /* Integrity checking context */
10078   int isFreeList,       /* True for a freelist.  False for overflow page list */
10079   Pgno iPage,           /* Page number for first page in the list */
10080   u32 N                 /* Expected number of pages in the list */
10081 ){
10082   int i;
10083   u32 expected = N;
10084   int nErrAtStart = pCheck->nErr;
10085   while( iPage!=0 && pCheck->mxErr ){
10086     DbPage *pOvflPage;
10087     unsigned char *pOvflData;
10088     if( checkRef(pCheck, iPage) ) break;
10089     N--;
10090     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10091       checkAppendMsg(pCheck, "failed to get page %d", iPage);
10092       break;
10093     }
10094     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10095     if( isFreeList ){
10096       u32 n = (u32)get4byte(&pOvflData[4]);
10097 #ifndef SQLITE_OMIT_AUTOVACUUM
10098       if( pCheck->pBt->autoVacuum ){
10099         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10100       }
10101 #endif
10102       if( n>pCheck->pBt->usableSize/4-2 ){
10103         checkAppendMsg(pCheck,
10104            "freelist leaf count too big on page %d", iPage);
10105         N--;
10106       }else{
10107         for(i=0; i<(int)n; i++){
10108           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10109 #ifndef SQLITE_OMIT_AUTOVACUUM
10110           if( pCheck->pBt->autoVacuum ){
10111             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10112           }
10113 #endif
10114           checkRef(pCheck, iFreePage);
10115         }
10116         N -= n;
10117       }
10118     }
10119 #ifndef SQLITE_OMIT_AUTOVACUUM
10120     else{
10121       /* If this database supports auto-vacuum and iPage is not the last
10122       ** page in this overflow list, check that the pointer-map entry for
10123       ** the following page matches iPage.
10124       */
10125       if( pCheck->pBt->autoVacuum && N>0 ){
10126         i = get4byte(pOvflData);
10127         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10128       }
10129     }
10130 #endif
10131     iPage = get4byte(pOvflData);
10132     sqlite3PagerUnref(pOvflPage);
10133   }
10134   if( N && nErrAtStart==pCheck->nErr ){
10135     checkAppendMsg(pCheck,
10136       "%s is %d but should be %d",
10137       isFreeList ? "size" : "overflow list length",
10138       expected-N, expected);
10139   }
10140 }
10141 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10142 
10143 /*
10144 ** An implementation of a min-heap.
10145 **
10146 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
10147 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
10148 ** and aHeap[N*2+1].
10149 **
10150 ** The heap property is this:  Every node is less than or equal to both
10151 ** of its daughter nodes.  A consequence of the heap property is that the
10152 ** root node aHeap[1] is always the minimum value currently in the heap.
10153 **
10154 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10155 ** the heap, preserving the heap property.  The btreeHeapPull() routine
10156 ** removes the root element from the heap (the minimum value in the heap)
10157 ** and then moves other nodes around as necessary to preserve the heap
10158 ** property.
10159 **
10160 ** This heap is used for cell overlap and coverage testing.  Each u32
10161 ** entry represents the span of a cell or freeblock on a btree page.
10162 ** The upper 16 bits are the index of the first byte of a range and the
10163 ** lower 16 bits are the index of the last byte of that range.
10164 */
10165 static void btreeHeapInsert(u32 *aHeap, u32 x){
10166   u32 j, i = ++aHeap[0];
10167   aHeap[i] = x;
10168   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10169     x = aHeap[j];
10170     aHeap[j] = aHeap[i];
10171     aHeap[i] = x;
10172     i = j;
10173   }
10174 }
10175 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10176   u32 j, i, x;
10177   if( (x = aHeap[0])==0 ) return 0;
10178   *pOut = aHeap[1];
10179   aHeap[1] = aHeap[x];
10180   aHeap[x] = 0xffffffff;
10181   aHeap[0]--;
10182   i = 1;
10183   while( (j = i*2)<=aHeap[0] ){
10184     if( aHeap[j]>aHeap[j+1] ) j++;
10185     if( aHeap[i]<aHeap[j] ) break;
10186     x = aHeap[i];
10187     aHeap[i] = aHeap[j];
10188     aHeap[j] = x;
10189     i = j;
10190   }
10191   return 1;
10192 }
10193 
10194 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10195 /*
10196 ** Do various sanity checks on a single page of a tree.  Return
10197 ** the tree depth.  Root pages return 0.  Parents of root pages
10198 ** return 1, and so forth.
10199 **
10200 ** These checks are done:
10201 **
10202 **      1.  Make sure that cells and freeblocks do not overlap
10203 **          but combine to completely cover the page.
10204 **      2.  Make sure integer cell keys are in order.
10205 **      3.  Check the integrity of overflow pages.
10206 **      4.  Recursively call checkTreePage on all children.
10207 **      5.  Verify that the depth of all children is the same.
10208 */
10209 static int checkTreePage(
10210   IntegrityCk *pCheck,  /* Context for the sanity check */
10211   Pgno iPage,           /* Page number of the page to check */
10212   i64 *piMinKey,        /* Write minimum integer primary key here */
10213   i64 maxKey            /* Error if integer primary key greater than this */
10214 ){
10215   MemPage *pPage = 0;      /* The page being analyzed */
10216   int i;                   /* Loop counter */
10217   int rc;                  /* Result code from subroutine call */
10218   int depth = -1, d2;      /* Depth of a subtree */
10219   int pgno;                /* Page number */
10220   int nFrag;               /* Number of fragmented bytes on the page */
10221   int hdr;                 /* Offset to the page header */
10222   int cellStart;           /* Offset to the start of the cell pointer array */
10223   int nCell;               /* Number of cells */
10224   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10225   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
10226                            ** False if IPK must be strictly less than maxKey */
10227   u8 *data;                /* Page content */
10228   u8 *pCell;               /* Cell content */
10229   u8 *pCellIdx;            /* Next element of the cell pointer array */
10230   BtShared *pBt;           /* The BtShared object that owns pPage */
10231   u32 pc;                  /* Address of a cell */
10232   u32 usableSize;          /* Usable size of the page */
10233   u32 contentOffset;       /* Offset to the start of the cell content area */
10234   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
10235   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
10236   const char *saved_zPfx = pCheck->zPfx;
10237   int saved_v1 = pCheck->v1;
10238   int saved_v2 = pCheck->v2;
10239   u8 savedIsInit = 0;
10240 
10241   /* Check that the page exists
10242   */
10243   pBt = pCheck->pBt;
10244   usableSize = pBt->usableSize;
10245   if( iPage==0 ) return 0;
10246   if( checkRef(pCheck, iPage) ) return 0;
10247   pCheck->zPfx = "Page %u: ";
10248   pCheck->v1 = iPage;
10249   if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10250     checkAppendMsg(pCheck,
10251        "unable to get the page. error code=%d", rc);
10252     goto end_of_check;
10253   }
10254 
10255   /* Clear MemPage.isInit to make sure the corruption detection code in
10256   ** btreeInitPage() is executed.  */
10257   savedIsInit = pPage->isInit;
10258   pPage->isInit = 0;
10259   if( (rc = btreeInitPage(pPage))!=0 ){
10260     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
10261     checkAppendMsg(pCheck,
10262                    "btreeInitPage() returns error code %d", rc);
10263     goto end_of_check;
10264   }
10265   if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10266     assert( rc==SQLITE_CORRUPT );
10267     checkAppendMsg(pCheck, "free space corruption", rc);
10268     goto end_of_check;
10269   }
10270   data = pPage->aData;
10271   hdr = pPage->hdrOffset;
10272 
10273   /* Set up for cell analysis */
10274   pCheck->zPfx = "On tree page %u cell %d: ";
10275   contentOffset = get2byteNotZero(&data[hdr+5]);
10276   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
10277 
10278   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10279   ** number of cells on the page. */
10280   nCell = get2byte(&data[hdr+3]);
10281   assert( pPage->nCell==nCell );
10282 
10283   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10284   ** immediately follows the b-tree page header. */
10285   cellStart = hdr + 12 - 4*pPage->leaf;
10286   assert( pPage->aCellIdx==&data[cellStart] );
10287   pCellIdx = &data[cellStart + 2*(nCell-1)];
10288 
10289   if( !pPage->leaf ){
10290     /* Analyze the right-child page of internal pages */
10291     pgno = get4byte(&data[hdr+8]);
10292 #ifndef SQLITE_OMIT_AUTOVACUUM
10293     if( pBt->autoVacuum ){
10294       pCheck->zPfx = "On page %u at right child: ";
10295       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10296     }
10297 #endif
10298     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10299     keyCanBeEqual = 0;
10300   }else{
10301     /* For leaf pages, the coverage check will occur in the same loop
10302     ** as the other cell checks, so initialize the heap.  */
10303     heap = pCheck->heap;
10304     heap[0] = 0;
10305   }
10306 
10307   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10308   ** integer offsets to the cell contents. */
10309   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10310     CellInfo info;
10311 
10312     /* Check cell size */
10313     pCheck->v2 = i;
10314     assert( pCellIdx==&data[cellStart + i*2] );
10315     pc = get2byteAligned(pCellIdx);
10316     pCellIdx -= 2;
10317     if( pc<contentOffset || pc>usableSize-4 ){
10318       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10319                              pc, contentOffset, usableSize-4);
10320       doCoverageCheck = 0;
10321       continue;
10322     }
10323     pCell = &data[pc];
10324     pPage->xParseCell(pPage, pCell, &info);
10325     if( pc+info.nSize>usableSize ){
10326       checkAppendMsg(pCheck, "Extends off end of page");
10327       doCoverageCheck = 0;
10328       continue;
10329     }
10330 
10331     /* Check for integer primary key out of range */
10332     if( pPage->intKey ){
10333       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10334         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10335       }
10336       maxKey = info.nKey;
10337       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
10338     }
10339 
10340     /* Check the content overflow list */
10341     if( info.nPayload>info.nLocal ){
10342       u32 nPage;       /* Number of pages on the overflow chain */
10343       Pgno pgnoOvfl;   /* First page of the overflow chain */
10344       assert( pc + info.nSize - 4 <= usableSize );
10345       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10346       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10347 #ifndef SQLITE_OMIT_AUTOVACUUM
10348       if( pBt->autoVacuum ){
10349         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10350       }
10351 #endif
10352       checkList(pCheck, 0, pgnoOvfl, nPage);
10353     }
10354 
10355     if( !pPage->leaf ){
10356       /* Check sanity of left child page for internal pages */
10357       pgno = get4byte(pCell);
10358 #ifndef SQLITE_OMIT_AUTOVACUUM
10359       if( pBt->autoVacuum ){
10360         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10361       }
10362 #endif
10363       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10364       keyCanBeEqual = 0;
10365       if( d2!=depth ){
10366         checkAppendMsg(pCheck, "Child page depth differs");
10367         depth = d2;
10368       }
10369     }else{
10370       /* Populate the coverage-checking heap for leaf pages */
10371       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10372     }
10373   }
10374   *piMinKey = maxKey;
10375 
10376   /* Check for complete coverage of the page
10377   */
10378   pCheck->zPfx = 0;
10379   if( doCoverageCheck && pCheck->mxErr>0 ){
10380     /* For leaf pages, the min-heap has already been initialized and the
10381     ** cells have already been inserted.  But for internal pages, that has
10382     ** not yet been done, so do it now */
10383     if( !pPage->leaf ){
10384       heap = pCheck->heap;
10385       heap[0] = 0;
10386       for(i=nCell-1; i>=0; i--){
10387         u32 size;
10388         pc = get2byteAligned(&data[cellStart+i*2]);
10389         size = pPage->xCellSize(pPage, &data[pc]);
10390         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10391       }
10392     }
10393     /* Add the freeblocks to the min-heap
10394     **
10395     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10396     ** is the offset of the first freeblock, or zero if there are no
10397     ** freeblocks on the page.
10398     */
10399     i = get2byte(&data[hdr+1]);
10400     while( i>0 ){
10401       int size, j;
10402       assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10403       size = get2byte(&data[i+2]);
10404       assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10405       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10406       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10407       ** big-endian integer which is the offset in the b-tree page of the next
10408       ** freeblock in the chain, or zero if the freeblock is the last on the
10409       ** chain. */
10410       j = get2byte(&data[i]);
10411       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10412       ** increasing offset. */
10413       assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
10414       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10415       i = j;
10416     }
10417     /* Analyze the min-heap looking for overlap between cells and/or
10418     ** freeblocks, and counting the number of untracked bytes in nFrag.
10419     **
10420     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
10421     ** There is an implied first entry the covers the page header, the cell
10422     ** pointer index, and the gap between the cell pointer index and the start
10423     ** of cell content.
10424     **
10425     ** The loop below pulls entries from the min-heap in order and compares
10426     ** the start_address against the previous end_address.  If there is an
10427     ** overlap, that means bytes are used multiple times.  If there is a gap,
10428     ** that gap is added to the fragmentation count.
10429     */
10430     nFrag = 0;
10431     prev = contentOffset - 1;   /* Implied first min-heap entry */
10432     while( btreeHeapPull(heap,&x) ){
10433       if( (prev&0xffff)>=(x>>16) ){
10434         checkAppendMsg(pCheck,
10435           "Multiple uses for byte %u of page %u", x>>16, iPage);
10436         break;
10437       }else{
10438         nFrag += (x>>16) - (prev&0xffff) - 1;
10439         prev = x;
10440       }
10441     }
10442     nFrag += usableSize - (prev&0xffff) - 1;
10443     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10444     ** is stored in the fifth field of the b-tree page header.
10445     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10446     ** number of fragmented free bytes within the cell content area.
10447     */
10448     if( heap[0]==0 && nFrag!=data[hdr+7] ){
10449       checkAppendMsg(pCheck,
10450           "Fragmentation of %d bytes reported as %d on page %u",
10451           nFrag, data[hdr+7], iPage);
10452     }
10453   }
10454 
10455 end_of_check:
10456   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10457   releasePage(pPage);
10458   pCheck->zPfx = saved_zPfx;
10459   pCheck->v1 = saved_v1;
10460   pCheck->v2 = saved_v2;
10461   return depth+1;
10462 }
10463 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10464 
10465 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10466 /*
10467 ** This routine does a complete check of the given BTree file.  aRoot[] is
10468 ** an array of pages numbers were each page number is the root page of
10469 ** a table.  nRoot is the number of entries in aRoot.
10470 **
10471 ** A read-only or read-write transaction must be opened before calling
10472 ** this function.
10473 **
10474 ** Write the number of error seen in *pnErr.  Except for some memory
10475 ** allocation errors,  an error message held in memory obtained from
10476 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
10477 ** returned.  If a memory allocation error occurs, NULL is returned.
10478 **
10479 ** If the first entry in aRoot[] is 0, that indicates that the list of
10480 ** root pages is incomplete.  This is a "partial integrity-check".  This
10481 ** happens when performing an integrity check on a single table.  The
10482 ** zero is skipped, of course.  But in addition, the freelist checks
10483 ** and the checks to make sure every page is referenced are also skipped,
10484 ** since obviously it is not possible to know which pages are covered by
10485 ** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
10486 ** checks are still performed.
10487 */
10488 char *sqlite3BtreeIntegrityCheck(
10489   sqlite3 *db,  /* Database connection that is running the check */
10490   Btree *p,     /* The btree to be checked */
10491   Pgno *aRoot,  /* An array of root pages numbers for individual trees */
10492   int nRoot,    /* Number of entries in aRoot[] */
10493   int mxErr,    /* Stop reporting errors after this many */
10494   int *pnErr    /* Write number of errors seen to this variable */
10495 ){
10496   Pgno i;
10497   IntegrityCk sCheck;
10498   BtShared *pBt = p->pBt;
10499   u64 savedDbFlags = pBt->db->flags;
10500   char zErr[100];
10501   int bPartial = 0;            /* True if not checking all btrees */
10502   int bCkFreelist = 1;         /* True to scan the freelist */
10503   VVA_ONLY( int nRef );
10504   assert( nRoot>0 );
10505 
10506   /* aRoot[0]==0 means this is a partial check */
10507   if( aRoot[0]==0 ){
10508     assert( nRoot>1 );
10509     bPartial = 1;
10510     if( aRoot[1]!=1 ) bCkFreelist = 0;
10511   }
10512 
10513   sqlite3BtreeEnter(p);
10514   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10515   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10516   assert( nRef>=0 );
10517   sCheck.db = db;
10518   sCheck.pBt = pBt;
10519   sCheck.pPager = pBt->pPager;
10520   sCheck.nPage = btreePagecount(sCheck.pBt);
10521   sCheck.mxErr = mxErr;
10522   sCheck.nErr = 0;
10523   sCheck.bOomFault = 0;
10524   sCheck.zPfx = 0;
10525   sCheck.v1 = 0;
10526   sCheck.v2 = 0;
10527   sCheck.aPgRef = 0;
10528   sCheck.heap = 0;
10529   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10530   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10531   if( sCheck.nPage==0 ){
10532     goto integrity_ck_cleanup;
10533   }
10534 
10535   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10536   if( !sCheck.aPgRef ){
10537     sCheck.bOomFault = 1;
10538     goto integrity_ck_cleanup;
10539   }
10540   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10541   if( sCheck.heap==0 ){
10542     sCheck.bOomFault = 1;
10543     goto integrity_ck_cleanup;
10544   }
10545 
10546   i = PENDING_BYTE_PAGE(pBt);
10547   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10548 
10549   /* Check the integrity of the freelist
10550   */
10551   if( bCkFreelist ){
10552     sCheck.zPfx = "Main freelist: ";
10553     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10554               get4byte(&pBt->pPage1->aData[36]));
10555     sCheck.zPfx = 0;
10556   }
10557 
10558   /* Check all the tables.
10559   */
10560 #ifndef SQLITE_OMIT_AUTOVACUUM
10561   if( !bPartial ){
10562     if( pBt->autoVacuum ){
10563       Pgno mx = 0;
10564       Pgno mxInHdr;
10565       for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10566       mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10567       if( mx!=mxInHdr ){
10568         checkAppendMsg(&sCheck,
10569           "max rootpage (%d) disagrees with header (%d)",
10570           mx, mxInHdr
10571         );
10572       }
10573     }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10574       checkAppendMsg(&sCheck,
10575         "incremental_vacuum enabled with a max rootpage of zero"
10576       );
10577     }
10578   }
10579 #endif
10580   testcase( pBt->db->flags & SQLITE_CellSizeCk );
10581   pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10582   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10583     i64 notUsed;
10584     if( aRoot[i]==0 ) continue;
10585 #ifndef SQLITE_OMIT_AUTOVACUUM
10586     if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10587       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10588     }
10589 #endif
10590     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10591   }
10592   pBt->db->flags = savedDbFlags;
10593 
10594   /* Make sure every page in the file is referenced
10595   */
10596   if( !bPartial ){
10597     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10598 #ifdef SQLITE_OMIT_AUTOVACUUM
10599       if( getPageReferenced(&sCheck, i)==0 ){
10600         checkAppendMsg(&sCheck, "Page %d is never used", i);
10601       }
10602 #else
10603       /* If the database supports auto-vacuum, make sure no tables contain
10604       ** references to pointer-map pages.
10605       */
10606       if( getPageReferenced(&sCheck, i)==0 &&
10607          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10608         checkAppendMsg(&sCheck, "Page %d is never used", i);
10609       }
10610       if( getPageReferenced(&sCheck, i)!=0 &&
10611          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10612         checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10613       }
10614 #endif
10615     }
10616   }
10617 
10618   /* Clean  up and report errors.
10619   */
10620 integrity_ck_cleanup:
10621   sqlite3PageFree(sCheck.heap);
10622   sqlite3_free(sCheck.aPgRef);
10623   if( sCheck.bOomFault ){
10624     sqlite3_str_reset(&sCheck.errMsg);
10625     sCheck.nErr++;
10626   }
10627   *pnErr = sCheck.nErr;
10628   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10629   /* Make sure this analysis did not leave any unref() pages. */
10630   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10631   sqlite3BtreeLeave(p);
10632   return sqlite3StrAccumFinish(&sCheck.errMsg);
10633 }
10634 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10635 
10636 /*
10637 ** Return the full pathname of the underlying database file.  Return
10638 ** an empty string if the database is in-memory or a TEMP database.
10639 **
10640 ** The pager filename is invariant as long as the pager is
10641 ** open so it is safe to access without the BtShared mutex.
10642 */
10643 const char *sqlite3BtreeGetFilename(Btree *p){
10644   assert( p->pBt->pPager!=0 );
10645   return sqlite3PagerFilename(p->pBt->pPager, 1);
10646 }
10647 
10648 /*
10649 ** Return the pathname of the journal file for this database. The return
10650 ** value of this routine is the same regardless of whether the journal file
10651 ** has been created or not.
10652 **
10653 ** The pager journal filename is invariant as long as the pager is
10654 ** open so it is safe to access without the BtShared mutex.
10655 */
10656 const char *sqlite3BtreeGetJournalname(Btree *p){
10657   assert( p->pBt->pPager!=0 );
10658   return sqlite3PagerJournalname(p->pBt->pPager);
10659 }
10660 
10661 /*
10662 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10663 ** to describe the current transaction state of Btree p.
10664 */
10665 int sqlite3BtreeTxnState(Btree *p){
10666   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10667   return p ? p->inTrans : 0;
10668 }
10669 
10670 #ifndef SQLITE_OMIT_WAL
10671 /*
10672 ** Run a checkpoint on the Btree passed as the first argument.
10673 **
10674 ** Return SQLITE_LOCKED if this or any other connection has an open
10675 ** transaction on the shared-cache the argument Btree is connected to.
10676 **
10677 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10678 */
10679 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10680   int rc = SQLITE_OK;
10681   if( p ){
10682     BtShared *pBt = p->pBt;
10683     sqlite3BtreeEnter(p);
10684     if( pBt->inTransaction!=TRANS_NONE ){
10685       rc = SQLITE_LOCKED;
10686     }else{
10687       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10688     }
10689     sqlite3BtreeLeave(p);
10690   }
10691   return rc;
10692 }
10693 #endif
10694 
10695 /*
10696 ** Return true if there is currently a backup running on Btree p.
10697 */
10698 int sqlite3BtreeIsInBackup(Btree *p){
10699   assert( p );
10700   assert( sqlite3_mutex_held(p->db->mutex) );
10701   return p->nBackup!=0;
10702 }
10703 
10704 /*
10705 ** This function returns a pointer to a blob of memory associated with
10706 ** a single shared-btree. The memory is used by client code for its own
10707 ** purposes (for example, to store a high-level schema associated with
10708 ** the shared-btree). The btree layer manages reference counting issues.
10709 **
10710 ** The first time this is called on a shared-btree, nBytes bytes of memory
10711 ** are allocated, zeroed, and returned to the caller. For each subsequent
10712 ** call the nBytes parameter is ignored and a pointer to the same blob
10713 ** of memory returned.
10714 **
10715 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10716 ** allocated, a null pointer is returned. If the blob has already been
10717 ** allocated, it is returned as normal.
10718 **
10719 ** Just before the shared-btree is closed, the function passed as the
10720 ** xFree argument when the memory allocation was made is invoked on the
10721 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10722 ** on the memory, the btree layer does that.
10723 */
10724 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10725   BtShared *pBt = p->pBt;
10726   sqlite3BtreeEnter(p);
10727   if( !pBt->pSchema && nBytes ){
10728     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10729     pBt->xFreeSchema = xFree;
10730   }
10731   sqlite3BtreeLeave(p);
10732   return pBt->pSchema;
10733 }
10734 
10735 /*
10736 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10737 ** btree as the argument handle holds an exclusive lock on the
10738 ** sqlite_schema table. Otherwise SQLITE_OK.
10739 */
10740 int sqlite3BtreeSchemaLocked(Btree *p){
10741   int rc;
10742   assert( sqlite3_mutex_held(p->db->mutex) );
10743   sqlite3BtreeEnter(p);
10744   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10745   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10746   sqlite3BtreeLeave(p);
10747   return rc;
10748 }
10749 
10750 
10751 #ifndef SQLITE_OMIT_SHARED_CACHE
10752 /*
10753 ** Obtain a lock on the table whose root page is iTab.  The
10754 ** lock is a write lock if isWritelock is true or a read lock
10755 ** if it is false.
10756 */
10757 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10758   int rc = SQLITE_OK;
10759   assert( p->inTrans!=TRANS_NONE );
10760   if( p->sharable ){
10761     u8 lockType = READ_LOCK + isWriteLock;
10762     assert( READ_LOCK+1==WRITE_LOCK );
10763     assert( isWriteLock==0 || isWriteLock==1 );
10764 
10765     sqlite3BtreeEnter(p);
10766     rc = querySharedCacheTableLock(p, iTab, lockType);
10767     if( rc==SQLITE_OK ){
10768       rc = setSharedCacheTableLock(p, iTab, lockType);
10769     }
10770     sqlite3BtreeLeave(p);
10771   }
10772   return rc;
10773 }
10774 #endif
10775 
10776 #ifndef SQLITE_OMIT_INCRBLOB
10777 /*
10778 ** Argument pCsr must be a cursor opened for writing on an
10779 ** INTKEY table currently pointing at a valid table entry.
10780 ** This function modifies the data stored as part of that entry.
10781 **
10782 ** Only the data content may only be modified, it is not possible to
10783 ** change the length of the data stored. If this function is called with
10784 ** parameters that attempt to write past the end of the existing data,
10785 ** no modifications are made and SQLITE_CORRUPT is returned.
10786 */
10787 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10788   int rc;
10789   assert( cursorOwnsBtShared(pCsr) );
10790   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10791   assert( pCsr->curFlags & BTCF_Incrblob );
10792 
10793   rc = restoreCursorPosition(pCsr);
10794   if( rc!=SQLITE_OK ){
10795     return rc;
10796   }
10797   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10798   if( pCsr->eState!=CURSOR_VALID ){
10799     return SQLITE_ABORT;
10800   }
10801 
10802   /* Save the positions of all other cursors open on this table. This is
10803   ** required in case any of them are holding references to an xFetch
10804   ** version of the b-tree page modified by the accessPayload call below.
10805   **
10806   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10807   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10808   ** saveAllCursors can only return SQLITE_OK.
10809   */
10810   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10811   assert( rc==SQLITE_OK );
10812 
10813   /* Check some assumptions:
10814   **   (a) the cursor is open for writing,
10815   **   (b) there is a read/write transaction open,
10816   **   (c) the connection holds a write-lock on the table (if required),
10817   **   (d) there are no conflicting read-locks, and
10818   **   (e) the cursor points at a valid row of an intKey table.
10819   */
10820   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10821     return SQLITE_READONLY;
10822   }
10823   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10824               && pCsr->pBt->inTransaction==TRANS_WRITE );
10825   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10826   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10827   assert( pCsr->pPage->intKey );
10828 
10829   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10830 }
10831 
10832 /*
10833 ** Mark this cursor as an incremental blob cursor.
10834 */
10835 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10836   pCur->curFlags |= BTCF_Incrblob;
10837   pCur->pBtree->hasIncrblobCur = 1;
10838 }
10839 #endif
10840 
10841 /*
10842 ** Set both the "read version" (single byte at byte offset 18) and
10843 ** "write version" (single byte at byte offset 19) fields in the database
10844 ** header to iVersion.
10845 */
10846 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10847   BtShared *pBt = pBtree->pBt;
10848   int rc;                         /* Return code */
10849 
10850   assert( iVersion==1 || iVersion==2 );
10851 
10852   /* If setting the version fields to 1, do not automatically open the
10853   ** WAL connection, even if the version fields are currently set to 2.
10854   */
10855   pBt->btsFlags &= ~BTS_NO_WAL;
10856   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10857 
10858   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10859   if( rc==SQLITE_OK ){
10860     u8 *aData = pBt->pPage1->aData;
10861     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10862       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10863       if( rc==SQLITE_OK ){
10864         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10865         if( rc==SQLITE_OK ){
10866           aData[18] = (u8)iVersion;
10867           aData[19] = (u8)iVersion;
10868         }
10869       }
10870     }
10871   }
10872 
10873   pBt->btsFlags &= ~BTS_NO_WAL;
10874   return rc;
10875 }
10876 
10877 /*
10878 ** Return true if the cursor has a hint specified.  This routine is
10879 ** only used from within assert() statements
10880 */
10881 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10882   return (pCsr->hints & mask)!=0;
10883 }
10884 
10885 /*
10886 ** Return true if the given Btree is read-only.
10887 */
10888 int sqlite3BtreeIsReadonly(Btree *p){
10889   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10890 }
10891 
10892 /*
10893 ** Return the size of the header added to each page by this module.
10894 */
10895 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10896 
10897 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10898 /*
10899 ** Return true if the Btree passed as the only argument is sharable.
10900 */
10901 int sqlite3BtreeSharable(Btree *p){
10902   return p->sharable;
10903 }
10904 
10905 /*
10906 ** Return the number of connections to the BtShared object accessed by
10907 ** the Btree handle passed as the only argument. For private caches
10908 ** this is always 1. For shared caches it may be 1 or greater.
10909 */
10910 int sqlite3BtreeConnectionCount(Btree *p){
10911   testcase( p->sharable );
10912   return p->pBt->nRef;
10913 }
10914 #endif
10915