xref: /sqlite-3.40.0/src/btree.c (revision a4cd0bbc)
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file implements an external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
15 */
16 #include "btreeInt.h"
17 
18 /*
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
21 */
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
23 
24 /*
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
27 */
28 #if 0
29 int sqlite3BtreeTrace=1;  /* True to enable tracing */
30 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
34 
35 /*
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
38 **
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page.  If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
43 */
44 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
45 
46 /*
47 ** Values passed as the 5th argument to allocateBtreePage()
48 */
49 #define BTALLOC_ANY   0           /* Allocate any page */
50 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
51 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
52 
53 /*
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
56 **
57 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58 */
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
64 
65 #ifndef SQLITE_OMIT_SHARED_CACHE
66 /*
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache.  This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
71 **
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
73 */
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
80 
81 #ifndef SQLITE_OMIT_SHARED_CACHE
82 /*
83 ** Enable or disable the shared pager and schema features.
84 **
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
88 */
89 int sqlite3_enable_shared_cache(int enable){
90   sqlite3GlobalConfig.sharedCacheEnabled = enable;
91   return SQLITE_OK;
92 }
93 #endif
94 
95 
96 
97 #ifdef SQLITE_OMIT_SHARED_CACHE
98   /*
99   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100   ** and clearAllSharedCacheTableLocks()
101   ** manipulate entries in the BtShared.pLock linked list used to store
102   ** shared-cache table level locks. If the library is compiled with the
103   ** shared-cache feature disabled, then there is only ever one user
104   ** of each BtShared structure and so this locking is not necessary.
105   ** So define the lock related functions as no-ops.
106   */
107   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109   #define clearAllSharedCacheTableLocks(a)
110   #define downgradeAllSharedCacheTableLocks(a)
111   #define hasSharedCacheTableLock(a,b,c,d) 1
112   #define hasReadConflicts(a, b) 0
113 #endif
114 
115 #ifdef SQLITE_DEBUG
116 /*
117 ** Return and reset the seek counter for a Btree object.
118 */
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120   u64 n =  pBt->nSeek;
121   pBt->nSeek = 0;
122   return n;
123 }
124 #endif
125 
126 /*
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
129 **
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
134 */
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137   char *zMsg;
138   sqlite3BeginBenignMalloc();
139   zMsg = sqlite3_mprintf("database corruption page %d of %s",
140       (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
141   );
142   sqlite3EndBenignMalloc();
143   if( zMsg ){
144     sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
145   }
146   sqlite3_free(zMsg);
147   return SQLITE_CORRUPT_BKPT;
148 }
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
153 
154 #ifndef SQLITE_OMIT_SHARED_CACHE
155 
156 #ifdef SQLITE_DEBUG
157 /*
158 **** This function is only used as part of an assert() statement. ***
159 **
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot.   Return 1 if it does and 0 if not.
162 **
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
165 **
166 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
167 **
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
174 **
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
178 */
179 static int hasSharedCacheTableLock(
180   Btree *pBtree,         /* Handle that must hold lock */
181   Pgno iRoot,            /* Root page of b-tree */
182   int isIndex,           /* True if iRoot is the root of an index b-tree */
183   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
184 ){
185   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186   Pgno iTab = 0;
187   BtLock *pLock;
188 
189   /* If this database is not shareable, or if the client is reading
190   ** and has the read-uncommitted flag set, then no lock is required.
191   ** Return true immediately.
192   */
193   if( (pBtree->sharable==0)
194    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
195   ){
196     return 1;
197   }
198 
199   /* If the client is reading  or writing an index and the schema is
200   ** not loaded, then it is too difficult to actually check to see if
201   ** the correct locks are held.  So do not bother - just return true.
202   ** This case does not come up very often anyhow.
203   */
204   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205     return 1;
206   }
207 
208   /* Figure out the root-page that the lock should be held on. For table
209   ** b-trees, this is just the root page of the b-tree being read or
210   ** written. For index b-trees, it is the root page of the associated
211   ** table.  */
212   if( isIndex ){
213     HashElem *p;
214     int bSeen = 0;
215     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216       Index *pIdx = (Index *)sqliteHashData(p);
217       if( pIdx->tnum==(int)iRoot ){
218         if( bSeen ){
219           /* Two or more indexes share the same root page.  There must
220           ** be imposter tables.  So just return true.  The assert is not
221           ** useful in that case. */
222           return 1;
223         }
224         iTab = pIdx->pTable->tnum;
225         bSeen = 1;
226       }
227     }
228   }else{
229     iTab = iRoot;
230   }
231 
232   /* Search for the required lock. Either a write-lock on root-page iTab, a
233   ** write-lock on the schema table, or (if the client is reading) a
234   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
235   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236     if( pLock->pBtree==pBtree
237      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238      && pLock->eLock>=eLockType
239     ){
240       return 1;
241     }
242   }
243 
244   /* Failed to find the required lock. */
245   return 0;
246 }
247 #endif /* SQLITE_DEBUG */
248 
249 #ifdef SQLITE_DEBUG
250 /*
251 **** This function may be used as part of assert() statements only. ****
252 **
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
256 **
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table.  Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
262 **
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
265 **
266 **    assert( !hasReadConflicts(pBtree, iRoot) );
267 */
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269   BtCursor *p;
270   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271     if( p->pgnoRoot==iRoot
272      && p->pBtree!=pBtree
273      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
274     ){
275       return 1;
276     }
277   }
278   return 0;
279 }
280 #endif    /* #ifdef SQLITE_DEBUG */
281 
282 /*
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
287 */
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289   BtShared *pBt = p->pBt;
290   BtLock *pIter;
291 
292   assert( sqlite3BtreeHoldsMutex(p) );
293   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294   assert( p->db!=0 );
295   assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
296 
297   /* If requesting a write-lock, then the Btree must have an open write
298   ** transaction on this file. And, obviously, for this to be so there
299   ** must be an open write transaction on the file itself.
300   */
301   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
303 
304   /* This routine is a no-op if the shared-cache is not enabled */
305   if( !p->sharable ){
306     return SQLITE_OK;
307   }
308 
309   /* If some other connection is holding an exclusive lock, the
310   ** requested lock may not be obtained.
311   */
312   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314     return SQLITE_LOCKED_SHAREDCACHE;
315   }
316 
317   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318     /* The condition (pIter->eLock!=eLock) in the following if(...)
319     ** statement is a simplification of:
320     **
321     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
322     **
323     ** since we know that if eLock==WRITE_LOCK, then no other connection
324     ** may hold a WRITE_LOCK on any table in this file (since there can
325     ** only be a single writer).
326     */
327     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331       if( eLock==WRITE_LOCK ){
332         assert( p==pBt->pWriter );
333         pBt->btsFlags |= BTS_PENDING;
334       }
335       return SQLITE_LOCKED_SHAREDCACHE;
336     }
337   }
338   return SQLITE_OK;
339 }
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
341 
342 #ifndef SQLITE_OMIT_SHARED_CACHE
343 /*
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
347 **
348 ** This function assumes the following:
349 **
350 **   (a) The specified Btree object p is connected to a sharable
351 **       database (one with the BtShared.sharable flag set), and
352 **
353 **   (b) No other Btree objects hold a lock that conflicts
354 **       with the requested lock (i.e. querySharedCacheTableLock() has
355 **       already been called and returned SQLITE_OK).
356 **
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
359 */
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361   BtShared *pBt = p->pBt;
362   BtLock *pLock = 0;
363   BtLock *pIter;
364 
365   assert( sqlite3BtreeHoldsMutex(p) );
366   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367   assert( p->db!=0 );
368 
369   /* A connection with the read-uncommitted flag set will never try to
370   ** obtain a read-lock using this function. The only read-lock obtained
371   ** by a connection in read-uncommitted mode is on the sqlite_schema
372   ** table, and that lock is obtained in BtreeBeginTrans().  */
373   assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
374 
375   /* This function should only be called on a sharable b-tree after it
376   ** has been determined that no other b-tree holds a conflicting lock.  */
377   assert( p->sharable );
378   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
379 
380   /* First search the list for an existing lock on this table. */
381   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382     if( pIter->iTable==iTable && pIter->pBtree==p ){
383       pLock = pIter;
384       break;
385     }
386   }
387 
388   /* If the above search did not find a BtLock struct associating Btree p
389   ** with table iTable, allocate one and link it into the list.
390   */
391   if( !pLock ){
392     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393     if( !pLock ){
394       return SQLITE_NOMEM_BKPT;
395     }
396     pLock->iTable = iTable;
397     pLock->pBtree = p;
398     pLock->pNext = pBt->pLock;
399     pBt->pLock = pLock;
400   }
401 
402   /* Set the BtLock.eLock variable to the maximum of the current lock
403   ** and the requested lock. This means if a write-lock was already held
404   ** and a read-lock requested, we don't incorrectly downgrade the lock.
405   */
406   assert( WRITE_LOCK>READ_LOCK );
407   if( eLock>pLock->eLock ){
408     pLock->eLock = eLock;
409   }
410 
411   return SQLITE_OK;
412 }
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
414 
415 #ifndef SQLITE_OMIT_SHARED_CACHE
416 /*
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
419 **
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
423 */
424 static void clearAllSharedCacheTableLocks(Btree *p){
425   BtShared *pBt = p->pBt;
426   BtLock **ppIter = &pBt->pLock;
427 
428   assert( sqlite3BtreeHoldsMutex(p) );
429   assert( p->sharable || 0==*ppIter );
430   assert( p->inTrans>0 );
431 
432   while( *ppIter ){
433     BtLock *pLock = *ppIter;
434     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435     assert( pLock->pBtree->inTrans>=pLock->eLock );
436     if( pLock->pBtree==p ){
437       *ppIter = pLock->pNext;
438       assert( pLock->iTable!=1 || pLock==&p->lock );
439       if( pLock->iTable!=1 ){
440         sqlite3_free(pLock);
441       }
442     }else{
443       ppIter = &pLock->pNext;
444     }
445   }
446 
447   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448   if( pBt->pWriter==p ){
449     pBt->pWriter = 0;
450     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451   }else if( pBt->nTransaction==2 ){
452     /* This function is called when Btree p is concluding its
453     ** transaction. If there currently exists a writer, and p is not
454     ** that writer, then the number of locks held by connections other
455     ** than the writer must be about to drop to zero. In this case
456     ** set the BTS_PENDING flag to 0.
457     **
458     ** If there is not currently a writer, then BTS_PENDING must
459     ** be zero already. So this next line is harmless in that case.
460     */
461     pBt->btsFlags &= ~BTS_PENDING;
462   }
463 }
464 
465 /*
466 ** This function changes all write-locks held by Btree p into read-locks.
467 */
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469   BtShared *pBt = p->pBt;
470   if( pBt->pWriter==p ){
471     BtLock *pLock;
472     pBt->pWriter = 0;
473     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476       pLock->eLock = READ_LOCK;
477     }
478   }
479 }
480 
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
482 
483 static void releasePage(MemPage *pPage);         /* Forward reference */
484 static void releasePageOne(MemPage *pPage);      /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
486 
487 /*
488 ***** This routine is used inside of assert() only ****
489 **
490 ** Verify that the cursor holds the mutex on its BtShared
491 */
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494   return sqlite3_mutex_held(p->pBt->mutex);
495 }
496 
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed.  This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
504 */
505 static int cursorOwnsBtShared(BtCursor *p){
506   assert( cursorHoldsMutex(p) );
507   return (p->pBtree->db==p->pBt->db);
508 }
509 #endif
510 
511 /*
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
514 */
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
516 
517 /*
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
520 */
521 static void invalidateAllOverflowCache(BtShared *pBt){
522   BtCursor *p;
523   assert( sqlite3_mutex_held(pBt->mutex) );
524   for(p=pBt->pCursor; p; p=p->pNext){
525     invalidateOverflowCache(p);
526   }
527 }
528 
529 #ifndef SQLITE_OMIT_INCRBLOB
530 /*
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
534 **
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
538 **
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
542 */
543 static void invalidateIncrblobCursors(
544   Btree *pBtree,          /* The database file to check */
545   Pgno pgnoRoot,          /* The table that might be changing */
546   i64 iRow,               /* The rowid that might be changing */
547   int isClearTable        /* True if all rows are being deleted */
548 ){
549   BtCursor *p;
550   if( pBtree->hasIncrblobCur==0 ) return;
551   assert( sqlite3BtreeHoldsMutex(pBtree) );
552   pBtree->hasIncrblobCur = 0;
553   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
554     if( (p->curFlags & BTCF_Incrblob)!=0 ){
555       pBtree->hasIncrblobCur = 1;
556       if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
557         p->eState = CURSOR_INVALID;
558       }
559     }
560   }
561 }
562 
563 #else
564   /* Stub function when INCRBLOB is omitted */
565   #define invalidateIncrblobCursors(w,x,y,z)
566 #endif /* SQLITE_OMIT_INCRBLOB */
567 
568 /*
569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
570 ** when a page that previously contained data becomes a free-list leaf
571 ** page.
572 **
573 ** The BtShared.pHasContent bitvec exists to work around an obscure
574 ** bug caused by the interaction of two useful IO optimizations surrounding
575 ** free-list leaf pages:
576 **
577 **   1) When all data is deleted from a page and the page becomes
578 **      a free-list leaf page, the page is not written to the database
579 **      (as free-list leaf pages contain no meaningful data). Sometimes
580 **      such a page is not even journalled (as it will not be modified,
581 **      why bother journalling it?).
582 **
583 **   2) When a free-list leaf page is reused, its content is not read
584 **      from the database or written to the journal file (why should it
585 **      be, if it is not at all meaningful?).
586 **
587 ** By themselves, these optimizations work fine and provide a handy
588 ** performance boost to bulk delete or insert operations. However, if
589 ** a page is moved to the free-list and then reused within the same
590 ** transaction, a problem comes up. If the page is not journalled when
591 ** it is moved to the free-list and it is also not journalled when it
592 ** is extracted from the free-list and reused, then the original data
593 ** may be lost. In the event of a rollback, it may not be possible
594 ** to restore the database to its original configuration.
595 **
596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
597 ** moved to become a free-list leaf page, the corresponding bit is
598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
599 ** optimization 2 above is omitted if the corresponding bit is already
600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
601 ** at the end of every transaction.
602 */
603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
604   int rc = SQLITE_OK;
605   if( !pBt->pHasContent ){
606     assert( pgno<=pBt->nPage );
607     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
608     if( !pBt->pHasContent ){
609       rc = SQLITE_NOMEM_BKPT;
610     }
611   }
612   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
613     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
614   }
615   return rc;
616 }
617 
618 /*
619 ** Query the BtShared.pHasContent vector.
620 **
621 ** This function is called when a free-list leaf page is removed from the
622 ** free-list for reuse. It returns false if it is safe to retrieve the
623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
624 */
625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
626   Bitvec *p = pBt->pHasContent;
627   return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
628 }
629 
630 /*
631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
632 ** invoked at the conclusion of each write-transaction.
633 */
634 static void btreeClearHasContent(BtShared *pBt){
635   sqlite3BitvecDestroy(pBt->pHasContent);
636   pBt->pHasContent = 0;
637 }
638 
639 /*
640 ** Release all of the apPage[] pages for a cursor.
641 */
642 static void btreeReleaseAllCursorPages(BtCursor *pCur){
643   int i;
644   if( pCur->iPage>=0 ){
645     for(i=0; i<pCur->iPage; i++){
646       releasePageNotNull(pCur->apPage[i]);
647     }
648     releasePageNotNull(pCur->pPage);
649     pCur->iPage = -1;
650   }
651 }
652 
653 /*
654 ** The cursor passed as the only argument must point to a valid entry
655 ** when this function is called (i.e. have eState==CURSOR_VALID). This
656 ** function saves the current cursor key in variables pCur->nKey and
657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
658 ** code otherwise.
659 **
660 ** If the cursor is open on an intkey table, then the integer key
661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
663 ** set to point to a malloced buffer pCur->nKey bytes in size containing
664 ** the key.
665 */
666 static int saveCursorKey(BtCursor *pCur){
667   int rc = SQLITE_OK;
668   assert( CURSOR_VALID==pCur->eState );
669   assert( 0==pCur->pKey );
670   assert( cursorHoldsMutex(pCur) );
671 
672   if( pCur->curIntKey ){
673     /* Only the rowid is required for a table btree */
674     pCur->nKey = sqlite3BtreeIntegerKey(pCur);
675   }else{
676     /* For an index btree, save the complete key content. It is possible
677     ** that the current key is corrupt. In that case, it is possible that
678     ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
679     ** up to the size of 1 varint plus 1 8-byte value when the cursor
680     ** position is restored. Hence the 17 bytes of padding allocated
681     ** below. */
682     void *pKey;
683     pCur->nKey = sqlite3BtreePayloadSize(pCur);
684     pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
685     if( pKey ){
686       rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
687       if( rc==SQLITE_OK ){
688         memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
689         pCur->pKey = pKey;
690       }else{
691         sqlite3_free(pKey);
692       }
693     }else{
694       rc = SQLITE_NOMEM_BKPT;
695     }
696   }
697   assert( !pCur->curIntKey || !pCur->pKey );
698   return rc;
699 }
700 
701 /*
702 ** Save the current cursor position in the variables BtCursor.nKey
703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
704 **
705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
706 ** prior to calling this routine.
707 */
708 static int saveCursorPosition(BtCursor *pCur){
709   int rc;
710 
711   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
712   assert( 0==pCur->pKey );
713   assert( cursorHoldsMutex(pCur) );
714 
715   if( pCur->curFlags & BTCF_Pinned ){
716     return SQLITE_CONSTRAINT_PINNED;
717   }
718   if( pCur->eState==CURSOR_SKIPNEXT ){
719     pCur->eState = CURSOR_VALID;
720   }else{
721     pCur->skipNext = 0;
722   }
723 
724   rc = saveCursorKey(pCur);
725   if( rc==SQLITE_OK ){
726     btreeReleaseAllCursorPages(pCur);
727     pCur->eState = CURSOR_REQUIRESEEK;
728   }
729 
730   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
731   return rc;
732 }
733 
734 /* Forward reference */
735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
736 
737 /*
738 ** Save the positions of all cursors (except pExcept) that are open on
739 ** the table with root-page iRoot.  "Saving the cursor position" means that
740 ** the location in the btree is remembered in such a way that it can be
741 ** moved back to the same spot after the btree has been modified.  This
742 ** routine is called just before cursor pExcept is used to modify the
743 ** table, for example in BtreeDelete() or BtreeInsert().
744 **
745 ** If there are two or more cursors on the same btree, then all such
746 ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
747 ** routine enforces that rule.  This routine only needs to be called in
748 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
749 **
750 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
752 ** pointless call to this routine.
753 **
754 ** Implementation note:  This routine merely checks to see if any cursors
755 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
756 ** event that cursors are in need to being saved.
757 */
758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
759   BtCursor *p;
760   assert( sqlite3_mutex_held(pBt->mutex) );
761   assert( pExcept==0 || pExcept->pBt==pBt );
762   for(p=pBt->pCursor; p; p=p->pNext){
763     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
764   }
765   if( p ) return saveCursorsOnList(p, iRoot, pExcept);
766   if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
767   return SQLITE_OK;
768 }
769 
770 /* This helper routine to saveAllCursors does the actual work of saving
771 ** the cursors if and when a cursor is found that actually requires saving.
772 ** The common case is that no cursors need to be saved, so this routine is
773 ** broken out from its caller to avoid unnecessary stack pointer movement.
774 */
775 static int SQLITE_NOINLINE saveCursorsOnList(
776   BtCursor *p,         /* The first cursor that needs saving */
777   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
778   BtCursor *pExcept    /* Do not save this cursor */
779 ){
780   do{
781     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
782       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
783         int rc = saveCursorPosition(p);
784         if( SQLITE_OK!=rc ){
785           return rc;
786         }
787       }else{
788         testcase( p->iPage>=0 );
789         btreeReleaseAllCursorPages(p);
790       }
791     }
792     p = p->pNext;
793   }while( p );
794   return SQLITE_OK;
795 }
796 
797 /*
798 ** Clear the current cursor position.
799 */
800 void sqlite3BtreeClearCursor(BtCursor *pCur){
801   assert( cursorHoldsMutex(pCur) );
802   sqlite3_free(pCur->pKey);
803   pCur->pKey = 0;
804   pCur->eState = CURSOR_INVALID;
805 }
806 
807 /*
808 ** In this version of BtreeMoveto, pKey is a packed index record
809 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
810 ** record and then call BtreeMovetoUnpacked() to do the work.
811 */
812 static int btreeMoveto(
813   BtCursor *pCur,     /* Cursor open on the btree to be searched */
814   const void *pKey,   /* Packed key if the btree is an index */
815   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
816   int bias,           /* Bias search to the high end */
817   int *pRes           /* Write search results here */
818 ){
819   int rc;                    /* Status code */
820   UnpackedRecord *pIdxKey;   /* Unpacked index key */
821 
822   if( pKey ){
823     KeyInfo *pKeyInfo = pCur->pKeyInfo;
824     assert( nKey==(i64)(int)nKey );
825     pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826     if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827     sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828     if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829       rc = SQLITE_CORRUPT_BKPT;
830       goto moveto_done;
831     }
832   }else{
833     pIdxKey = 0;
834   }
835   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
836 moveto_done:
837   if( pIdxKey ){
838     sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
839   }
840   return rc;
841 }
842 
843 /*
844 ** Restore the cursor to the position it was in (or as close to as possible)
845 ** when saveCursorPosition() was called. Note that this call deletes the
846 ** saved position info stored by saveCursorPosition(), so there can be
847 ** at most one effective restoreCursorPosition() call after each
848 ** saveCursorPosition().
849 */
850 static int btreeRestoreCursorPosition(BtCursor *pCur){
851   int rc;
852   int skipNext = 0;
853   assert( cursorOwnsBtShared(pCur) );
854   assert( pCur->eState>=CURSOR_REQUIRESEEK );
855   if( pCur->eState==CURSOR_FAULT ){
856     return pCur->skipNext;
857   }
858   pCur->eState = CURSOR_INVALID;
859   if( sqlite3FaultSim(410) ){
860     rc = SQLITE_IOERR;
861   }else{
862     rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
863   }
864   if( rc==SQLITE_OK ){
865     sqlite3_free(pCur->pKey);
866     pCur->pKey = 0;
867     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
868     if( skipNext ) pCur->skipNext = skipNext;
869     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
870       pCur->eState = CURSOR_SKIPNEXT;
871     }
872   }
873   return rc;
874 }
875 
876 #define restoreCursorPosition(p) \
877   (p->eState>=CURSOR_REQUIRESEEK ? \
878          btreeRestoreCursorPosition(p) : \
879          SQLITE_OK)
880 
881 /*
882 ** Determine whether or not a cursor has moved from the position where
883 ** it was last placed, or has been invalidated for any other reason.
884 ** Cursors can move when the row they are pointing at is deleted out
885 ** from under them, for example.  Cursor might also move if a btree
886 ** is rebalanced.
887 **
888 ** Calling this routine with a NULL cursor pointer returns false.
889 **
890 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
891 ** back to where it ought to be if this routine returns true.
892 */
893 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
894   assert( EIGHT_BYTE_ALIGNMENT(pCur)
895        || pCur==sqlite3BtreeFakeValidCursor() );
896   assert( offsetof(BtCursor, eState)==0 );
897   assert( sizeof(pCur->eState)==1 );
898   return CURSOR_VALID != *(u8*)pCur;
899 }
900 
901 /*
902 ** Return a pointer to a fake BtCursor object that will always answer
903 ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
904 ** cursor returned must not be used with any other Btree interface.
905 */
906 BtCursor *sqlite3BtreeFakeValidCursor(void){
907   static u8 fakeCursor = CURSOR_VALID;
908   assert( offsetof(BtCursor, eState)==0 );
909   return (BtCursor*)&fakeCursor;
910 }
911 
912 /*
913 ** This routine restores a cursor back to its original position after it
914 ** has been moved by some outside activity (such as a btree rebalance or
915 ** a row having been deleted out from under the cursor).
916 **
917 ** On success, the *pDifferentRow parameter is false if the cursor is left
918 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
919 ** was pointing to has been deleted, forcing the cursor to point to some
920 ** nearby row.
921 **
922 ** This routine should only be called for a cursor that just returned
923 ** TRUE from sqlite3BtreeCursorHasMoved().
924 */
925 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
926   int rc;
927 
928   assert( pCur!=0 );
929   assert( pCur->eState!=CURSOR_VALID );
930   rc = restoreCursorPosition(pCur);
931   if( rc ){
932     *pDifferentRow = 1;
933     return rc;
934   }
935   if( pCur->eState!=CURSOR_VALID ){
936     *pDifferentRow = 1;
937   }else{
938     *pDifferentRow = 0;
939   }
940   return SQLITE_OK;
941 }
942 
943 #ifdef SQLITE_ENABLE_CURSOR_HINTS
944 /*
945 ** Provide hints to the cursor.  The particular hint given (and the type
946 ** and number of the varargs parameters) is determined by the eHintType
947 ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
948 */
949 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
950   /* Used only by system that substitute their own storage engine */
951 }
952 #endif
953 
954 /*
955 ** Provide flag hints to the cursor.
956 */
957 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
958   assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
959   pCur->hints = x;
960 }
961 
962 
963 #ifndef SQLITE_OMIT_AUTOVACUUM
964 /*
965 ** Given a page number of a regular database page, return the page
966 ** number for the pointer-map page that contains the entry for the
967 ** input page number.
968 **
969 ** Return 0 (not a valid page) for pgno==1 since there is
970 ** no pointer map associated with page 1.  The integrity_check logic
971 ** requires that ptrmapPageno(*,1)!=1.
972 */
973 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
974   int nPagesPerMapPage;
975   Pgno iPtrMap, ret;
976   assert( sqlite3_mutex_held(pBt->mutex) );
977   if( pgno<2 ) return 0;
978   nPagesPerMapPage = (pBt->usableSize/5)+1;
979   iPtrMap = (pgno-2)/nPagesPerMapPage;
980   ret = (iPtrMap*nPagesPerMapPage) + 2;
981   if( ret==PENDING_BYTE_PAGE(pBt) ){
982     ret++;
983   }
984   return ret;
985 }
986 
987 /*
988 ** Write an entry into the pointer map.
989 **
990 ** This routine updates the pointer map entry for page number 'key'
991 ** so that it maps to type 'eType' and parent page number 'pgno'.
992 **
993 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
994 ** a no-op.  If an error occurs, the appropriate error code is written
995 ** into *pRC.
996 */
997 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
998   DbPage *pDbPage;  /* The pointer map page */
999   u8 *pPtrmap;      /* The pointer map data */
1000   Pgno iPtrmap;     /* The pointer map page number */
1001   int offset;       /* Offset in pointer map page */
1002   int rc;           /* Return code from subfunctions */
1003 
1004   if( *pRC ) return;
1005 
1006   assert( sqlite3_mutex_held(pBt->mutex) );
1007   /* The super-journal page number must never be used as a pointer map page */
1008   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1009 
1010   assert( pBt->autoVacuum );
1011   if( key==0 ){
1012     *pRC = SQLITE_CORRUPT_BKPT;
1013     return;
1014   }
1015   iPtrmap = PTRMAP_PAGENO(pBt, key);
1016   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1017   if( rc!=SQLITE_OK ){
1018     *pRC = rc;
1019     return;
1020   }
1021   if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1022     /* The first byte of the extra data is the MemPage.isInit byte.
1023     ** If that byte is set, it means this page is also being used
1024     ** as a btree page. */
1025     *pRC = SQLITE_CORRUPT_BKPT;
1026     goto ptrmap_exit;
1027   }
1028   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1029   if( offset<0 ){
1030     *pRC = SQLITE_CORRUPT_BKPT;
1031     goto ptrmap_exit;
1032   }
1033   assert( offset <= (int)pBt->usableSize-5 );
1034   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1035 
1036   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1037     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1038     *pRC= rc = sqlite3PagerWrite(pDbPage);
1039     if( rc==SQLITE_OK ){
1040       pPtrmap[offset] = eType;
1041       put4byte(&pPtrmap[offset+1], parent);
1042     }
1043   }
1044 
1045 ptrmap_exit:
1046   sqlite3PagerUnref(pDbPage);
1047 }
1048 
1049 /*
1050 ** Read an entry from the pointer map.
1051 **
1052 ** This routine retrieves the pointer map entry for page 'key', writing
1053 ** the type and parent page number to *pEType and *pPgno respectively.
1054 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1055 */
1056 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1057   DbPage *pDbPage;   /* The pointer map page */
1058   int iPtrmap;       /* Pointer map page index */
1059   u8 *pPtrmap;       /* Pointer map page data */
1060   int offset;        /* Offset of entry in pointer map */
1061   int rc;
1062 
1063   assert( sqlite3_mutex_held(pBt->mutex) );
1064 
1065   iPtrmap = PTRMAP_PAGENO(pBt, key);
1066   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1067   if( rc!=0 ){
1068     return rc;
1069   }
1070   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1071 
1072   offset = PTRMAP_PTROFFSET(iPtrmap, key);
1073   if( offset<0 ){
1074     sqlite3PagerUnref(pDbPage);
1075     return SQLITE_CORRUPT_BKPT;
1076   }
1077   assert( offset <= (int)pBt->usableSize-5 );
1078   assert( pEType!=0 );
1079   *pEType = pPtrmap[offset];
1080   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1081 
1082   sqlite3PagerUnref(pDbPage);
1083   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1084   return SQLITE_OK;
1085 }
1086 
1087 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1088   #define ptrmapPut(w,x,y,z,rc)
1089   #define ptrmapGet(w,x,y,z) SQLITE_OK
1090   #define ptrmapPutOvflPtr(x, y, z, rc)
1091 #endif
1092 
1093 /*
1094 ** Given a btree page and a cell index (0 means the first cell on
1095 ** the page, 1 means the second cell, and so forth) return a pointer
1096 ** to the cell content.
1097 **
1098 ** findCellPastPtr() does the same except it skips past the initial
1099 ** 4-byte child pointer found on interior pages, if there is one.
1100 **
1101 ** This routine works only for pages that do not contain overflow cells.
1102 */
1103 #define findCell(P,I) \
1104   ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1105 #define findCellPastPtr(P,I) \
1106   ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1107 
1108 
1109 /*
1110 ** This is common tail processing for btreeParseCellPtr() and
1111 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1112 ** on a single B-tree page.  Make necessary adjustments to the CellInfo
1113 ** structure.
1114 */
1115 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1116   MemPage *pPage,         /* Page containing the cell */
1117   u8 *pCell,              /* Pointer to the cell text. */
1118   CellInfo *pInfo         /* Fill in this structure */
1119 ){
1120   /* If the payload will not fit completely on the local page, we have
1121   ** to decide how much to store locally and how much to spill onto
1122   ** overflow pages.  The strategy is to minimize the amount of unused
1123   ** space on overflow pages while keeping the amount of local storage
1124   ** in between minLocal and maxLocal.
1125   **
1126   ** Warning:  changing the way overflow payload is distributed in any
1127   ** way will result in an incompatible file format.
1128   */
1129   int minLocal;  /* Minimum amount of payload held locally */
1130   int maxLocal;  /* Maximum amount of payload held locally */
1131   int surplus;   /* Overflow payload available for local storage */
1132 
1133   minLocal = pPage->minLocal;
1134   maxLocal = pPage->maxLocal;
1135   surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1136   testcase( surplus==maxLocal );
1137   testcase( surplus==maxLocal+1 );
1138   if( surplus <= maxLocal ){
1139     pInfo->nLocal = (u16)surplus;
1140   }else{
1141     pInfo->nLocal = (u16)minLocal;
1142   }
1143   pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1144 }
1145 
1146 /*
1147 ** Given a record with nPayload bytes of payload stored within btree
1148 ** page pPage, return the number of bytes of payload stored locally.
1149 */
1150 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1151   int maxLocal;  /* Maximum amount of payload held locally */
1152   maxLocal = pPage->maxLocal;
1153   if( nPayload<=maxLocal ){
1154     return nPayload;
1155   }else{
1156     int minLocal;  /* Minimum amount of payload held locally */
1157     int surplus;   /* Overflow payload available for local storage */
1158     minLocal = pPage->minLocal;
1159     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1160     return ( surplus <= maxLocal ) ? surplus : minLocal;
1161   }
1162 }
1163 
1164 /*
1165 ** The following routines are implementations of the MemPage.xParseCell()
1166 ** method.
1167 **
1168 ** Parse a cell content block and fill in the CellInfo structure.
1169 **
1170 ** btreeParseCellPtr()        =>   table btree leaf nodes
1171 ** btreeParseCellNoPayload()  =>   table btree internal nodes
1172 ** btreeParseCellPtrIndex()   =>   index btree nodes
1173 **
1174 ** There is also a wrapper function btreeParseCell() that works for
1175 ** all MemPage types and that references the cell by index rather than
1176 ** by pointer.
1177 */
1178 static void btreeParseCellPtrNoPayload(
1179   MemPage *pPage,         /* Page containing the cell */
1180   u8 *pCell,              /* Pointer to the cell text. */
1181   CellInfo *pInfo         /* Fill in this structure */
1182 ){
1183   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1184   assert( pPage->leaf==0 );
1185   assert( pPage->childPtrSize==4 );
1186 #ifndef SQLITE_DEBUG
1187   UNUSED_PARAMETER(pPage);
1188 #endif
1189   pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1190   pInfo->nPayload = 0;
1191   pInfo->nLocal = 0;
1192   pInfo->pPayload = 0;
1193   return;
1194 }
1195 static void btreeParseCellPtr(
1196   MemPage *pPage,         /* Page containing the cell */
1197   u8 *pCell,              /* Pointer to the cell text. */
1198   CellInfo *pInfo         /* Fill in this structure */
1199 ){
1200   u8 *pIter;              /* For scanning through pCell */
1201   u32 nPayload;           /* Number of bytes of cell payload */
1202   u64 iKey;               /* Extracted Key value */
1203 
1204   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1205   assert( pPage->leaf==0 || pPage->leaf==1 );
1206   assert( pPage->intKeyLeaf );
1207   assert( pPage->childPtrSize==0 );
1208   pIter = pCell;
1209 
1210   /* The next block of code is equivalent to:
1211   **
1212   **     pIter += getVarint32(pIter, nPayload);
1213   **
1214   ** The code is inlined to avoid a function call.
1215   */
1216   nPayload = *pIter;
1217   if( nPayload>=0x80 ){
1218     u8 *pEnd = &pIter[8];
1219     nPayload &= 0x7f;
1220     do{
1221       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1222     }while( (*pIter)>=0x80 && pIter<pEnd );
1223   }
1224   pIter++;
1225 
1226   /* The next block of code is equivalent to:
1227   **
1228   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1229   **
1230   ** The code is inlined to avoid a function call.
1231   */
1232   iKey = *pIter;
1233   if( iKey>=0x80 ){
1234     u8 *pEnd = &pIter[7];
1235     iKey &= 0x7f;
1236     while(1){
1237       iKey = (iKey<<7) | (*++pIter & 0x7f);
1238       if( (*pIter)<0x80 ) break;
1239       if( pIter>=pEnd ){
1240         iKey = (iKey<<8) | *++pIter;
1241         break;
1242       }
1243     }
1244   }
1245   pIter++;
1246 
1247   pInfo->nKey = *(i64*)&iKey;
1248   pInfo->nPayload = nPayload;
1249   pInfo->pPayload = pIter;
1250   testcase( nPayload==pPage->maxLocal );
1251   testcase( nPayload==pPage->maxLocal+1 );
1252   if( nPayload<=pPage->maxLocal ){
1253     /* This is the (easy) common case where the entire payload fits
1254     ** on the local page.  No overflow is required.
1255     */
1256     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1257     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1258     pInfo->nLocal = (u16)nPayload;
1259   }else{
1260     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1261   }
1262 }
1263 static void btreeParseCellPtrIndex(
1264   MemPage *pPage,         /* Page containing the cell */
1265   u8 *pCell,              /* Pointer to the cell text. */
1266   CellInfo *pInfo         /* Fill in this structure */
1267 ){
1268   u8 *pIter;              /* For scanning through pCell */
1269   u32 nPayload;           /* Number of bytes of cell payload */
1270 
1271   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1272   assert( pPage->leaf==0 || pPage->leaf==1 );
1273   assert( pPage->intKeyLeaf==0 );
1274   pIter = pCell + pPage->childPtrSize;
1275   nPayload = *pIter;
1276   if( nPayload>=0x80 ){
1277     u8 *pEnd = &pIter[8];
1278     nPayload &= 0x7f;
1279     do{
1280       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1281     }while( *(pIter)>=0x80 && pIter<pEnd );
1282   }
1283   pIter++;
1284   pInfo->nKey = nPayload;
1285   pInfo->nPayload = nPayload;
1286   pInfo->pPayload = pIter;
1287   testcase( nPayload==pPage->maxLocal );
1288   testcase( nPayload==pPage->maxLocal+1 );
1289   if( nPayload<=pPage->maxLocal ){
1290     /* This is the (easy) common case where the entire payload fits
1291     ** on the local page.  No overflow is required.
1292     */
1293     pInfo->nSize = nPayload + (u16)(pIter - pCell);
1294     if( pInfo->nSize<4 ) pInfo->nSize = 4;
1295     pInfo->nLocal = (u16)nPayload;
1296   }else{
1297     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1298   }
1299 }
1300 static void btreeParseCell(
1301   MemPage *pPage,         /* Page containing the cell */
1302   int iCell,              /* The cell index.  First cell is 0 */
1303   CellInfo *pInfo         /* Fill in this structure */
1304 ){
1305   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1306 }
1307 
1308 /*
1309 ** The following routines are implementations of the MemPage.xCellSize
1310 ** method.
1311 **
1312 ** Compute the total number of bytes that a Cell needs in the cell
1313 ** data area of the btree-page.  The return number includes the cell
1314 ** data header and the local payload, but not any overflow page or
1315 ** the space used by the cell pointer.
1316 **
1317 ** cellSizePtrNoPayload()    =>   table internal nodes
1318 ** cellSizePtr()             =>   all index nodes & table leaf nodes
1319 */
1320 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1321   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1322   u8 *pEnd;                                /* End mark for a varint */
1323   u32 nSize;                               /* Size value to return */
1324 
1325 #ifdef SQLITE_DEBUG
1326   /* The value returned by this function should always be the same as
1327   ** the (CellInfo.nSize) value found by doing a full parse of the
1328   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1329   ** this function verifies that this invariant is not violated. */
1330   CellInfo debuginfo;
1331   pPage->xParseCell(pPage, pCell, &debuginfo);
1332 #endif
1333 
1334   nSize = *pIter;
1335   if( nSize>=0x80 ){
1336     pEnd = &pIter[8];
1337     nSize &= 0x7f;
1338     do{
1339       nSize = (nSize<<7) | (*++pIter & 0x7f);
1340     }while( *(pIter)>=0x80 && pIter<pEnd );
1341   }
1342   pIter++;
1343   if( pPage->intKey ){
1344     /* pIter now points at the 64-bit integer key value, a variable length
1345     ** integer. The following block moves pIter to point at the first byte
1346     ** past the end of the key value. */
1347     pEnd = &pIter[9];
1348     while( (*pIter++)&0x80 && pIter<pEnd );
1349   }
1350   testcase( nSize==pPage->maxLocal );
1351   testcase( nSize==pPage->maxLocal+1 );
1352   if( nSize<=pPage->maxLocal ){
1353     nSize += (u32)(pIter - pCell);
1354     if( nSize<4 ) nSize = 4;
1355   }else{
1356     int minLocal = pPage->minLocal;
1357     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1358     testcase( nSize==pPage->maxLocal );
1359     testcase( nSize==pPage->maxLocal+1 );
1360     if( nSize>pPage->maxLocal ){
1361       nSize = minLocal;
1362     }
1363     nSize += 4 + (u16)(pIter - pCell);
1364   }
1365   assert( nSize==debuginfo.nSize || CORRUPT_DB );
1366   return (u16)nSize;
1367 }
1368 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1369   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1370   u8 *pEnd;              /* End mark for a varint */
1371 
1372 #ifdef SQLITE_DEBUG
1373   /* The value returned by this function should always be the same as
1374   ** the (CellInfo.nSize) value found by doing a full parse of the
1375   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1376   ** this function verifies that this invariant is not violated. */
1377   CellInfo debuginfo;
1378   pPage->xParseCell(pPage, pCell, &debuginfo);
1379 #else
1380   UNUSED_PARAMETER(pPage);
1381 #endif
1382 
1383   assert( pPage->childPtrSize==4 );
1384   pEnd = pIter + 9;
1385   while( (*pIter++)&0x80 && pIter<pEnd );
1386   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1387   return (u16)(pIter - pCell);
1388 }
1389 
1390 
1391 #ifdef SQLITE_DEBUG
1392 /* This variation on cellSizePtr() is used inside of assert() statements
1393 ** only. */
1394 static u16 cellSize(MemPage *pPage, int iCell){
1395   return pPage->xCellSize(pPage, findCell(pPage, iCell));
1396 }
1397 #endif
1398 
1399 #ifndef SQLITE_OMIT_AUTOVACUUM
1400 /*
1401 ** The cell pCell is currently part of page pSrc but will ultimately be part
1402 ** of pPage.  (pSrc and pPager are often the same.)  If pCell contains a
1403 ** pointer to an overflow page, insert an entry into the pointer-map for
1404 ** the overflow page that will be valid after pCell has been moved to pPage.
1405 */
1406 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1407   CellInfo info;
1408   if( *pRC ) return;
1409   assert( pCell!=0 );
1410   pPage->xParseCell(pPage, pCell, &info);
1411   if( info.nLocal<info.nPayload ){
1412     Pgno ovfl;
1413     if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1414       testcase( pSrc!=pPage );
1415       *pRC = SQLITE_CORRUPT_BKPT;
1416       return;
1417     }
1418     ovfl = get4byte(&pCell[info.nSize-4]);
1419     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1420   }
1421 }
1422 #endif
1423 
1424 
1425 /*
1426 ** Defragment the page given. This routine reorganizes cells within the
1427 ** page so that there are no free-blocks on the free-block list.
1428 **
1429 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1430 ** present in the page after this routine returns.
1431 **
1432 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1433 ** b-tree page so that there are no freeblocks or fragment bytes, all
1434 ** unused bytes are contained in the unallocated space region, and all
1435 ** cells are packed tightly at the end of the page.
1436 */
1437 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1438   int i;                     /* Loop counter */
1439   int pc;                    /* Address of the i-th cell */
1440   int hdr;                   /* Offset to the page header */
1441   int size;                  /* Size of a cell */
1442   int usableSize;            /* Number of usable bytes on a page */
1443   int cellOffset;            /* Offset to the cell pointer array */
1444   int cbrk;                  /* Offset to the cell content area */
1445   int nCell;                 /* Number of cells on the page */
1446   unsigned char *data;       /* The page data */
1447   unsigned char *temp;       /* Temp area for cell content */
1448   unsigned char *src;        /* Source of content */
1449   int iCellFirst;            /* First allowable cell index */
1450   int iCellLast;             /* Last possible cell index */
1451   int iCellStart;            /* First cell offset in input */
1452 
1453   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1454   assert( pPage->pBt!=0 );
1455   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1456   assert( pPage->nOverflow==0 );
1457   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1458   temp = 0;
1459   src = data = pPage->aData;
1460   hdr = pPage->hdrOffset;
1461   cellOffset = pPage->cellOffset;
1462   nCell = pPage->nCell;
1463   assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1464   iCellFirst = cellOffset + 2*nCell;
1465   usableSize = pPage->pBt->usableSize;
1466 
1467   /* This block handles pages with two or fewer free blocks and nMaxFrag
1468   ** or fewer fragmented bytes. In this case it is faster to move the
1469   ** two (or one) blocks of cells using memmove() and add the required
1470   ** offsets to each pointer in the cell-pointer array than it is to
1471   ** reconstruct the entire page.  */
1472   if( (int)data[hdr+7]<=nMaxFrag ){
1473     int iFree = get2byte(&data[hdr+1]);
1474     if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1475     if( iFree ){
1476       int iFree2 = get2byte(&data[iFree]);
1477       if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1478       if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1479         u8 *pEnd = &data[cellOffset + nCell*2];
1480         u8 *pAddr;
1481         int sz2 = 0;
1482         int sz = get2byte(&data[iFree+2]);
1483         int top = get2byte(&data[hdr+5]);
1484         if( top>=iFree ){
1485           return SQLITE_CORRUPT_PAGE(pPage);
1486         }
1487         if( iFree2 ){
1488           if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1489           sz2 = get2byte(&data[iFree2+2]);
1490           if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1491           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1492           sz += sz2;
1493         }else if( iFree+sz>usableSize ){
1494           return SQLITE_CORRUPT_PAGE(pPage);
1495         }
1496 
1497         cbrk = top+sz;
1498         assert( cbrk+(iFree-top) <= usableSize );
1499         memmove(&data[cbrk], &data[top], iFree-top);
1500         for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1501           pc = get2byte(pAddr);
1502           if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1503           else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1504         }
1505         goto defragment_out;
1506       }
1507     }
1508   }
1509 
1510   cbrk = usableSize;
1511   iCellLast = usableSize - 4;
1512   iCellStart = get2byte(&data[hdr+5]);
1513   for(i=0; i<nCell; i++){
1514     u8 *pAddr;     /* The i-th cell pointer */
1515     pAddr = &data[cellOffset + i*2];
1516     pc = get2byte(pAddr);
1517     testcase( pc==iCellFirst );
1518     testcase( pc==iCellLast );
1519     /* These conditions have already been verified in btreeInitPage()
1520     ** if PRAGMA cell_size_check=ON.
1521     */
1522     if( pc<iCellStart || pc>iCellLast ){
1523       return SQLITE_CORRUPT_PAGE(pPage);
1524     }
1525     assert( pc>=iCellStart && pc<=iCellLast );
1526     size = pPage->xCellSize(pPage, &src[pc]);
1527     cbrk -= size;
1528     if( cbrk<iCellStart || pc+size>usableSize ){
1529       return SQLITE_CORRUPT_PAGE(pPage);
1530     }
1531     assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1532     testcase( cbrk+size==usableSize );
1533     testcase( pc+size==usableSize );
1534     put2byte(pAddr, cbrk);
1535     if( temp==0 ){
1536       if( cbrk==pc ) continue;
1537       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1538       memcpy(&temp[iCellStart], &data[iCellStart], (cbrk+size) - iCellStart);
1539       src = temp;
1540     }
1541     memcpy(&data[cbrk], &src[pc], size);
1542   }
1543   data[hdr+7] = 0;
1544 
1545  defragment_out:
1546   assert( pPage->nFree>=0 );
1547   if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1548     return SQLITE_CORRUPT_PAGE(pPage);
1549   }
1550   assert( cbrk>=iCellFirst );
1551   put2byte(&data[hdr+5], cbrk);
1552   data[hdr+1] = 0;
1553   data[hdr+2] = 0;
1554   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1555   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1556   return SQLITE_OK;
1557 }
1558 
1559 /*
1560 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1561 ** size. If one can be found, return a pointer to the space and remove it
1562 ** from the free-list.
1563 **
1564 ** If no suitable space can be found on the free-list, return NULL.
1565 **
1566 ** This function may detect corruption within pPg.  If corruption is
1567 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1568 **
1569 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1570 ** will be ignored if adding the extra space to the fragmentation count
1571 ** causes the fragmentation count to exceed 60.
1572 */
1573 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1574   const int hdr = pPg->hdrOffset;            /* Offset to page header */
1575   u8 * const aData = pPg->aData;             /* Page data */
1576   int iAddr = hdr + 1;                       /* Address of ptr to pc */
1577   int pc = get2byte(&aData[iAddr]);          /* Address of a free slot */
1578   int x;                                     /* Excess size of the slot */
1579   int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */
1580   int size;                                  /* Size of the free slot */
1581 
1582   assert( pc>0 );
1583   while( pc<=maxPC ){
1584     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1585     ** freeblock form a big-endian integer which is the size of the freeblock
1586     ** in bytes, including the 4-byte header. */
1587     size = get2byte(&aData[pc+2]);
1588     if( (x = size - nByte)>=0 ){
1589       testcase( x==4 );
1590       testcase( x==3 );
1591       if( x<4 ){
1592         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1593         ** number of bytes in fragments may not exceed 60. */
1594         if( aData[hdr+7]>57 ) return 0;
1595 
1596         /* Remove the slot from the free-list. Update the number of
1597         ** fragmented bytes within the page. */
1598         memcpy(&aData[iAddr], &aData[pc], 2);
1599         aData[hdr+7] += (u8)x;
1600       }else if( x+pc > maxPC ){
1601         /* This slot extends off the end of the usable part of the page */
1602         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1603         return 0;
1604       }else{
1605         /* The slot remains on the free-list. Reduce its size to account
1606         ** for the portion used by the new allocation. */
1607         put2byte(&aData[pc+2], x);
1608       }
1609       return &aData[pc + x];
1610     }
1611     iAddr = pc;
1612     pc = get2byte(&aData[pc]);
1613     if( pc<=iAddr+size ){
1614       if( pc ){
1615         /* The next slot in the chain is not past the end of the current slot */
1616         *pRc = SQLITE_CORRUPT_PAGE(pPg);
1617       }
1618       return 0;
1619     }
1620   }
1621   if( pc>maxPC+nByte-4 ){
1622     /* The free slot chain extends off the end of the page */
1623     *pRc = SQLITE_CORRUPT_PAGE(pPg);
1624   }
1625   return 0;
1626 }
1627 
1628 /*
1629 ** Allocate nByte bytes of space from within the B-Tree page passed
1630 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1631 ** of the first byte of allocated space. Return either SQLITE_OK or
1632 ** an error code (usually SQLITE_CORRUPT).
1633 **
1634 ** The caller guarantees that there is sufficient space to make the
1635 ** allocation.  This routine might need to defragment in order to bring
1636 ** all the space together, however.  This routine will avoid using
1637 ** the first two bytes past the cell pointer area since presumably this
1638 ** allocation is being made in order to insert a new cell, so we will
1639 ** also end up needing a new cell pointer.
1640 */
1641 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1642   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
1643   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
1644   int top;                             /* First byte of cell content area */
1645   int rc = SQLITE_OK;                  /* Integer return code */
1646   int gap;        /* First byte of gap between cell pointers and cell content */
1647 
1648   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1649   assert( pPage->pBt );
1650   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1651   assert( nByte>=0 );  /* Minimum cell size is 4 */
1652   assert( pPage->nFree>=nByte );
1653   assert( pPage->nOverflow==0 );
1654   assert( nByte < (int)(pPage->pBt->usableSize-8) );
1655 
1656   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1657   gap = pPage->cellOffset + 2*pPage->nCell;
1658   assert( gap<=65536 );
1659   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1660   ** and the reserved space is zero (the usual value for reserved space)
1661   ** then the cell content offset of an empty page wants to be 65536.
1662   ** However, that integer is too large to be stored in a 2-byte unsigned
1663   ** integer, so a value of 0 is used in its place. */
1664   top = get2byte(&data[hdr+5]);
1665   assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1666   if( gap>top ){
1667     if( top==0 && pPage->pBt->usableSize==65536 ){
1668       top = 65536;
1669     }else{
1670       return SQLITE_CORRUPT_PAGE(pPage);
1671     }
1672   }
1673 
1674   /* If there is enough space between gap and top for one more cell pointer,
1675   ** and if the freelist is not empty, then search the
1676   ** freelist looking for a slot big enough to satisfy the request.
1677   */
1678   testcase( gap+2==top );
1679   testcase( gap+1==top );
1680   testcase( gap==top );
1681   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1682     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1683     if( pSpace ){
1684       int g2;
1685       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1686       *pIdx = g2 = (int)(pSpace-data);
1687       if( NEVER(g2<=gap) ){
1688         return SQLITE_CORRUPT_PAGE(pPage);
1689       }else{
1690         return SQLITE_OK;
1691       }
1692     }else if( rc ){
1693       return rc;
1694     }
1695   }
1696 
1697   /* The request could not be fulfilled using a freelist slot.  Check
1698   ** to see if defragmentation is necessary.
1699   */
1700   testcase( gap+2+nByte==top );
1701   if( gap+2+nByte>top ){
1702     assert( pPage->nCell>0 || CORRUPT_DB );
1703     assert( pPage->nFree>=0 );
1704     rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1705     if( rc ) return rc;
1706     top = get2byteNotZero(&data[hdr+5]);
1707     assert( gap+2+nByte<=top );
1708   }
1709 
1710 
1711   /* Allocate memory from the gap in between the cell pointer array
1712   ** and the cell content area.  The btreeComputeFreeSpace() call has already
1713   ** validated the freelist.  Given that the freelist is valid, there
1714   ** is no way that the allocation can extend off the end of the page.
1715   ** The assert() below verifies the previous sentence.
1716   */
1717   top -= nByte;
1718   put2byte(&data[hdr+5], top);
1719   assert( top+nByte <= (int)pPage->pBt->usableSize );
1720   *pIdx = top;
1721   return SQLITE_OK;
1722 }
1723 
1724 /*
1725 ** Return a section of the pPage->aData to the freelist.
1726 ** The first byte of the new free block is pPage->aData[iStart]
1727 ** and the size of the block is iSize bytes.
1728 **
1729 ** Adjacent freeblocks are coalesced.
1730 **
1731 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1732 ** that routine will not detect overlap between cells or freeblocks.  Nor
1733 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1734 ** at the end of the page.  So do additional corruption checks inside this
1735 ** routine and return SQLITE_CORRUPT if any problems are found.
1736 */
1737 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1738   u16 iPtr;                             /* Address of ptr to next freeblock */
1739   u16 iFreeBlk;                         /* Address of the next freeblock */
1740   u8 hdr;                               /* Page header size.  0 or 100 */
1741   u8 nFrag = 0;                         /* Reduction in fragmentation */
1742   u16 iOrigSize = iSize;                /* Original value of iSize */
1743   u16 x;                                /* Offset to cell content area */
1744   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
1745   unsigned char *data = pPage->aData;   /* Page content */
1746 
1747   assert( pPage->pBt!=0 );
1748   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1749   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1750   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1751   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1752   assert( iSize>=4 );   /* Minimum cell size is 4 */
1753   assert( iStart<=pPage->pBt->usableSize-4 );
1754 
1755   /* The list of freeblocks must be in ascending order.  Find the
1756   ** spot on the list where iStart should be inserted.
1757   */
1758   hdr = pPage->hdrOffset;
1759   iPtr = hdr + 1;
1760   if( data[iPtr+1]==0 && data[iPtr]==0 ){
1761     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
1762   }else{
1763     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1764       if( iFreeBlk<iPtr+4 ){
1765         if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1766         return SQLITE_CORRUPT_PAGE(pPage);
1767       }
1768       iPtr = iFreeBlk;
1769     }
1770     if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1771       return SQLITE_CORRUPT_PAGE(pPage);
1772     }
1773     assert( iFreeBlk>iPtr || iFreeBlk==0 );
1774 
1775     /* At this point:
1776     **    iFreeBlk:   First freeblock after iStart, or zero if none
1777     **    iPtr:       The address of a pointer to iFreeBlk
1778     **
1779     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1780     */
1781     if( iFreeBlk && iEnd+3>=iFreeBlk ){
1782       nFrag = iFreeBlk - iEnd;
1783       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1784       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1785       if( iEnd > pPage->pBt->usableSize ){
1786         return SQLITE_CORRUPT_PAGE(pPage);
1787       }
1788       iSize = iEnd - iStart;
1789       iFreeBlk = get2byte(&data[iFreeBlk]);
1790     }
1791 
1792     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1793     ** pointer in the page header) then check to see if iStart should be
1794     ** coalesced onto the end of iPtr.
1795     */
1796     if( iPtr>hdr+1 ){
1797       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1798       if( iPtrEnd+3>=iStart ){
1799         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1800         nFrag += iStart - iPtrEnd;
1801         iSize = iEnd - iPtr;
1802         iStart = iPtr;
1803       }
1804     }
1805     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1806     data[hdr+7] -= nFrag;
1807   }
1808   x = get2byte(&data[hdr+5]);
1809   if( iStart<=x ){
1810     /* The new freeblock is at the beginning of the cell content area,
1811     ** so just extend the cell content area rather than create another
1812     ** freelist entry */
1813     if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1814     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1815     put2byte(&data[hdr+1], iFreeBlk);
1816     put2byte(&data[hdr+5], iEnd);
1817   }else{
1818     /* Insert the new freeblock into the freelist */
1819     put2byte(&data[iPtr], iStart);
1820   }
1821   if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1822     /* Overwrite deleted information with zeros when the secure_delete
1823     ** option is enabled */
1824     memset(&data[iStart], 0, iSize);
1825   }
1826   put2byte(&data[iStart], iFreeBlk);
1827   put2byte(&data[iStart+2], iSize);
1828   pPage->nFree += iOrigSize;
1829   return SQLITE_OK;
1830 }
1831 
1832 /*
1833 ** Decode the flags byte (the first byte of the header) for a page
1834 ** and initialize fields of the MemPage structure accordingly.
1835 **
1836 ** Only the following combinations are supported.  Anything different
1837 ** indicates a corrupt database files:
1838 **
1839 **         PTF_ZERODATA
1840 **         PTF_ZERODATA | PTF_LEAF
1841 **         PTF_LEAFDATA | PTF_INTKEY
1842 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1843 */
1844 static int decodeFlags(MemPage *pPage, int flagByte){
1845   BtShared *pBt;     /* A copy of pPage->pBt */
1846 
1847   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1848   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1849   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
1850   flagByte &= ~PTF_LEAF;
1851   pPage->childPtrSize = 4-4*pPage->leaf;
1852   pPage->xCellSize = cellSizePtr;
1853   pBt = pPage->pBt;
1854   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1855     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1856     ** interior table b-tree page. */
1857     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1858     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1859     ** leaf table b-tree page. */
1860     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1861     pPage->intKey = 1;
1862     if( pPage->leaf ){
1863       pPage->intKeyLeaf = 1;
1864       pPage->xParseCell = btreeParseCellPtr;
1865     }else{
1866       pPage->intKeyLeaf = 0;
1867       pPage->xCellSize = cellSizePtrNoPayload;
1868       pPage->xParseCell = btreeParseCellPtrNoPayload;
1869     }
1870     pPage->maxLocal = pBt->maxLeaf;
1871     pPage->minLocal = pBt->minLeaf;
1872   }else if( flagByte==PTF_ZERODATA ){
1873     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1874     ** interior index b-tree page. */
1875     assert( (PTF_ZERODATA)==2 );
1876     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1877     ** leaf index b-tree page. */
1878     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1879     pPage->intKey = 0;
1880     pPage->intKeyLeaf = 0;
1881     pPage->xParseCell = btreeParseCellPtrIndex;
1882     pPage->maxLocal = pBt->maxLocal;
1883     pPage->minLocal = pBt->minLocal;
1884   }else{
1885     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1886     ** an error. */
1887     return SQLITE_CORRUPT_PAGE(pPage);
1888   }
1889   pPage->max1bytePayload = pBt->max1bytePayload;
1890   return SQLITE_OK;
1891 }
1892 
1893 /*
1894 ** Compute the amount of freespace on the page.  In other words, fill
1895 ** in the pPage->nFree field.
1896 */
1897 static int btreeComputeFreeSpace(MemPage *pPage){
1898   int pc;            /* Address of a freeblock within pPage->aData[] */
1899   u8 hdr;            /* Offset to beginning of page header */
1900   u8 *data;          /* Equal to pPage->aData */
1901   int usableSize;    /* Amount of usable space on each page */
1902   int nFree;         /* Number of unused bytes on the page */
1903   int top;           /* First byte of the cell content area */
1904   int iCellFirst;    /* First allowable cell or freeblock offset */
1905   int iCellLast;     /* Last possible cell or freeblock offset */
1906 
1907   assert( pPage->pBt!=0 );
1908   assert( pPage->pBt->db!=0 );
1909   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1910   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1911   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1912   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1913   assert( pPage->isInit==1 );
1914   assert( pPage->nFree<0 );
1915 
1916   usableSize = pPage->pBt->usableSize;
1917   hdr = pPage->hdrOffset;
1918   data = pPage->aData;
1919   /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1920   ** the start of the cell content area. A zero value for this integer is
1921   ** interpreted as 65536. */
1922   top = get2byteNotZero(&data[hdr+5]);
1923   iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1924   iCellLast = usableSize - 4;
1925 
1926   /* Compute the total free space on the page
1927   ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1928   ** start of the first freeblock on the page, or is zero if there are no
1929   ** freeblocks. */
1930   pc = get2byte(&data[hdr+1]);
1931   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
1932   if( pc>0 ){
1933     u32 next, size;
1934     if( pc<top ){
1935       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1936       ** always be at least one cell before the first freeblock.
1937       */
1938       return SQLITE_CORRUPT_PAGE(pPage);
1939     }
1940     while( 1 ){
1941       if( pc>iCellLast ){
1942         /* Freeblock off the end of the page */
1943         return SQLITE_CORRUPT_PAGE(pPage);
1944       }
1945       next = get2byte(&data[pc]);
1946       size = get2byte(&data[pc+2]);
1947       nFree = nFree + size;
1948       if( next<=pc+size+3 ) break;
1949       pc = next;
1950     }
1951     if( next>0 ){
1952       /* Freeblock not in ascending order */
1953       return SQLITE_CORRUPT_PAGE(pPage);
1954     }
1955     if( pc+size>(unsigned int)usableSize ){
1956       /* Last freeblock extends past page end */
1957       return SQLITE_CORRUPT_PAGE(pPage);
1958     }
1959   }
1960 
1961   /* At this point, nFree contains the sum of the offset to the start
1962   ** of the cell-content area plus the number of free bytes within
1963   ** the cell-content area. If this is greater than the usable-size
1964   ** of the page, then the page must be corrupted. This check also
1965   ** serves to verify that the offset to the start of the cell-content
1966   ** area, according to the page header, lies within the page.
1967   */
1968   if( nFree>usableSize || nFree<iCellFirst ){
1969     return SQLITE_CORRUPT_PAGE(pPage);
1970   }
1971   pPage->nFree = (u16)(nFree - iCellFirst);
1972   return SQLITE_OK;
1973 }
1974 
1975 /*
1976 ** Do additional sanity check after btreeInitPage() if
1977 ** PRAGMA cell_size_check=ON
1978 */
1979 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1980   int iCellFirst;    /* First allowable cell or freeblock offset */
1981   int iCellLast;     /* Last possible cell or freeblock offset */
1982   int i;             /* Index into the cell pointer array */
1983   int sz;            /* Size of a cell */
1984   int pc;            /* Address of a freeblock within pPage->aData[] */
1985   u8 *data;          /* Equal to pPage->aData */
1986   int usableSize;    /* Maximum usable space on the page */
1987   int cellOffset;    /* Start of cell content area */
1988 
1989   iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1990   usableSize = pPage->pBt->usableSize;
1991   iCellLast = usableSize - 4;
1992   data = pPage->aData;
1993   cellOffset = pPage->cellOffset;
1994   if( !pPage->leaf ) iCellLast--;
1995   for(i=0; i<pPage->nCell; i++){
1996     pc = get2byteAligned(&data[cellOffset+i*2]);
1997     testcase( pc==iCellFirst );
1998     testcase( pc==iCellLast );
1999     if( pc<iCellFirst || pc>iCellLast ){
2000       return SQLITE_CORRUPT_PAGE(pPage);
2001     }
2002     sz = pPage->xCellSize(pPage, &data[pc]);
2003     testcase( pc+sz==usableSize );
2004     if( pc+sz>usableSize ){
2005       return SQLITE_CORRUPT_PAGE(pPage);
2006     }
2007   }
2008   return SQLITE_OK;
2009 }
2010 
2011 /*
2012 ** Initialize the auxiliary information for a disk block.
2013 **
2014 ** Return SQLITE_OK on success.  If we see that the page does
2015 ** not contain a well-formed database page, then return
2016 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
2017 ** guarantee that the page is well-formed.  It only shows that
2018 ** we failed to detect any corruption.
2019 */
2020 static int btreeInitPage(MemPage *pPage){
2021   u8 *data;          /* Equal to pPage->aData */
2022   BtShared *pBt;        /* The main btree structure */
2023 
2024   assert( pPage->pBt!=0 );
2025   assert( pPage->pBt->db!=0 );
2026   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2027   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2028   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2029   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2030   assert( pPage->isInit==0 );
2031 
2032   pBt = pPage->pBt;
2033   data = pPage->aData + pPage->hdrOffset;
2034   /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2035   ** the b-tree page type. */
2036   if( decodeFlags(pPage, data[0]) ){
2037     return SQLITE_CORRUPT_PAGE(pPage);
2038   }
2039   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2040   pPage->maskPage = (u16)(pBt->pageSize - 1);
2041   pPage->nOverflow = 0;
2042   pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2043   pPage->aCellIdx = data + pPage->childPtrSize + 8;
2044   pPage->aDataEnd = pPage->aData + pBt->usableSize;
2045   pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2046   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2047   ** number of cells on the page. */
2048   pPage->nCell = get2byte(&data[3]);
2049   if( pPage->nCell>MX_CELL(pBt) ){
2050     /* To many cells for a single page.  The page must be corrupt */
2051     return SQLITE_CORRUPT_PAGE(pPage);
2052   }
2053   testcase( pPage->nCell==MX_CELL(pBt) );
2054   /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2055   ** possible for a root page of a table that contains no rows) then the
2056   ** offset to the cell content area will equal the page size minus the
2057   ** bytes of reserved space. */
2058   assert( pPage->nCell>0
2059        || get2byteNotZero(&data[5])==(int)pBt->usableSize
2060        || CORRUPT_DB );
2061   pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */
2062   pPage->isInit = 1;
2063   if( pBt->db->flags & SQLITE_CellSizeCk ){
2064     return btreeCellSizeCheck(pPage);
2065   }
2066   return SQLITE_OK;
2067 }
2068 
2069 /*
2070 ** Set up a raw page so that it looks like a database page holding
2071 ** no entries.
2072 */
2073 static void zeroPage(MemPage *pPage, int flags){
2074   unsigned char *data = pPage->aData;
2075   BtShared *pBt = pPage->pBt;
2076   u8 hdr = pPage->hdrOffset;
2077   u16 first;
2078 
2079   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2080   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2081   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2082   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2083   assert( sqlite3_mutex_held(pBt->mutex) );
2084   if( pBt->btsFlags & BTS_FAST_SECURE ){
2085     memset(&data[hdr], 0, pBt->usableSize - hdr);
2086   }
2087   data[hdr] = (char)flags;
2088   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2089   memset(&data[hdr+1], 0, 4);
2090   data[hdr+7] = 0;
2091   put2byte(&data[hdr+5], pBt->usableSize);
2092   pPage->nFree = (u16)(pBt->usableSize - first);
2093   decodeFlags(pPage, flags);
2094   pPage->cellOffset = first;
2095   pPage->aDataEnd = &data[pBt->usableSize];
2096   pPage->aCellIdx = &data[first];
2097   pPage->aDataOfst = &data[pPage->childPtrSize];
2098   pPage->nOverflow = 0;
2099   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2100   pPage->maskPage = (u16)(pBt->pageSize - 1);
2101   pPage->nCell = 0;
2102   pPage->isInit = 1;
2103 }
2104 
2105 
2106 /*
2107 ** Convert a DbPage obtained from the pager into a MemPage used by
2108 ** the btree layer.
2109 */
2110 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2111   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2112   if( pgno!=pPage->pgno ){
2113     pPage->aData = sqlite3PagerGetData(pDbPage);
2114     pPage->pDbPage = pDbPage;
2115     pPage->pBt = pBt;
2116     pPage->pgno = pgno;
2117     pPage->hdrOffset = pgno==1 ? 100 : 0;
2118   }
2119   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2120   return pPage;
2121 }
2122 
2123 /*
2124 ** Get a page from the pager.  Initialize the MemPage.pBt and
2125 ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
2126 **
2127 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2128 ** about the content of the page at this time.  So do not go to the disk
2129 ** to fetch the content.  Just fill in the content with zeros for now.
2130 ** If in the future we call sqlite3PagerWrite() on this page, that
2131 ** means we have started to be concerned about content and the disk
2132 ** read should occur at that point.
2133 */
2134 static int btreeGetPage(
2135   BtShared *pBt,       /* The btree */
2136   Pgno pgno,           /* Number of the page to fetch */
2137   MemPage **ppPage,    /* Return the page in this parameter */
2138   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2139 ){
2140   int rc;
2141   DbPage *pDbPage;
2142 
2143   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2144   assert( sqlite3_mutex_held(pBt->mutex) );
2145   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2146   if( rc ) return rc;
2147   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2148   return SQLITE_OK;
2149 }
2150 
2151 /*
2152 ** Retrieve a page from the pager cache. If the requested page is not
2153 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2154 ** MemPage.aData elements if needed.
2155 */
2156 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2157   DbPage *pDbPage;
2158   assert( sqlite3_mutex_held(pBt->mutex) );
2159   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2160   if( pDbPage ){
2161     return btreePageFromDbPage(pDbPage, pgno, pBt);
2162   }
2163   return 0;
2164 }
2165 
2166 /*
2167 ** Return the size of the database file in pages. If there is any kind of
2168 ** error, return ((unsigned int)-1).
2169 */
2170 static Pgno btreePagecount(BtShared *pBt){
2171   return pBt->nPage;
2172 }
2173 Pgno sqlite3BtreeLastPage(Btree *p){
2174   assert( sqlite3BtreeHoldsMutex(p) );
2175   return btreePagecount(p->pBt);
2176 }
2177 
2178 /*
2179 ** Get a page from the pager and initialize it.
2180 **
2181 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2182 ** call.  Do additional sanity checking on the page in this case.
2183 ** And if the fetch fails, this routine must decrement pCur->iPage.
2184 **
2185 ** The page is fetched as read-write unless pCur is not NULL and is
2186 ** a read-only cursor.
2187 **
2188 ** If an error occurs, then *ppPage is undefined. It
2189 ** may remain unchanged, or it may be set to an invalid value.
2190 */
2191 static int getAndInitPage(
2192   BtShared *pBt,                  /* The database file */
2193   Pgno pgno,                      /* Number of the page to get */
2194   MemPage **ppPage,               /* Write the page pointer here */
2195   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
2196   int bReadOnly                   /* True for a read-only page */
2197 ){
2198   int rc;
2199   DbPage *pDbPage;
2200   assert( sqlite3_mutex_held(pBt->mutex) );
2201   assert( pCur==0 || ppPage==&pCur->pPage );
2202   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2203   assert( pCur==0 || pCur->iPage>0 );
2204 
2205   if( pgno>btreePagecount(pBt) ){
2206     rc = SQLITE_CORRUPT_BKPT;
2207     goto getAndInitPage_error1;
2208   }
2209   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2210   if( rc ){
2211     goto getAndInitPage_error1;
2212   }
2213   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2214   if( (*ppPage)->isInit==0 ){
2215     btreePageFromDbPage(pDbPage, pgno, pBt);
2216     rc = btreeInitPage(*ppPage);
2217     if( rc!=SQLITE_OK ){
2218       goto getAndInitPage_error2;
2219     }
2220   }
2221   assert( (*ppPage)->pgno==pgno );
2222   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2223 
2224   /* If obtaining a child page for a cursor, we must verify that the page is
2225   ** compatible with the root page. */
2226   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2227     rc = SQLITE_CORRUPT_PGNO(pgno);
2228     goto getAndInitPage_error2;
2229   }
2230   return SQLITE_OK;
2231 
2232 getAndInitPage_error2:
2233   releasePage(*ppPage);
2234 getAndInitPage_error1:
2235   if( pCur ){
2236     pCur->iPage--;
2237     pCur->pPage = pCur->apPage[pCur->iPage];
2238   }
2239   testcase( pgno==0 );
2240   assert( pgno!=0 || rc==SQLITE_CORRUPT );
2241   return rc;
2242 }
2243 
2244 /*
2245 ** Release a MemPage.  This should be called once for each prior
2246 ** call to btreeGetPage.
2247 **
2248 ** Page1 is a special case and must be released using releasePageOne().
2249 */
2250 static void releasePageNotNull(MemPage *pPage){
2251   assert( pPage->aData );
2252   assert( pPage->pBt );
2253   assert( pPage->pDbPage!=0 );
2254   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2255   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2256   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2257   sqlite3PagerUnrefNotNull(pPage->pDbPage);
2258 }
2259 static void releasePage(MemPage *pPage){
2260   if( pPage ) releasePageNotNull(pPage);
2261 }
2262 static void releasePageOne(MemPage *pPage){
2263   assert( pPage!=0 );
2264   assert( pPage->aData );
2265   assert( pPage->pBt );
2266   assert( pPage->pDbPage!=0 );
2267   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2268   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2269   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2270   sqlite3PagerUnrefPageOne(pPage->pDbPage);
2271 }
2272 
2273 /*
2274 ** Get an unused page.
2275 **
2276 ** This works just like btreeGetPage() with the addition:
2277 **
2278 **   *  If the page is already in use for some other purpose, immediately
2279 **      release it and return an SQLITE_CURRUPT error.
2280 **   *  Make sure the isInit flag is clear
2281 */
2282 static int btreeGetUnusedPage(
2283   BtShared *pBt,       /* The btree */
2284   Pgno pgno,           /* Number of the page to fetch */
2285   MemPage **ppPage,    /* Return the page in this parameter */
2286   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2287 ){
2288   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2289   if( rc==SQLITE_OK ){
2290     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2291       releasePage(*ppPage);
2292       *ppPage = 0;
2293       return SQLITE_CORRUPT_BKPT;
2294     }
2295     (*ppPage)->isInit = 0;
2296   }else{
2297     *ppPage = 0;
2298   }
2299   return rc;
2300 }
2301 
2302 
2303 /*
2304 ** During a rollback, when the pager reloads information into the cache
2305 ** so that the cache is restored to its original state at the start of
2306 ** the transaction, for each page restored this routine is called.
2307 **
2308 ** This routine needs to reset the extra data section at the end of the
2309 ** page to agree with the restored data.
2310 */
2311 static void pageReinit(DbPage *pData){
2312   MemPage *pPage;
2313   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2314   assert( sqlite3PagerPageRefcount(pData)>0 );
2315   if( pPage->isInit ){
2316     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2317     pPage->isInit = 0;
2318     if( sqlite3PagerPageRefcount(pData)>1 ){
2319       /* pPage might not be a btree page;  it might be an overflow page
2320       ** or ptrmap page or a free page.  In those cases, the following
2321       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2322       ** But no harm is done by this.  And it is very important that
2323       ** btreeInitPage() be called on every btree page so we make
2324       ** the call for every page that comes in for re-initing. */
2325       btreeInitPage(pPage);
2326     }
2327   }
2328 }
2329 
2330 /*
2331 ** Invoke the busy handler for a btree.
2332 */
2333 static int btreeInvokeBusyHandler(void *pArg){
2334   BtShared *pBt = (BtShared*)pArg;
2335   assert( pBt->db );
2336   assert( sqlite3_mutex_held(pBt->db->mutex) );
2337   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2338 }
2339 
2340 /*
2341 ** Open a database file.
2342 **
2343 ** zFilename is the name of the database file.  If zFilename is NULL
2344 ** then an ephemeral database is created.  The ephemeral database might
2345 ** be exclusively in memory, or it might use a disk-based memory cache.
2346 ** Either way, the ephemeral database will be automatically deleted
2347 ** when sqlite3BtreeClose() is called.
2348 **
2349 ** If zFilename is ":memory:" then an in-memory database is created
2350 ** that is automatically destroyed when it is closed.
2351 **
2352 ** The "flags" parameter is a bitmask that might contain bits like
2353 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2354 **
2355 ** If the database is already opened in the same database connection
2356 ** and we are in shared cache mode, then the open will fail with an
2357 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
2358 ** objects in the same database connection since doing so will lead
2359 ** to problems with locking.
2360 */
2361 int sqlite3BtreeOpen(
2362   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
2363   const char *zFilename,  /* Name of the file containing the BTree database */
2364   sqlite3 *db,            /* Associated database handle */
2365   Btree **ppBtree,        /* Pointer to new Btree object written here */
2366   int flags,              /* Options */
2367   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
2368 ){
2369   BtShared *pBt = 0;             /* Shared part of btree structure */
2370   Btree *p;                      /* Handle to return */
2371   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
2372   int rc = SQLITE_OK;            /* Result code from this function */
2373   u8 nReserve;                   /* Byte of unused space on each page */
2374   unsigned char zDbHeader[100];  /* Database header content */
2375 
2376   /* True if opening an ephemeral, temporary database */
2377   const int isTempDb = zFilename==0 || zFilename[0]==0;
2378 
2379   /* Set the variable isMemdb to true for an in-memory database, or
2380   ** false for a file-based database.
2381   */
2382 #ifdef SQLITE_OMIT_MEMORYDB
2383   const int isMemdb = 0;
2384 #else
2385   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2386                        || (isTempDb && sqlite3TempInMemory(db))
2387                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2388 #endif
2389 
2390   assert( db!=0 );
2391   assert( pVfs!=0 );
2392   assert( sqlite3_mutex_held(db->mutex) );
2393   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
2394 
2395   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2396   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2397 
2398   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2399   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2400 
2401   if( isMemdb ){
2402     flags |= BTREE_MEMORY;
2403   }
2404   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2405     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2406   }
2407   p = sqlite3MallocZero(sizeof(Btree));
2408   if( !p ){
2409     return SQLITE_NOMEM_BKPT;
2410   }
2411   p->inTrans = TRANS_NONE;
2412   p->db = db;
2413 #ifndef SQLITE_OMIT_SHARED_CACHE
2414   p->lock.pBtree = p;
2415   p->lock.iTable = 1;
2416 #endif
2417 
2418 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2419   /*
2420   ** If this Btree is a candidate for shared cache, try to find an
2421   ** existing BtShared object that we can share with
2422   */
2423   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2424     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2425       int nFilename = sqlite3Strlen30(zFilename)+1;
2426       int nFullPathname = pVfs->mxPathname+1;
2427       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2428       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2429 
2430       p->sharable = 1;
2431       if( !zFullPathname ){
2432         sqlite3_free(p);
2433         return SQLITE_NOMEM_BKPT;
2434       }
2435       if( isMemdb ){
2436         memcpy(zFullPathname, zFilename, nFilename);
2437       }else{
2438         rc = sqlite3OsFullPathname(pVfs, zFilename,
2439                                    nFullPathname, zFullPathname);
2440         if( rc ){
2441           if( rc==SQLITE_OK_SYMLINK ){
2442             rc = SQLITE_OK;
2443           }else{
2444             sqlite3_free(zFullPathname);
2445             sqlite3_free(p);
2446             return rc;
2447           }
2448         }
2449       }
2450 #if SQLITE_THREADSAFE
2451       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2452       sqlite3_mutex_enter(mutexOpen);
2453       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2454       sqlite3_mutex_enter(mutexShared);
2455 #endif
2456       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2457         assert( pBt->nRef>0 );
2458         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2459                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2460           int iDb;
2461           for(iDb=db->nDb-1; iDb>=0; iDb--){
2462             Btree *pExisting = db->aDb[iDb].pBt;
2463             if( pExisting && pExisting->pBt==pBt ){
2464               sqlite3_mutex_leave(mutexShared);
2465               sqlite3_mutex_leave(mutexOpen);
2466               sqlite3_free(zFullPathname);
2467               sqlite3_free(p);
2468               return SQLITE_CONSTRAINT;
2469             }
2470           }
2471           p->pBt = pBt;
2472           pBt->nRef++;
2473           break;
2474         }
2475       }
2476       sqlite3_mutex_leave(mutexShared);
2477       sqlite3_free(zFullPathname);
2478     }
2479 #ifdef SQLITE_DEBUG
2480     else{
2481       /* In debug mode, we mark all persistent databases as sharable
2482       ** even when they are not.  This exercises the locking code and
2483       ** gives more opportunity for asserts(sqlite3_mutex_held())
2484       ** statements to find locking problems.
2485       */
2486       p->sharable = 1;
2487     }
2488 #endif
2489   }
2490 #endif
2491   if( pBt==0 ){
2492     /*
2493     ** The following asserts make sure that structures used by the btree are
2494     ** the right size.  This is to guard against size changes that result
2495     ** when compiling on a different architecture.
2496     */
2497     assert( sizeof(i64)==8 );
2498     assert( sizeof(u64)==8 );
2499     assert( sizeof(u32)==4 );
2500     assert( sizeof(u16)==2 );
2501     assert( sizeof(Pgno)==4 );
2502 
2503     pBt = sqlite3MallocZero( sizeof(*pBt) );
2504     if( pBt==0 ){
2505       rc = SQLITE_NOMEM_BKPT;
2506       goto btree_open_out;
2507     }
2508     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2509                           sizeof(MemPage), flags, vfsFlags, pageReinit);
2510     if( rc==SQLITE_OK ){
2511       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2512       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2513     }
2514     if( rc!=SQLITE_OK ){
2515       goto btree_open_out;
2516     }
2517     pBt->openFlags = (u8)flags;
2518     pBt->db = db;
2519     sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2520     p->pBt = pBt;
2521 
2522     pBt->pCursor = 0;
2523     pBt->pPage1 = 0;
2524     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2525 #if defined(SQLITE_SECURE_DELETE)
2526     pBt->btsFlags |= BTS_SECURE_DELETE;
2527 #elif defined(SQLITE_FAST_SECURE_DELETE)
2528     pBt->btsFlags |= BTS_OVERWRITE;
2529 #endif
2530     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2531     ** determined by the 2-byte integer located at an offset of 16 bytes from
2532     ** the beginning of the database file. */
2533     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2534     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2535          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2536       pBt->pageSize = 0;
2537 #ifndef SQLITE_OMIT_AUTOVACUUM
2538       /* If the magic name ":memory:" will create an in-memory database, then
2539       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2540       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2541       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2542       ** regular file-name. In this case the auto-vacuum applies as per normal.
2543       */
2544       if( zFilename && !isMemdb ){
2545         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2546         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2547       }
2548 #endif
2549       nReserve = 0;
2550     }else{
2551       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2552       ** determined by the one-byte unsigned integer found at an offset of 20
2553       ** into the database file header. */
2554       nReserve = zDbHeader[20];
2555       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2556 #ifndef SQLITE_OMIT_AUTOVACUUM
2557       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2558       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2559 #endif
2560     }
2561     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2562     if( rc ) goto btree_open_out;
2563     pBt->usableSize = pBt->pageSize - nReserve;
2564     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
2565 
2566 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2567     /* Add the new BtShared object to the linked list sharable BtShareds.
2568     */
2569     pBt->nRef = 1;
2570     if( p->sharable ){
2571       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2572       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2573       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2574         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2575         if( pBt->mutex==0 ){
2576           rc = SQLITE_NOMEM_BKPT;
2577           goto btree_open_out;
2578         }
2579       }
2580       sqlite3_mutex_enter(mutexShared);
2581       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2582       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2583       sqlite3_mutex_leave(mutexShared);
2584     }
2585 #endif
2586   }
2587 
2588 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2589   /* If the new Btree uses a sharable pBtShared, then link the new
2590   ** Btree into the list of all sharable Btrees for the same connection.
2591   ** The list is kept in ascending order by pBt address.
2592   */
2593   if( p->sharable ){
2594     int i;
2595     Btree *pSib;
2596     for(i=0; i<db->nDb; i++){
2597       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2598         while( pSib->pPrev ){ pSib = pSib->pPrev; }
2599         if( (uptr)p->pBt<(uptr)pSib->pBt ){
2600           p->pNext = pSib;
2601           p->pPrev = 0;
2602           pSib->pPrev = p;
2603         }else{
2604           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2605             pSib = pSib->pNext;
2606           }
2607           p->pNext = pSib->pNext;
2608           p->pPrev = pSib;
2609           if( p->pNext ){
2610             p->pNext->pPrev = p;
2611           }
2612           pSib->pNext = p;
2613         }
2614         break;
2615       }
2616     }
2617   }
2618 #endif
2619   *ppBtree = p;
2620 
2621 btree_open_out:
2622   if( rc!=SQLITE_OK ){
2623     if( pBt && pBt->pPager ){
2624       sqlite3PagerClose(pBt->pPager, 0);
2625     }
2626     sqlite3_free(pBt);
2627     sqlite3_free(p);
2628     *ppBtree = 0;
2629   }else{
2630     sqlite3_file *pFile;
2631 
2632     /* If the B-Tree was successfully opened, set the pager-cache size to the
2633     ** default value. Except, when opening on an existing shared pager-cache,
2634     ** do not change the pager-cache size.
2635     */
2636     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2637       sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2638     }
2639 
2640     pFile = sqlite3PagerFile(pBt->pPager);
2641     if( pFile->pMethods ){
2642       sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2643     }
2644   }
2645   if( mutexOpen ){
2646     assert( sqlite3_mutex_held(mutexOpen) );
2647     sqlite3_mutex_leave(mutexOpen);
2648   }
2649   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2650   return rc;
2651 }
2652 
2653 /*
2654 ** Decrement the BtShared.nRef counter.  When it reaches zero,
2655 ** remove the BtShared structure from the sharing list.  Return
2656 ** true if the BtShared.nRef counter reaches zero and return
2657 ** false if it is still positive.
2658 */
2659 static int removeFromSharingList(BtShared *pBt){
2660 #ifndef SQLITE_OMIT_SHARED_CACHE
2661   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2662   BtShared *pList;
2663   int removed = 0;
2664 
2665   assert( sqlite3_mutex_notheld(pBt->mutex) );
2666   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2667   sqlite3_mutex_enter(pMainMtx);
2668   pBt->nRef--;
2669   if( pBt->nRef<=0 ){
2670     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2671       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2672     }else{
2673       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2674       while( ALWAYS(pList) && pList->pNext!=pBt ){
2675         pList=pList->pNext;
2676       }
2677       if( ALWAYS(pList) ){
2678         pList->pNext = pBt->pNext;
2679       }
2680     }
2681     if( SQLITE_THREADSAFE ){
2682       sqlite3_mutex_free(pBt->mutex);
2683     }
2684     removed = 1;
2685   }
2686   sqlite3_mutex_leave(pMainMtx);
2687   return removed;
2688 #else
2689   return 1;
2690 #endif
2691 }
2692 
2693 /*
2694 ** Make sure pBt->pTmpSpace points to an allocation of
2695 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2696 ** pointer.
2697 */
2698 static void allocateTempSpace(BtShared *pBt){
2699   if( !pBt->pTmpSpace ){
2700     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2701 
2702     /* One of the uses of pBt->pTmpSpace is to format cells before
2703     ** inserting them into a leaf page (function fillInCell()). If
2704     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2705     ** by the various routines that manipulate binary cells. Which
2706     ** can mean that fillInCell() only initializes the first 2 or 3
2707     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2708     ** it into a database page. This is not actually a problem, but it
2709     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2710     ** data is passed to system call write(). So to avoid this error,
2711     ** zero the first 4 bytes of temp space here.
2712     **
2713     ** Also:  Provide four bytes of initialized space before the
2714     ** beginning of pTmpSpace as an area available to prepend the
2715     ** left-child pointer to the beginning of a cell.
2716     */
2717     if( pBt->pTmpSpace ){
2718       memset(pBt->pTmpSpace, 0, 8);
2719       pBt->pTmpSpace += 4;
2720     }
2721   }
2722 }
2723 
2724 /*
2725 ** Free the pBt->pTmpSpace allocation
2726 */
2727 static void freeTempSpace(BtShared *pBt){
2728   if( pBt->pTmpSpace ){
2729     pBt->pTmpSpace -= 4;
2730     sqlite3PageFree(pBt->pTmpSpace);
2731     pBt->pTmpSpace = 0;
2732   }
2733 }
2734 
2735 /*
2736 ** Close an open database and invalidate all cursors.
2737 */
2738 int sqlite3BtreeClose(Btree *p){
2739   BtShared *pBt = p->pBt;
2740 
2741   /* Close all cursors opened via this handle.  */
2742   assert( sqlite3_mutex_held(p->db->mutex) );
2743   sqlite3BtreeEnter(p);
2744 
2745   /* Verify that no other cursors have this Btree open */
2746 #ifdef SQLITE_DEBUG
2747   {
2748     BtCursor *pCur = pBt->pCursor;
2749     while( pCur ){
2750       BtCursor *pTmp = pCur;
2751       pCur = pCur->pNext;
2752       assert( pTmp->pBtree!=p );
2753 
2754     }
2755   }
2756 #endif
2757 
2758   /* Rollback any active transaction and free the handle structure.
2759   ** The call to sqlite3BtreeRollback() drops any table-locks held by
2760   ** this handle.
2761   */
2762   sqlite3BtreeRollback(p, SQLITE_OK, 0);
2763   sqlite3BtreeLeave(p);
2764 
2765   /* If there are still other outstanding references to the shared-btree
2766   ** structure, return now. The remainder of this procedure cleans
2767   ** up the shared-btree.
2768   */
2769   assert( p->wantToLock==0 && p->locked==0 );
2770   if( !p->sharable || removeFromSharingList(pBt) ){
2771     /* The pBt is no longer on the sharing list, so we can access
2772     ** it without having to hold the mutex.
2773     **
2774     ** Clean out and delete the BtShared object.
2775     */
2776     assert( !pBt->pCursor );
2777     sqlite3PagerClose(pBt->pPager, p->db);
2778     if( pBt->xFreeSchema && pBt->pSchema ){
2779       pBt->xFreeSchema(pBt->pSchema);
2780     }
2781     sqlite3DbFree(0, pBt->pSchema);
2782     freeTempSpace(pBt);
2783     sqlite3_free(pBt);
2784   }
2785 
2786 #ifndef SQLITE_OMIT_SHARED_CACHE
2787   assert( p->wantToLock==0 );
2788   assert( p->locked==0 );
2789   if( p->pPrev ) p->pPrev->pNext = p->pNext;
2790   if( p->pNext ) p->pNext->pPrev = p->pPrev;
2791 #endif
2792 
2793   sqlite3_free(p);
2794   return SQLITE_OK;
2795 }
2796 
2797 /*
2798 ** Change the "soft" limit on the number of pages in the cache.
2799 ** Unused and unmodified pages will be recycled when the number of
2800 ** pages in the cache exceeds this soft limit.  But the size of the
2801 ** cache is allowed to grow larger than this limit if it contains
2802 ** dirty pages or pages still in active use.
2803 */
2804 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2805   BtShared *pBt = p->pBt;
2806   assert( sqlite3_mutex_held(p->db->mutex) );
2807   sqlite3BtreeEnter(p);
2808   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2809   sqlite3BtreeLeave(p);
2810   return SQLITE_OK;
2811 }
2812 
2813 /*
2814 ** Change the "spill" limit on the number of pages in the cache.
2815 ** If the number of pages exceeds this limit during a write transaction,
2816 ** the pager might attempt to "spill" pages to the journal early in
2817 ** order to free up memory.
2818 **
2819 ** The value returned is the current spill size.  If zero is passed
2820 ** as an argument, no changes are made to the spill size setting, so
2821 ** using mxPage of 0 is a way to query the current spill size.
2822 */
2823 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2824   BtShared *pBt = p->pBt;
2825   int res;
2826   assert( sqlite3_mutex_held(p->db->mutex) );
2827   sqlite3BtreeEnter(p);
2828   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2829   sqlite3BtreeLeave(p);
2830   return res;
2831 }
2832 
2833 #if SQLITE_MAX_MMAP_SIZE>0
2834 /*
2835 ** Change the limit on the amount of the database file that may be
2836 ** memory mapped.
2837 */
2838 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2839   BtShared *pBt = p->pBt;
2840   assert( sqlite3_mutex_held(p->db->mutex) );
2841   sqlite3BtreeEnter(p);
2842   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2843   sqlite3BtreeLeave(p);
2844   return SQLITE_OK;
2845 }
2846 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2847 
2848 /*
2849 ** Change the way data is synced to disk in order to increase or decrease
2850 ** how well the database resists damage due to OS crashes and power
2851 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
2852 ** there is a high probability of damage)  Level 2 is the default.  There
2853 ** is a very low but non-zero probability of damage.  Level 3 reduces the
2854 ** probability of damage to near zero but with a write performance reduction.
2855 */
2856 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2857 int sqlite3BtreeSetPagerFlags(
2858   Btree *p,              /* The btree to set the safety level on */
2859   unsigned pgFlags       /* Various PAGER_* flags */
2860 ){
2861   BtShared *pBt = p->pBt;
2862   assert( sqlite3_mutex_held(p->db->mutex) );
2863   sqlite3BtreeEnter(p);
2864   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2865   sqlite3BtreeLeave(p);
2866   return SQLITE_OK;
2867 }
2868 #endif
2869 
2870 /*
2871 ** Change the default pages size and the number of reserved bytes per page.
2872 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2873 ** without changing anything.
2874 **
2875 ** The page size must be a power of 2 between 512 and 65536.  If the page
2876 ** size supplied does not meet this constraint then the page size is not
2877 ** changed.
2878 **
2879 ** Page sizes are constrained to be a power of two so that the region
2880 ** of the database file used for locking (beginning at PENDING_BYTE,
2881 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2882 ** at the beginning of a page.
2883 **
2884 ** If parameter nReserve is less than zero, then the number of reserved
2885 ** bytes per page is left unchanged.
2886 **
2887 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2888 ** and autovacuum mode can no longer be changed.
2889 */
2890 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2891   int rc = SQLITE_OK;
2892   int x;
2893   BtShared *pBt = p->pBt;
2894   assert( nReserve>=0 && nReserve<=255 );
2895   sqlite3BtreeEnter(p);
2896   pBt->nReserveWanted = nReserve;
2897   x = pBt->pageSize - pBt->usableSize;
2898   if( nReserve<x ) nReserve = x;
2899   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2900     sqlite3BtreeLeave(p);
2901     return SQLITE_READONLY;
2902   }
2903   assert( nReserve>=0 && nReserve<=255 );
2904   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2905         ((pageSize-1)&pageSize)==0 ){
2906     assert( (pageSize & 7)==0 );
2907     assert( !pBt->pCursor );
2908     if( nReserve>32 && pageSize==512 ) pageSize = 1024;
2909     pBt->pageSize = (u32)pageSize;
2910     freeTempSpace(pBt);
2911   }
2912   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2913   pBt->usableSize = pBt->pageSize - (u16)nReserve;
2914   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2915   sqlite3BtreeLeave(p);
2916   return rc;
2917 }
2918 
2919 /*
2920 ** Return the currently defined page size
2921 */
2922 int sqlite3BtreeGetPageSize(Btree *p){
2923   return p->pBt->pageSize;
2924 }
2925 
2926 /*
2927 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2928 ** may only be called if it is guaranteed that the b-tree mutex is already
2929 ** held.
2930 **
2931 ** This is useful in one special case in the backup API code where it is
2932 ** known that the shared b-tree mutex is held, but the mutex on the
2933 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2934 ** were to be called, it might collide with some other operation on the
2935 ** database handle that owns *p, causing undefined behavior.
2936 */
2937 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2938   int n;
2939   assert( sqlite3_mutex_held(p->pBt->mutex) );
2940   n = p->pBt->pageSize - p->pBt->usableSize;
2941   return n;
2942 }
2943 
2944 /*
2945 ** Return the number of bytes of space at the end of every page that
2946 ** are intentually left unused.  This is the "reserved" space that is
2947 ** sometimes used by extensions.
2948 **
2949 ** The value returned is the larger of the current reserve size and
2950 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2951 ** The amount of reserve can only grow - never shrink.
2952 */
2953 int sqlite3BtreeGetRequestedReserve(Btree *p){
2954   int n1, n2;
2955   sqlite3BtreeEnter(p);
2956   n1 = (int)p->pBt->nReserveWanted;
2957   n2 = sqlite3BtreeGetReserveNoMutex(p);
2958   sqlite3BtreeLeave(p);
2959   return n1>n2 ? n1 : n2;
2960 }
2961 
2962 
2963 /*
2964 ** Set the maximum page count for a database if mxPage is positive.
2965 ** No changes are made if mxPage is 0 or negative.
2966 ** Regardless of the value of mxPage, return the maximum page count.
2967 */
2968 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2969   Pgno n;
2970   sqlite3BtreeEnter(p);
2971   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2972   sqlite3BtreeLeave(p);
2973   return n;
2974 }
2975 
2976 /*
2977 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2978 **
2979 **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2980 **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2981 **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2982 **    newFlag==(-1)    No changes
2983 **
2984 ** This routine acts as a query if newFlag is less than zero
2985 **
2986 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2987 ** freelist leaf pages are not written back to the database.  Thus in-page
2988 ** deleted content is cleared, but freelist deleted content is not.
2989 **
2990 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2991 ** that freelist leaf pages are written back into the database, increasing
2992 ** the amount of disk I/O.
2993 */
2994 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2995   int b;
2996   if( p==0 ) return 0;
2997   sqlite3BtreeEnter(p);
2998   assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2999   assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3000   if( newFlag>=0 ){
3001     p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3002     p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3003   }
3004   b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3005   sqlite3BtreeLeave(p);
3006   return b;
3007 }
3008 
3009 /*
3010 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3011 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3012 ** is disabled. The default value for the auto-vacuum property is
3013 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3014 */
3015 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3016 #ifdef SQLITE_OMIT_AUTOVACUUM
3017   return SQLITE_READONLY;
3018 #else
3019   BtShared *pBt = p->pBt;
3020   int rc = SQLITE_OK;
3021   u8 av = (u8)autoVacuum;
3022 
3023   sqlite3BtreeEnter(p);
3024   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3025     rc = SQLITE_READONLY;
3026   }else{
3027     pBt->autoVacuum = av ?1:0;
3028     pBt->incrVacuum = av==2 ?1:0;
3029   }
3030   sqlite3BtreeLeave(p);
3031   return rc;
3032 #endif
3033 }
3034 
3035 /*
3036 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3037 ** enabled 1 is returned. Otherwise 0.
3038 */
3039 int sqlite3BtreeGetAutoVacuum(Btree *p){
3040 #ifdef SQLITE_OMIT_AUTOVACUUM
3041   return BTREE_AUTOVACUUM_NONE;
3042 #else
3043   int rc;
3044   sqlite3BtreeEnter(p);
3045   rc = (
3046     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3047     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3048     BTREE_AUTOVACUUM_INCR
3049   );
3050   sqlite3BtreeLeave(p);
3051   return rc;
3052 #endif
3053 }
3054 
3055 /*
3056 ** If the user has not set the safety-level for this database connection
3057 ** using "PRAGMA synchronous", and if the safety-level is not already
3058 ** set to the value passed to this function as the second parameter,
3059 ** set it so.
3060 */
3061 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3062     && !defined(SQLITE_OMIT_WAL)
3063 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3064   sqlite3 *db;
3065   Db *pDb;
3066   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3067     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3068     if( pDb->bSyncSet==0
3069      && pDb->safety_level!=safety_level
3070      && pDb!=&db->aDb[1]
3071     ){
3072       pDb->safety_level = safety_level;
3073       sqlite3PagerSetFlags(pBt->pPager,
3074           pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3075     }
3076   }
3077 }
3078 #else
3079 # define setDefaultSyncFlag(pBt,safety_level)
3080 #endif
3081 
3082 /* Forward declaration */
3083 static int newDatabase(BtShared*);
3084 
3085 
3086 /*
3087 ** Get a reference to pPage1 of the database file.  This will
3088 ** also acquire a readlock on that file.
3089 **
3090 ** SQLITE_OK is returned on success.  If the file is not a
3091 ** well-formed database file, then SQLITE_CORRUPT is returned.
3092 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
3093 ** is returned if we run out of memory.
3094 */
3095 static int lockBtree(BtShared *pBt){
3096   int rc;              /* Result code from subfunctions */
3097   MemPage *pPage1;     /* Page 1 of the database file */
3098   u32 nPage;           /* Number of pages in the database */
3099   u32 nPageFile = 0;   /* Number of pages in the database file */
3100   u32 nPageHeader;     /* Number of pages in the database according to hdr */
3101 
3102   assert( sqlite3_mutex_held(pBt->mutex) );
3103   assert( pBt->pPage1==0 );
3104   rc = sqlite3PagerSharedLock(pBt->pPager);
3105   if( rc!=SQLITE_OK ) return rc;
3106   rc = btreeGetPage(pBt, 1, &pPage1, 0);
3107   if( rc!=SQLITE_OK ) return rc;
3108 
3109   /* Do some checking to help insure the file we opened really is
3110   ** a valid database file.
3111   */
3112   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
3113   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3114   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3115     nPage = nPageFile;
3116   }
3117   if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3118     nPage = 0;
3119   }
3120   if( nPage>0 ){
3121     u32 pageSize;
3122     u32 usableSize;
3123     u8 *page1 = pPage1->aData;
3124     rc = SQLITE_NOTADB;
3125     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3126     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3127     ** 61 74 20 33 00. */
3128     if( memcmp(page1, zMagicHeader, 16)!=0 ){
3129       goto page1_init_failed;
3130     }
3131 
3132 #ifdef SQLITE_OMIT_WAL
3133     if( page1[18]>1 ){
3134       pBt->btsFlags |= BTS_READ_ONLY;
3135     }
3136     if( page1[19]>1 ){
3137       goto page1_init_failed;
3138     }
3139 #else
3140     if( page1[18]>2 ){
3141       pBt->btsFlags |= BTS_READ_ONLY;
3142     }
3143     if( page1[19]>2 ){
3144       goto page1_init_failed;
3145     }
3146 
3147     /* If the write version is set to 2, this database should be accessed
3148     ** in WAL mode. If the log is not already open, open it now. Then
3149     ** return SQLITE_OK and return without populating BtShared.pPage1.
3150     ** The caller detects this and calls this function again. This is
3151     ** required as the version of page 1 currently in the page1 buffer
3152     ** may not be the latest version - there may be a newer one in the log
3153     ** file.
3154     */
3155     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3156       int isOpen = 0;
3157       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3158       if( rc!=SQLITE_OK ){
3159         goto page1_init_failed;
3160       }else{
3161         setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3162         if( isOpen==0 ){
3163           releasePageOne(pPage1);
3164           return SQLITE_OK;
3165         }
3166       }
3167       rc = SQLITE_NOTADB;
3168     }else{
3169       setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3170     }
3171 #endif
3172 
3173     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3174     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3175     **
3176     ** The original design allowed these amounts to vary, but as of
3177     ** version 3.6.0, we require them to be fixed.
3178     */
3179     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3180       goto page1_init_failed;
3181     }
3182     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3183     ** determined by the 2-byte integer located at an offset of 16 bytes from
3184     ** the beginning of the database file. */
3185     pageSize = (page1[16]<<8) | (page1[17]<<16);
3186     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3187     ** between 512 and 65536 inclusive. */
3188     if( ((pageSize-1)&pageSize)!=0
3189      || pageSize>SQLITE_MAX_PAGE_SIZE
3190      || pageSize<=256
3191     ){
3192       goto page1_init_failed;
3193     }
3194     pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3195     assert( (pageSize & 7)==0 );
3196     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3197     ** integer at offset 20 is the number of bytes of space at the end of
3198     ** each page to reserve for extensions.
3199     **
3200     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3201     ** determined by the one-byte unsigned integer found at an offset of 20
3202     ** into the database file header. */
3203     usableSize = pageSize - page1[20];
3204     if( (u32)pageSize!=pBt->pageSize ){
3205       /* After reading the first page of the database assuming a page size
3206       ** of BtShared.pageSize, we have discovered that the page-size is
3207       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3208       ** zero and return SQLITE_OK. The caller will call this function
3209       ** again with the correct page-size.
3210       */
3211       releasePageOne(pPage1);
3212       pBt->usableSize = usableSize;
3213       pBt->pageSize = pageSize;
3214       freeTempSpace(pBt);
3215       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3216                                    pageSize-usableSize);
3217       return rc;
3218     }
3219     if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3220       rc = SQLITE_CORRUPT_BKPT;
3221       goto page1_init_failed;
3222     }
3223     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3224     ** be less than 480. In other words, if the page size is 512, then the
3225     ** reserved space size cannot exceed 32. */
3226     if( usableSize<480 ){
3227       goto page1_init_failed;
3228     }
3229     pBt->pageSize = pageSize;
3230     pBt->usableSize = usableSize;
3231 #ifndef SQLITE_OMIT_AUTOVACUUM
3232     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3233     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3234 #endif
3235   }
3236 
3237   /* maxLocal is the maximum amount of payload to store locally for
3238   ** a cell.  Make sure it is small enough so that at least minFanout
3239   ** cells can will fit on one page.  We assume a 10-byte page header.
3240   ** Besides the payload, the cell must store:
3241   **     2-byte pointer to the cell
3242   **     4-byte child pointer
3243   **     9-byte nKey value
3244   **     4-byte nData value
3245   **     4-byte overflow page pointer
3246   ** So a cell consists of a 2-byte pointer, a header which is as much as
3247   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3248   ** page pointer.
3249   */
3250   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3251   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3252   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3253   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3254   if( pBt->maxLocal>127 ){
3255     pBt->max1bytePayload = 127;
3256   }else{
3257     pBt->max1bytePayload = (u8)pBt->maxLocal;
3258   }
3259   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3260   pBt->pPage1 = pPage1;
3261   pBt->nPage = nPage;
3262   return SQLITE_OK;
3263 
3264 page1_init_failed:
3265   releasePageOne(pPage1);
3266   pBt->pPage1 = 0;
3267   return rc;
3268 }
3269 
3270 #ifndef NDEBUG
3271 /*
3272 ** Return the number of cursors open on pBt. This is for use
3273 ** in assert() expressions, so it is only compiled if NDEBUG is not
3274 ** defined.
3275 **
3276 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
3277 ** false then all cursors are counted.
3278 **
3279 ** For the purposes of this routine, a cursor is any cursor that
3280 ** is capable of reading or writing to the database.  Cursors that
3281 ** have been tripped into the CURSOR_FAULT state are not counted.
3282 */
3283 static int countValidCursors(BtShared *pBt, int wrOnly){
3284   BtCursor *pCur;
3285   int r = 0;
3286   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3287     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3288      && pCur->eState!=CURSOR_FAULT ) r++;
3289   }
3290   return r;
3291 }
3292 #endif
3293 
3294 /*
3295 ** If there are no outstanding cursors and we are not in the middle
3296 ** of a transaction but there is a read lock on the database, then
3297 ** this routine unrefs the first page of the database file which
3298 ** has the effect of releasing the read lock.
3299 **
3300 ** If there is a transaction in progress, this routine is a no-op.
3301 */
3302 static void unlockBtreeIfUnused(BtShared *pBt){
3303   assert( sqlite3_mutex_held(pBt->mutex) );
3304   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3305   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3306     MemPage *pPage1 = pBt->pPage1;
3307     assert( pPage1->aData );
3308     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3309     pBt->pPage1 = 0;
3310     releasePageOne(pPage1);
3311   }
3312 }
3313 
3314 /*
3315 ** If pBt points to an empty file then convert that empty file
3316 ** into a new empty database by initializing the first page of
3317 ** the database.
3318 */
3319 static int newDatabase(BtShared *pBt){
3320   MemPage *pP1;
3321   unsigned char *data;
3322   int rc;
3323 
3324   assert( sqlite3_mutex_held(pBt->mutex) );
3325   if( pBt->nPage>0 ){
3326     return SQLITE_OK;
3327   }
3328   pP1 = pBt->pPage1;
3329   assert( pP1!=0 );
3330   data = pP1->aData;
3331   rc = sqlite3PagerWrite(pP1->pDbPage);
3332   if( rc ) return rc;
3333   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3334   assert( sizeof(zMagicHeader)==16 );
3335   data[16] = (u8)((pBt->pageSize>>8)&0xff);
3336   data[17] = (u8)((pBt->pageSize>>16)&0xff);
3337   data[18] = 1;
3338   data[19] = 1;
3339   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3340   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3341   data[21] = 64;
3342   data[22] = 32;
3343   data[23] = 32;
3344   memset(&data[24], 0, 100-24);
3345   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3346   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3347 #ifndef SQLITE_OMIT_AUTOVACUUM
3348   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3349   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3350   put4byte(&data[36 + 4*4], pBt->autoVacuum);
3351   put4byte(&data[36 + 7*4], pBt->incrVacuum);
3352 #endif
3353   pBt->nPage = 1;
3354   data[31] = 1;
3355   return SQLITE_OK;
3356 }
3357 
3358 /*
3359 ** Initialize the first page of the database file (creating a database
3360 ** consisting of a single page and no schema objects). Return SQLITE_OK
3361 ** if successful, or an SQLite error code otherwise.
3362 */
3363 int sqlite3BtreeNewDb(Btree *p){
3364   int rc;
3365   sqlite3BtreeEnter(p);
3366   p->pBt->nPage = 0;
3367   rc = newDatabase(p->pBt);
3368   sqlite3BtreeLeave(p);
3369   return rc;
3370 }
3371 
3372 /*
3373 ** Attempt to start a new transaction. A write-transaction
3374 ** is started if the second argument is nonzero, otherwise a read-
3375 ** transaction.  If the second argument is 2 or more and exclusive
3376 ** transaction is started, meaning that no other process is allowed
3377 ** to access the database.  A preexisting transaction may not be
3378 ** upgraded to exclusive by calling this routine a second time - the
3379 ** exclusivity flag only works for a new transaction.
3380 **
3381 ** A write-transaction must be started before attempting any
3382 ** changes to the database.  None of the following routines
3383 ** will work unless a transaction is started first:
3384 **
3385 **      sqlite3BtreeCreateTable()
3386 **      sqlite3BtreeCreateIndex()
3387 **      sqlite3BtreeClearTable()
3388 **      sqlite3BtreeDropTable()
3389 **      sqlite3BtreeInsert()
3390 **      sqlite3BtreeDelete()
3391 **      sqlite3BtreeUpdateMeta()
3392 **
3393 ** If an initial attempt to acquire the lock fails because of lock contention
3394 ** and the database was previously unlocked, then invoke the busy handler
3395 ** if there is one.  But if there was previously a read-lock, do not
3396 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
3397 ** returned when there is already a read-lock in order to avoid a deadlock.
3398 **
3399 ** Suppose there are two processes A and B.  A has a read lock and B has
3400 ** a reserved lock.  B tries to promote to exclusive but is blocked because
3401 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
3402 ** One or the other of the two processes must give way or there can be
3403 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
3404 ** when A already has a read lock, we encourage A to give up and let B
3405 ** proceed.
3406 */
3407 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3408   BtShared *pBt = p->pBt;
3409   Pager *pPager = pBt->pPager;
3410   int rc = SQLITE_OK;
3411 
3412   sqlite3BtreeEnter(p);
3413   btreeIntegrity(p);
3414 
3415   /* If the btree is already in a write-transaction, or it
3416   ** is already in a read-transaction and a read-transaction
3417   ** is requested, this is a no-op.
3418   */
3419   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3420     goto trans_begun;
3421   }
3422   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3423 
3424   if( (p->db->flags & SQLITE_ResetDatabase)
3425    && sqlite3PagerIsreadonly(pPager)==0
3426   ){
3427     pBt->btsFlags &= ~BTS_READ_ONLY;
3428   }
3429 
3430   /* Write transactions are not possible on a read-only database */
3431   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3432     rc = SQLITE_READONLY;
3433     goto trans_begun;
3434   }
3435 
3436 #ifndef SQLITE_OMIT_SHARED_CACHE
3437   {
3438     sqlite3 *pBlock = 0;
3439     /* If another database handle has already opened a write transaction
3440     ** on this shared-btree structure and a second write transaction is
3441     ** requested, return SQLITE_LOCKED.
3442     */
3443     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3444      || (pBt->btsFlags & BTS_PENDING)!=0
3445     ){
3446       pBlock = pBt->pWriter->db;
3447     }else if( wrflag>1 ){
3448       BtLock *pIter;
3449       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3450         if( pIter->pBtree!=p ){
3451           pBlock = pIter->pBtree->db;
3452           break;
3453         }
3454       }
3455     }
3456     if( pBlock ){
3457       sqlite3ConnectionBlocked(p->db, pBlock);
3458       rc = SQLITE_LOCKED_SHAREDCACHE;
3459       goto trans_begun;
3460     }
3461   }
3462 #endif
3463 
3464   /* Any read-only or read-write transaction implies a read-lock on
3465   ** page 1. So if some other shared-cache client already has a write-lock
3466   ** on page 1, the transaction cannot be opened. */
3467   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3468   if( SQLITE_OK!=rc ) goto trans_begun;
3469 
3470   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3471   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3472   do {
3473     sqlite3PagerWalDb(pPager, p->db);
3474 
3475 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3476     /* If transitioning from no transaction directly to a write transaction,
3477     ** block for the WRITER lock first if possible. */
3478     if( pBt->pPage1==0 && wrflag ){
3479       assert( pBt->inTransaction==TRANS_NONE );
3480       rc = sqlite3PagerWalWriteLock(pPager, 1);
3481       if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3482     }
3483 #endif
3484 
3485     /* Call lockBtree() until either pBt->pPage1 is populated or
3486     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3487     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3488     ** reading page 1 it discovers that the page-size of the database
3489     ** file is not pBt->pageSize. In this case lockBtree() will update
3490     ** pBt->pageSize to the page-size of the file on disk.
3491     */
3492     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3493 
3494     if( rc==SQLITE_OK && wrflag ){
3495       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3496         rc = SQLITE_READONLY;
3497       }else{
3498         rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3499         if( rc==SQLITE_OK ){
3500           rc = newDatabase(pBt);
3501         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3502           /* if there was no transaction opened when this function was
3503           ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3504           ** code to SQLITE_BUSY. */
3505           rc = SQLITE_BUSY;
3506         }
3507       }
3508     }
3509 
3510     if( rc!=SQLITE_OK ){
3511       (void)sqlite3PagerWalWriteLock(pPager, 0);
3512       unlockBtreeIfUnused(pBt);
3513     }
3514   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3515           btreeInvokeBusyHandler(pBt) );
3516   sqlite3PagerWalDb(pPager, 0);
3517 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3518   if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3519 #endif
3520 
3521   if( rc==SQLITE_OK ){
3522     if( p->inTrans==TRANS_NONE ){
3523       pBt->nTransaction++;
3524 #ifndef SQLITE_OMIT_SHARED_CACHE
3525       if( p->sharable ){
3526         assert( p->lock.pBtree==p && p->lock.iTable==1 );
3527         p->lock.eLock = READ_LOCK;
3528         p->lock.pNext = pBt->pLock;
3529         pBt->pLock = &p->lock;
3530       }
3531 #endif
3532     }
3533     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3534     if( p->inTrans>pBt->inTransaction ){
3535       pBt->inTransaction = p->inTrans;
3536     }
3537     if( wrflag ){
3538       MemPage *pPage1 = pBt->pPage1;
3539 #ifndef SQLITE_OMIT_SHARED_CACHE
3540       assert( !pBt->pWriter );
3541       pBt->pWriter = p;
3542       pBt->btsFlags &= ~BTS_EXCLUSIVE;
3543       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3544 #endif
3545 
3546       /* If the db-size header field is incorrect (as it may be if an old
3547       ** client has been writing the database file), update it now. Doing
3548       ** this sooner rather than later means the database size can safely
3549       ** re-read the database size from page 1 if a savepoint or transaction
3550       ** rollback occurs within the transaction.
3551       */
3552       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3553         rc = sqlite3PagerWrite(pPage1->pDbPage);
3554         if( rc==SQLITE_OK ){
3555           put4byte(&pPage1->aData[28], pBt->nPage);
3556         }
3557       }
3558     }
3559   }
3560 
3561 trans_begun:
3562   if( rc==SQLITE_OK ){
3563     if( pSchemaVersion ){
3564       *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3565     }
3566     if( wrflag ){
3567       /* This call makes sure that the pager has the correct number of
3568       ** open savepoints. If the second parameter is greater than 0 and
3569       ** the sub-journal is not already open, then it will be opened here.
3570       */
3571       rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3572     }
3573   }
3574 
3575   btreeIntegrity(p);
3576   sqlite3BtreeLeave(p);
3577   return rc;
3578 }
3579 
3580 #ifndef SQLITE_OMIT_AUTOVACUUM
3581 
3582 /*
3583 ** Set the pointer-map entries for all children of page pPage. Also, if
3584 ** pPage contains cells that point to overflow pages, set the pointer
3585 ** map entries for the overflow pages as well.
3586 */
3587 static int setChildPtrmaps(MemPage *pPage){
3588   int i;                             /* Counter variable */
3589   int nCell;                         /* Number of cells in page pPage */
3590   int rc;                            /* Return code */
3591   BtShared *pBt = pPage->pBt;
3592   Pgno pgno = pPage->pgno;
3593 
3594   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3595   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3596   if( rc!=SQLITE_OK ) return rc;
3597   nCell = pPage->nCell;
3598 
3599   for(i=0; i<nCell; i++){
3600     u8 *pCell = findCell(pPage, i);
3601 
3602     ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3603 
3604     if( !pPage->leaf ){
3605       Pgno childPgno = get4byte(pCell);
3606       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3607     }
3608   }
3609 
3610   if( !pPage->leaf ){
3611     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3612     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3613   }
3614 
3615   return rc;
3616 }
3617 
3618 /*
3619 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
3620 ** that it points to iTo. Parameter eType describes the type of pointer to
3621 ** be modified, as  follows:
3622 **
3623 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
3624 **                   page of pPage.
3625 **
3626 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3627 **                   page pointed to by one of the cells on pPage.
3628 **
3629 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3630 **                   overflow page in the list.
3631 */
3632 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3633   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3634   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3635   if( eType==PTRMAP_OVERFLOW2 ){
3636     /* The pointer is always the first 4 bytes of the page in this case.  */
3637     if( get4byte(pPage->aData)!=iFrom ){
3638       return SQLITE_CORRUPT_PAGE(pPage);
3639     }
3640     put4byte(pPage->aData, iTo);
3641   }else{
3642     int i;
3643     int nCell;
3644     int rc;
3645 
3646     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3647     if( rc ) return rc;
3648     nCell = pPage->nCell;
3649 
3650     for(i=0; i<nCell; i++){
3651       u8 *pCell = findCell(pPage, i);
3652       if( eType==PTRMAP_OVERFLOW1 ){
3653         CellInfo info;
3654         pPage->xParseCell(pPage, pCell, &info);
3655         if( info.nLocal<info.nPayload ){
3656           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3657             return SQLITE_CORRUPT_PAGE(pPage);
3658           }
3659           if( iFrom==get4byte(pCell+info.nSize-4) ){
3660             put4byte(pCell+info.nSize-4, iTo);
3661             break;
3662           }
3663         }
3664       }else{
3665         if( get4byte(pCell)==iFrom ){
3666           put4byte(pCell, iTo);
3667           break;
3668         }
3669       }
3670     }
3671 
3672     if( i==nCell ){
3673       if( eType!=PTRMAP_BTREE ||
3674           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3675         return SQLITE_CORRUPT_PAGE(pPage);
3676       }
3677       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3678     }
3679   }
3680   return SQLITE_OK;
3681 }
3682 
3683 
3684 /*
3685 ** Move the open database page pDbPage to location iFreePage in the
3686 ** database. The pDbPage reference remains valid.
3687 **
3688 ** The isCommit flag indicates that there is no need to remember that
3689 ** the journal needs to be sync()ed before database page pDbPage->pgno
3690 ** can be written to. The caller has already promised not to write to that
3691 ** page.
3692 */
3693 static int relocatePage(
3694   BtShared *pBt,           /* Btree */
3695   MemPage *pDbPage,        /* Open page to move */
3696   u8 eType,                /* Pointer map 'type' entry for pDbPage */
3697   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
3698   Pgno iFreePage,          /* The location to move pDbPage to */
3699   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
3700 ){
3701   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
3702   Pgno iDbPage = pDbPage->pgno;
3703   Pager *pPager = pBt->pPager;
3704   int rc;
3705 
3706   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3707       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3708   assert( sqlite3_mutex_held(pBt->mutex) );
3709   assert( pDbPage->pBt==pBt );
3710   if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3711 
3712   /* Move page iDbPage from its current location to page number iFreePage */
3713   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3714       iDbPage, iFreePage, iPtrPage, eType));
3715   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3716   if( rc!=SQLITE_OK ){
3717     return rc;
3718   }
3719   pDbPage->pgno = iFreePage;
3720 
3721   /* If pDbPage was a btree-page, then it may have child pages and/or cells
3722   ** that point to overflow pages. The pointer map entries for all these
3723   ** pages need to be changed.
3724   **
3725   ** If pDbPage is an overflow page, then the first 4 bytes may store a
3726   ** pointer to a subsequent overflow page. If this is the case, then
3727   ** the pointer map needs to be updated for the subsequent overflow page.
3728   */
3729   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3730     rc = setChildPtrmaps(pDbPage);
3731     if( rc!=SQLITE_OK ){
3732       return rc;
3733     }
3734   }else{
3735     Pgno nextOvfl = get4byte(pDbPage->aData);
3736     if( nextOvfl!=0 ){
3737       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3738       if( rc!=SQLITE_OK ){
3739         return rc;
3740       }
3741     }
3742   }
3743 
3744   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3745   ** that it points at iFreePage. Also fix the pointer map entry for
3746   ** iPtrPage.
3747   */
3748   if( eType!=PTRMAP_ROOTPAGE ){
3749     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3750     if( rc!=SQLITE_OK ){
3751       return rc;
3752     }
3753     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3754     if( rc!=SQLITE_OK ){
3755       releasePage(pPtrPage);
3756       return rc;
3757     }
3758     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3759     releasePage(pPtrPage);
3760     if( rc==SQLITE_OK ){
3761       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3762     }
3763   }
3764   return rc;
3765 }
3766 
3767 /* Forward declaration required by incrVacuumStep(). */
3768 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3769 
3770 /*
3771 ** Perform a single step of an incremental-vacuum. If successful, return
3772 ** SQLITE_OK. If there is no work to do (and therefore no point in
3773 ** calling this function again), return SQLITE_DONE. Or, if an error
3774 ** occurs, return some other error code.
3775 **
3776 ** More specifically, this function attempts to re-organize the database so
3777 ** that the last page of the file currently in use is no longer in use.
3778 **
3779 ** Parameter nFin is the number of pages that this database would contain
3780 ** were this function called until it returns SQLITE_DONE.
3781 **
3782 ** If the bCommit parameter is non-zero, this function assumes that the
3783 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3784 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3785 ** operation, or false for an incremental vacuum.
3786 */
3787 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3788   Pgno nFreeList;           /* Number of pages still on the free-list */
3789   int rc;
3790 
3791   assert( sqlite3_mutex_held(pBt->mutex) );
3792   assert( iLastPg>nFin );
3793 
3794   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3795     u8 eType;
3796     Pgno iPtrPage;
3797 
3798     nFreeList = get4byte(&pBt->pPage1->aData[36]);
3799     if( nFreeList==0 ){
3800       return SQLITE_DONE;
3801     }
3802 
3803     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3804     if( rc!=SQLITE_OK ){
3805       return rc;
3806     }
3807     if( eType==PTRMAP_ROOTPAGE ){
3808       return SQLITE_CORRUPT_BKPT;
3809     }
3810 
3811     if( eType==PTRMAP_FREEPAGE ){
3812       if( bCommit==0 ){
3813         /* Remove the page from the files free-list. This is not required
3814         ** if bCommit is non-zero. In that case, the free-list will be
3815         ** truncated to zero after this function returns, so it doesn't
3816         ** matter if it still contains some garbage entries.
3817         */
3818         Pgno iFreePg;
3819         MemPage *pFreePg;
3820         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3821         if( rc!=SQLITE_OK ){
3822           return rc;
3823         }
3824         assert( iFreePg==iLastPg );
3825         releasePage(pFreePg);
3826       }
3827     } else {
3828       Pgno iFreePg;             /* Index of free page to move pLastPg to */
3829       MemPage *pLastPg;
3830       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
3831       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
3832 
3833       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3834       if( rc!=SQLITE_OK ){
3835         return rc;
3836       }
3837 
3838       /* If bCommit is zero, this loop runs exactly once and page pLastPg
3839       ** is swapped with the first free page pulled off the free list.
3840       **
3841       ** On the other hand, if bCommit is greater than zero, then keep
3842       ** looping until a free-page located within the first nFin pages
3843       ** of the file is found.
3844       */
3845       if( bCommit==0 ){
3846         eMode = BTALLOC_LE;
3847         iNear = nFin;
3848       }
3849       do {
3850         MemPage *pFreePg;
3851         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3852         if( rc!=SQLITE_OK ){
3853           releasePage(pLastPg);
3854           return rc;
3855         }
3856         releasePage(pFreePg);
3857       }while( bCommit && iFreePg>nFin );
3858       assert( iFreePg<iLastPg );
3859 
3860       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3861       releasePage(pLastPg);
3862       if( rc!=SQLITE_OK ){
3863         return rc;
3864       }
3865     }
3866   }
3867 
3868   if( bCommit==0 ){
3869     do {
3870       iLastPg--;
3871     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3872     pBt->bDoTruncate = 1;
3873     pBt->nPage = iLastPg;
3874   }
3875   return SQLITE_OK;
3876 }
3877 
3878 /*
3879 ** The database opened by the first argument is an auto-vacuum database
3880 ** nOrig pages in size containing nFree free pages. Return the expected
3881 ** size of the database in pages following an auto-vacuum operation.
3882 */
3883 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3884   int nEntry;                     /* Number of entries on one ptrmap page */
3885   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
3886   Pgno nFin;                      /* Return value */
3887 
3888   nEntry = pBt->usableSize/5;
3889   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3890   nFin = nOrig - nFree - nPtrmap;
3891   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3892     nFin--;
3893   }
3894   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3895     nFin--;
3896   }
3897 
3898   return nFin;
3899 }
3900 
3901 /*
3902 ** A write-transaction must be opened before calling this function.
3903 ** It performs a single unit of work towards an incremental vacuum.
3904 **
3905 ** If the incremental vacuum is finished after this function has run,
3906 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3907 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3908 */
3909 int sqlite3BtreeIncrVacuum(Btree *p){
3910   int rc;
3911   BtShared *pBt = p->pBt;
3912 
3913   sqlite3BtreeEnter(p);
3914   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3915   if( !pBt->autoVacuum ){
3916     rc = SQLITE_DONE;
3917   }else{
3918     Pgno nOrig = btreePagecount(pBt);
3919     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3920     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3921 
3922     if( nOrig<nFin || nFree>=nOrig ){
3923       rc = SQLITE_CORRUPT_BKPT;
3924     }else if( nFree>0 ){
3925       rc = saveAllCursors(pBt, 0, 0);
3926       if( rc==SQLITE_OK ){
3927         invalidateAllOverflowCache(pBt);
3928         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3929       }
3930       if( rc==SQLITE_OK ){
3931         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3932         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3933       }
3934     }else{
3935       rc = SQLITE_DONE;
3936     }
3937   }
3938   sqlite3BtreeLeave(p);
3939   return rc;
3940 }
3941 
3942 /*
3943 ** This routine is called prior to sqlite3PagerCommit when a transaction
3944 ** is committed for an auto-vacuum database.
3945 **
3946 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3947 ** the database file should be truncated to during the commit process.
3948 ** i.e. the database has been reorganized so that only the first *pnTrunc
3949 ** pages are in use.
3950 */
3951 static int autoVacuumCommit(BtShared *pBt){
3952   int rc = SQLITE_OK;
3953   Pager *pPager = pBt->pPager;
3954   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3955 
3956   assert( sqlite3_mutex_held(pBt->mutex) );
3957   invalidateAllOverflowCache(pBt);
3958   assert(pBt->autoVacuum);
3959   if( !pBt->incrVacuum ){
3960     Pgno nFin;         /* Number of pages in database after autovacuuming */
3961     Pgno nFree;        /* Number of pages on the freelist initially */
3962     Pgno iFree;        /* The next page to be freed */
3963     Pgno nOrig;        /* Database size before freeing */
3964 
3965     nOrig = btreePagecount(pBt);
3966     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3967       /* It is not possible to create a database for which the final page
3968       ** is either a pointer-map page or the pending-byte page. If one
3969       ** is encountered, this indicates corruption.
3970       */
3971       return SQLITE_CORRUPT_BKPT;
3972     }
3973 
3974     nFree = get4byte(&pBt->pPage1->aData[36]);
3975     nFin = finalDbSize(pBt, nOrig, nFree);
3976     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3977     if( nFin<nOrig ){
3978       rc = saveAllCursors(pBt, 0, 0);
3979     }
3980     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3981       rc = incrVacuumStep(pBt, nFin, iFree, 1);
3982     }
3983     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3984       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3985       put4byte(&pBt->pPage1->aData[32], 0);
3986       put4byte(&pBt->pPage1->aData[36], 0);
3987       put4byte(&pBt->pPage1->aData[28], nFin);
3988       pBt->bDoTruncate = 1;
3989       pBt->nPage = nFin;
3990     }
3991     if( rc!=SQLITE_OK ){
3992       sqlite3PagerRollback(pPager);
3993     }
3994   }
3995 
3996   assert( nRef>=sqlite3PagerRefcount(pPager) );
3997   return rc;
3998 }
3999 
4000 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4001 # define setChildPtrmaps(x) SQLITE_OK
4002 #endif
4003 
4004 /*
4005 ** This routine does the first phase of a two-phase commit.  This routine
4006 ** causes a rollback journal to be created (if it does not already exist)
4007 ** and populated with enough information so that if a power loss occurs
4008 ** the database can be restored to its original state by playing back
4009 ** the journal.  Then the contents of the journal are flushed out to
4010 ** the disk.  After the journal is safely on oxide, the changes to the
4011 ** database are written into the database file and flushed to oxide.
4012 ** At the end of this call, the rollback journal still exists on the
4013 ** disk and we are still holding all locks, so the transaction has not
4014 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4015 ** commit process.
4016 **
4017 ** This call is a no-op if no write-transaction is currently active on pBt.
4018 **
4019 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4020 ** the name of a super-journal file that should be written into the
4021 ** individual journal file, or is NULL, indicating no super-journal file
4022 ** (single database transaction).
4023 **
4024 ** When this is called, the super-journal should already have been
4025 ** created, populated with this journal pointer and synced to disk.
4026 **
4027 ** Once this is routine has returned, the only thing required to commit
4028 ** the write-transaction for this database file is to delete the journal.
4029 */
4030 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4031   int rc = SQLITE_OK;
4032   if( p->inTrans==TRANS_WRITE ){
4033     BtShared *pBt = p->pBt;
4034     sqlite3BtreeEnter(p);
4035 #ifndef SQLITE_OMIT_AUTOVACUUM
4036     if( pBt->autoVacuum ){
4037       rc = autoVacuumCommit(pBt);
4038       if( rc!=SQLITE_OK ){
4039         sqlite3BtreeLeave(p);
4040         return rc;
4041       }
4042     }
4043     if( pBt->bDoTruncate ){
4044       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4045     }
4046 #endif
4047     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4048     sqlite3BtreeLeave(p);
4049   }
4050   return rc;
4051 }
4052 
4053 /*
4054 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4055 ** at the conclusion of a transaction.
4056 */
4057 static void btreeEndTransaction(Btree *p){
4058   BtShared *pBt = p->pBt;
4059   sqlite3 *db = p->db;
4060   assert( sqlite3BtreeHoldsMutex(p) );
4061 
4062 #ifndef SQLITE_OMIT_AUTOVACUUM
4063   pBt->bDoTruncate = 0;
4064 #endif
4065   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4066     /* If there are other active statements that belong to this database
4067     ** handle, downgrade to a read-only transaction. The other statements
4068     ** may still be reading from the database.  */
4069     downgradeAllSharedCacheTableLocks(p);
4070     p->inTrans = TRANS_READ;
4071   }else{
4072     /* If the handle had any kind of transaction open, decrement the
4073     ** transaction count of the shared btree. If the transaction count
4074     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4075     ** call below will unlock the pager.  */
4076     if( p->inTrans!=TRANS_NONE ){
4077       clearAllSharedCacheTableLocks(p);
4078       pBt->nTransaction--;
4079       if( 0==pBt->nTransaction ){
4080         pBt->inTransaction = TRANS_NONE;
4081       }
4082     }
4083 
4084     /* Set the current transaction state to TRANS_NONE and unlock the
4085     ** pager if this call closed the only read or write transaction.  */
4086     p->inTrans = TRANS_NONE;
4087     unlockBtreeIfUnused(pBt);
4088   }
4089 
4090   btreeIntegrity(p);
4091 }
4092 
4093 /*
4094 ** Commit the transaction currently in progress.
4095 **
4096 ** This routine implements the second phase of a 2-phase commit.  The
4097 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4098 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
4099 ** routine did all the work of writing information out to disk and flushing the
4100 ** contents so that they are written onto the disk platter.  All this
4101 ** routine has to do is delete or truncate or zero the header in the
4102 ** the rollback journal (which causes the transaction to commit) and
4103 ** drop locks.
4104 **
4105 ** Normally, if an error occurs while the pager layer is attempting to
4106 ** finalize the underlying journal file, this function returns an error and
4107 ** the upper layer will attempt a rollback. However, if the second argument
4108 ** is non-zero then this b-tree transaction is part of a multi-file
4109 ** transaction. In this case, the transaction has already been committed
4110 ** (by deleting a super-journal file) and the caller will ignore this
4111 ** functions return code. So, even if an error occurs in the pager layer,
4112 ** reset the b-tree objects internal state to indicate that the write
4113 ** transaction has been closed. This is quite safe, as the pager will have
4114 ** transitioned to the error state.
4115 **
4116 ** This will release the write lock on the database file.  If there
4117 ** are no active cursors, it also releases the read lock.
4118 */
4119 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4120 
4121   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4122   sqlite3BtreeEnter(p);
4123   btreeIntegrity(p);
4124 
4125   /* If the handle has a write-transaction open, commit the shared-btrees
4126   ** transaction and set the shared state to TRANS_READ.
4127   */
4128   if( p->inTrans==TRANS_WRITE ){
4129     int rc;
4130     BtShared *pBt = p->pBt;
4131     assert( pBt->inTransaction==TRANS_WRITE );
4132     assert( pBt->nTransaction>0 );
4133     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4134     if( rc!=SQLITE_OK && bCleanup==0 ){
4135       sqlite3BtreeLeave(p);
4136       return rc;
4137     }
4138     p->iBDataVersion--;  /* Compensate for pPager->iDataVersion++; */
4139     pBt->inTransaction = TRANS_READ;
4140     btreeClearHasContent(pBt);
4141   }
4142 
4143   btreeEndTransaction(p);
4144   sqlite3BtreeLeave(p);
4145   return SQLITE_OK;
4146 }
4147 
4148 /*
4149 ** Do both phases of a commit.
4150 */
4151 int sqlite3BtreeCommit(Btree *p){
4152   int rc;
4153   sqlite3BtreeEnter(p);
4154   rc = sqlite3BtreeCommitPhaseOne(p, 0);
4155   if( rc==SQLITE_OK ){
4156     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4157   }
4158   sqlite3BtreeLeave(p);
4159   return rc;
4160 }
4161 
4162 /*
4163 ** This routine sets the state to CURSOR_FAULT and the error
4164 ** code to errCode for every cursor on any BtShared that pBtree
4165 ** references.  Or if the writeOnly flag is set to 1, then only
4166 ** trip write cursors and leave read cursors unchanged.
4167 **
4168 ** Every cursor is a candidate to be tripped, including cursors
4169 ** that belong to other database connections that happen to be
4170 ** sharing the cache with pBtree.
4171 **
4172 ** This routine gets called when a rollback occurs. If the writeOnly
4173 ** flag is true, then only write-cursors need be tripped - read-only
4174 ** cursors save their current positions so that they may continue
4175 ** following the rollback. Or, if writeOnly is false, all cursors are
4176 ** tripped. In general, writeOnly is false if the transaction being
4177 ** rolled back modified the database schema. In this case b-tree root
4178 ** pages may be moved or deleted from the database altogether, making
4179 ** it unsafe for read cursors to continue.
4180 **
4181 ** If the writeOnly flag is true and an error is encountered while
4182 ** saving the current position of a read-only cursor, all cursors,
4183 ** including all read-cursors are tripped.
4184 **
4185 ** SQLITE_OK is returned if successful, or if an error occurs while
4186 ** saving a cursor position, an SQLite error code.
4187 */
4188 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4189   BtCursor *p;
4190   int rc = SQLITE_OK;
4191 
4192   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4193   if( pBtree ){
4194     sqlite3BtreeEnter(pBtree);
4195     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4196       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4197         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4198           rc = saveCursorPosition(p);
4199           if( rc!=SQLITE_OK ){
4200             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4201             break;
4202           }
4203         }
4204       }else{
4205         sqlite3BtreeClearCursor(p);
4206         p->eState = CURSOR_FAULT;
4207         p->skipNext = errCode;
4208       }
4209       btreeReleaseAllCursorPages(p);
4210     }
4211     sqlite3BtreeLeave(pBtree);
4212   }
4213   return rc;
4214 }
4215 
4216 /*
4217 ** Set the pBt->nPage field correctly, according to the current
4218 ** state of the database.  Assume pBt->pPage1 is valid.
4219 */
4220 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4221   int nPage = get4byte(&pPage1->aData[28]);
4222   testcase( nPage==0 );
4223   if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4224   testcase( pBt->nPage!=nPage );
4225   pBt->nPage = nPage;
4226 }
4227 
4228 /*
4229 ** Rollback the transaction in progress.
4230 **
4231 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4232 ** Only write cursors are tripped if writeOnly is true but all cursors are
4233 ** tripped if writeOnly is false.  Any attempt to use
4234 ** a tripped cursor will result in an error.
4235 **
4236 ** This will release the write lock on the database file.  If there
4237 ** are no active cursors, it also releases the read lock.
4238 */
4239 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4240   int rc;
4241   BtShared *pBt = p->pBt;
4242   MemPage *pPage1;
4243 
4244   assert( writeOnly==1 || writeOnly==0 );
4245   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4246   sqlite3BtreeEnter(p);
4247   if( tripCode==SQLITE_OK ){
4248     rc = tripCode = saveAllCursors(pBt, 0, 0);
4249     if( rc ) writeOnly = 0;
4250   }else{
4251     rc = SQLITE_OK;
4252   }
4253   if( tripCode ){
4254     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4255     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4256     if( rc2!=SQLITE_OK ) rc = rc2;
4257   }
4258   btreeIntegrity(p);
4259 
4260   if( p->inTrans==TRANS_WRITE ){
4261     int rc2;
4262 
4263     assert( TRANS_WRITE==pBt->inTransaction );
4264     rc2 = sqlite3PagerRollback(pBt->pPager);
4265     if( rc2!=SQLITE_OK ){
4266       rc = rc2;
4267     }
4268 
4269     /* The rollback may have destroyed the pPage1->aData value.  So
4270     ** call btreeGetPage() on page 1 again to make
4271     ** sure pPage1->aData is set correctly. */
4272     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4273       btreeSetNPage(pBt, pPage1);
4274       releasePageOne(pPage1);
4275     }
4276     assert( countValidCursors(pBt, 1)==0 );
4277     pBt->inTransaction = TRANS_READ;
4278     btreeClearHasContent(pBt);
4279   }
4280 
4281   btreeEndTransaction(p);
4282   sqlite3BtreeLeave(p);
4283   return rc;
4284 }
4285 
4286 /*
4287 ** Start a statement subtransaction. The subtransaction can be rolled
4288 ** back independently of the main transaction. You must start a transaction
4289 ** before starting a subtransaction. The subtransaction is ended automatically
4290 ** if the main transaction commits or rolls back.
4291 **
4292 ** Statement subtransactions are used around individual SQL statements
4293 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4294 ** error occurs within the statement, the effect of that one statement
4295 ** can be rolled back without having to rollback the entire transaction.
4296 **
4297 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4298 ** value passed as the second parameter is the total number of savepoints,
4299 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4300 ** are no active savepoints and no other statement-transactions open,
4301 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4302 ** using the sqlite3BtreeSavepoint() function.
4303 */
4304 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4305   int rc;
4306   BtShared *pBt = p->pBt;
4307   sqlite3BtreeEnter(p);
4308   assert( p->inTrans==TRANS_WRITE );
4309   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4310   assert( iStatement>0 );
4311   assert( iStatement>p->db->nSavepoint );
4312   assert( pBt->inTransaction==TRANS_WRITE );
4313   /* At the pager level, a statement transaction is a savepoint with
4314   ** an index greater than all savepoints created explicitly using
4315   ** SQL statements. It is illegal to open, release or rollback any
4316   ** such savepoints while the statement transaction savepoint is active.
4317   */
4318   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4319   sqlite3BtreeLeave(p);
4320   return rc;
4321 }
4322 
4323 /*
4324 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4325 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4326 ** savepoint identified by parameter iSavepoint, depending on the value
4327 ** of op.
4328 **
4329 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4330 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4331 ** contents of the entire transaction are rolled back. This is different
4332 ** from a normal transaction rollback, as no locks are released and the
4333 ** transaction remains open.
4334 */
4335 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4336   int rc = SQLITE_OK;
4337   if( p && p->inTrans==TRANS_WRITE ){
4338     BtShared *pBt = p->pBt;
4339     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4340     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4341     sqlite3BtreeEnter(p);
4342     if( op==SAVEPOINT_ROLLBACK ){
4343       rc = saveAllCursors(pBt, 0, 0);
4344     }
4345     if( rc==SQLITE_OK ){
4346       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4347     }
4348     if( rc==SQLITE_OK ){
4349       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4350         pBt->nPage = 0;
4351       }
4352       rc = newDatabase(pBt);
4353       btreeSetNPage(pBt, pBt->pPage1);
4354 
4355       /* pBt->nPage might be zero if the database was corrupt when
4356       ** the transaction was started. Otherwise, it must be at least 1.  */
4357       assert( CORRUPT_DB || pBt->nPage>0 );
4358     }
4359     sqlite3BtreeLeave(p);
4360   }
4361   return rc;
4362 }
4363 
4364 /*
4365 ** Create a new cursor for the BTree whose root is on the page
4366 ** iTable. If a read-only cursor is requested, it is assumed that
4367 ** the caller already has at least a read-only transaction open
4368 ** on the database already. If a write-cursor is requested, then
4369 ** the caller is assumed to have an open write transaction.
4370 **
4371 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4372 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4373 ** can be used for reading or for writing if other conditions for writing
4374 ** are also met.  These are the conditions that must be met in order
4375 ** for writing to be allowed:
4376 **
4377 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4378 **
4379 ** 2:  Other database connections that share the same pager cache
4380 **     but which are not in the READ_UNCOMMITTED state may not have
4381 **     cursors open with wrFlag==0 on the same table.  Otherwise
4382 **     the changes made by this write cursor would be visible to
4383 **     the read cursors in the other database connection.
4384 **
4385 ** 3:  The database must be writable (not on read-only media)
4386 **
4387 ** 4:  There must be an active transaction.
4388 **
4389 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4390 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4391 ** this cursor will only be used to seek to and delete entries of an index
4392 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4393 ** this implementation.  But in a hypothetical alternative storage engine
4394 ** in which index entries are automatically deleted when corresponding table
4395 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4396 ** operations on this cursor can be no-ops and all READ operations can
4397 ** return a null row (2-bytes: 0x01 0x00).
4398 **
4399 ** No checking is done to make sure that page iTable really is the
4400 ** root page of a b-tree.  If it is not, then the cursor acquired
4401 ** will not work correctly.
4402 **
4403 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4404 ** on pCur to initialize the memory space prior to invoking this routine.
4405 */
4406 static int btreeCursor(
4407   Btree *p,                              /* The btree */
4408   Pgno iTable,                           /* Root page of table to open */
4409   int wrFlag,                            /* 1 to write. 0 read-only */
4410   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4411   BtCursor *pCur                         /* Space for new cursor */
4412 ){
4413   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4414   BtCursor *pX;                          /* Looping over other all cursors */
4415 
4416   assert( sqlite3BtreeHoldsMutex(p) );
4417   assert( wrFlag==0
4418        || wrFlag==BTREE_WRCSR
4419        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4420   );
4421 
4422   /* The following assert statements verify that if this is a sharable
4423   ** b-tree database, the connection is holding the required table locks,
4424   ** and that no other connection has any open cursor that conflicts with
4425   ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
4426   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4427           || iTable<1 );
4428   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4429 
4430   /* Assert that the caller has opened the required transaction. */
4431   assert( p->inTrans>TRANS_NONE );
4432   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4433   assert( pBt->pPage1 && pBt->pPage1->aData );
4434   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4435 
4436   if( wrFlag ){
4437     allocateTempSpace(pBt);
4438     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4439   }
4440   if( iTable<=1 ){
4441     if( iTable<1 ){
4442       return SQLITE_CORRUPT_BKPT;
4443     }else if( btreePagecount(pBt)==0 ){
4444       assert( wrFlag==0 );
4445       iTable = 0;
4446     }
4447   }
4448 
4449   /* Now that no other errors can occur, finish filling in the BtCursor
4450   ** variables and link the cursor into the BtShared list.  */
4451   pCur->pgnoRoot = iTable;
4452   pCur->iPage = -1;
4453   pCur->pKeyInfo = pKeyInfo;
4454   pCur->pBtree = p;
4455   pCur->pBt = pBt;
4456   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4457   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4458   /* If there are two or more cursors on the same btree, then all such
4459   ** cursors *must* have the BTCF_Multiple flag set. */
4460   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4461     if( pX->pgnoRoot==iTable ){
4462       pX->curFlags |= BTCF_Multiple;
4463       pCur->curFlags |= BTCF_Multiple;
4464     }
4465   }
4466   pCur->pNext = pBt->pCursor;
4467   pBt->pCursor = pCur;
4468   pCur->eState = CURSOR_INVALID;
4469   return SQLITE_OK;
4470 }
4471 static int btreeCursorWithLock(
4472   Btree *p,                              /* The btree */
4473   Pgno iTable,                           /* Root page of table to open */
4474   int wrFlag,                            /* 1 to write. 0 read-only */
4475   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4476   BtCursor *pCur                         /* Space for new cursor */
4477 ){
4478   int rc;
4479   sqlite3BtreeEnter(p);
4480   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4481   sqlite3BtreeLeave(p);
4482   return rc;
4483 }
4484 int sqlite3BtreeCursor(
4485   Btree *p,                                   /* The btree */
4486   Pgno iTable,                                /* Root page of table to open */
4487   int wrFlag,                                 /* 1 to write. 0 read-only */
4488   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4489   BtCursor *pCur                              /* Write new cursor here */
4490 ){
4491   if( p->sharable ){
4492     return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4493   }else{
4494     return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4495   }
4496 }
4497 
4498 /*
4499 ** Return the size of a BtCursor object in bytes.
4500 **
4501 ** This interfaces is needed so that users of cursors can preallocate
4502 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4503 ** to users so they cannot do the sizeof() themselves - they must call
4504 ** this routine.
4505 */
4506 int sqlite3BtreeCursorSize(void){
4507   return ROUND8(sizeof(BtCursor));
4508 }
4509 
4510 /*
4511 ** Initialize memory that will be converted into a BtCursor object.
4512 **
4513 ** The simple approach here would be to memset() the entire object
4514 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4515 ** do not need to be zeroed and they are large, so we can save a lot
4516 ** of run-time by skipping the initialization of those elements.
4517 */
4518 void sqlite3BtreeCursorZero(BtCursor *p){
4519   memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4520 }
4521 
4522 /*
4523 ** Close a cursor.  The read lock on the database file is released
4524 ** when the last cursor is closed.
4525 */
4526 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4527   Btree *pBtree = pCur->pBtree;
4528   if( pBtree ){
4529     BtShared *pBt = pCur->pBt;
4530     sqlite3BtreeEnter(pBtree);
4531     assert( pBt->pCursor!=0 );
4532     if( pBt->pCursor==pCur ){
4533       pBt->pCursor = pCur->pNext;
4534     }else{
4535       BtCursor *pPrev = pBt->pCursor;
4536       do{
4537         if( pPrev->pNext==pCur ){
4538           pPrev->pNext = pCur->pNext;
4539           break;
4540         }
4541         pPrev = pPrev->pNext;
4542       }while( ALWAYS(pPrev) );
4543     }
4544     btreeReleaseAllCursorPages(pCur);
4545     unlockBtreeIfUnused(pBt);
4546     sqlite3_free(pCur->aOverflow);
4547     sqlite3_free(pCur->pKey);
4548     if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4549       /* Since the BtShared is not sharable, there is no need to
4550       ** worry about the missing sqlite3BtreeLeave() call here.  */
4551       assert( pBtree->sharable==0 );
4552       sqlite3BtreeClose(pBtree);
4553     }else{
4554       sqlite3BtreeLeave(pBtree);
4555     }
4556     pCur->pBtree = 0;
4557   }
4558   return SQLITE_OK;
4559 }
4560 
4561 /*
4562 ** Make sure the BtCursor* given in the argument has a valid
4563 ** BtCursor.info structure.  If it is not already valid, call
4564 ** btreeParseCell() to fill it in.
4565 **
4566 ** BtCursor.info is a cache of the information in the current cell.
4567 ** Using this cache reduces the number of calls to btreeParseCell().
4568 */
4569 #ifndef NDEBUG
4570   static int cellInfoEqual(CellInfo *a, CellInfo *b){
4571     if( a->nKey!=b->nKey ) return 0;
4572     if( a->pPayload!=b->pPayload ) return 0;
4573     if( a->nPayload!=b->nPayload ) return 0;
4574     if( a->nLocal!=b->nLocal ) return 0;
4575     if( a->nSize!=b->nSize ) return 0;
4576     return 1;
4577   }
4578   static void assertCellInfo(BtCursor *pCur){
4579     CellInfo info;
4580     memset(&info, 0, sizeof(info));
4581     btreeParseCell(pCur->pPage, pCur->ix, &info);
4582     assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4583   }
4584 #else
4585   #define assertCellInfo(x)
4586 #endif
4587 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4588   if( pCur->info.nSize==0 ){
4589     pCur->curFlags |= BTCF_ValidNKey;
4590     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4591   }else{
4592     assertCellInfo(pCur);
4593   }
4594 }
4595 
4596 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4597 /*
4598 ** Return true if the given BtCursor is valid.  A valid cursor is one
4599 ** that is currently pointing to a row in a (non-empty) table.
4600 ** This is a verification routine is used only within assert() statements.
4601 */
4602 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4603   return pCur && pCur->eState==CURSOR_VALID;
4604 }
4605 #endif /* NDEBUG */
4606 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4607   assert( pCur!=0 );
4608   return pCur->eState==CURSOR_VALID;
4609 }
4610 
4611 /*
4612 ** Return the value of the integer key or "rowid" for a table btree.
4613 ** This routine is only valid for a cursor that is pointing into a
4614 ** ordinary table btree.  If the cursor points to an index btree or
4615 ** is invalid, the result of this routine is undefined.
4616 */
4617 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4618   assert( cursorHoldsMutex(pCur) );
4619   assert( pCur->eState==CURSOR_VALID );
4620   assert( pCur->curIntKey );
4621   getCellInfo(pCur);
4622   return pCur->info.nKey;
4623 }
4624 
4625 /*
4626 ** Pin or unpin a cursor.
4627 */
4628 void sqlite3BtreeCursorPin(BtCursor *pCur){
4629   assert( (pCur->curFlags & BTCF_Pinned)==0 );
4630   pCur->curFlags |= BTCF_Pinned;
4631 }
4632 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4633   assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4634   pCur->curFlags &= ~BTCF_Pinned;
4635 }
4636 
4637 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4638 /*
4639 ** Return the offset into the database file for the start of the
4640 ** payload to which the cursor is pointing.
4641 */
4642 i64 sqlite3BtreeOffset(BtCursor *pCur){
4643   assert( cursorHoldsMutex(pCur) );
4644   assert( pCur->eState==CURSOR_VALID );
4645   getCellInfo(pCur);
4646   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4647          (i64)(pCur->info.pPayload - pCur->pPage->aData);
4648 }
4649 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4650 
4651 /*
4652 ** Return the number of bytes of payload for the entry that pCur is
4653 ** currently pointing to.  For table btrees, this will be the amount
4654 ** of data.  For index btrees, this will be the size of the key.
4655 **
4656 ** The caller must guarantee that the cursor is pointing to a non-NULL
4657 ** valid entry.  In other words, the calling procedure must guarantee
4658 ** that the cursor has Cursor.eState==CURSOR_VALID.
4659 */
4660 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4661   assert( cursorHoldsMutex(pCur) );
4662   assert( pCur->eState==CURSOR_VALID );
4663   getCellInfo(pCur);
4664   return pCur->info.nPayload;
4665 }
4666 
4667 /*
4668 ** Return an upper bound on the size of any record for the table
4669 ** that the cursor is pointing into.
4670 **
4671 ** This is an optimization.  Everything will still work if this
4672 ** routine always returns 2147483647 (which is the largest record
4673 ** that SQLite can handle) or more.  But returning a smaller value might
4674 ** prevent large memory allocations when trying to interpret a
4675 ** corrupt datrabase.
4676 **
4677 ** The current implementation merely returns the size of the underlying
4678 ** database file.
4679 */
4680 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4681   assert( cursorHoldsMutex(pCur) );
4682   assert( pCur->eState==CURSOR_VALID );
4683   return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4684 }
4685 
4686 /*
4687 ** Given the page number of an overflow page in the database (parameter
4688 ** ovfl), this function finds the page number of the next page in the
4689 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4690 ** pointer-map data instead of reading the content of page ovfl to do so.
4691 **
4692 ** If an error occurs an SQLite error code is returned. Otherwise:
4693 **
4694 ** The page number of the next overflow page in the linked list is
4695 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4696 ** list, *pPgnoNext is set to zero.
4697 **
4698 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4699 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4700 ** reference. It is the responsibility of the caller to call releasePage()
4701 ** on *ppPage to free the reference. In no reference was obtained (because
4702 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4703 ** *ppPage is set to zero.
4704 */
4705 static int getOverflowPage(
4706   BtShared *pBt,               /* The database file */
4707   Pgno ovfl,                   /* Current overflow page number */
4708   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4709   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4710 ){
4711   Pgno next = 0;
4712   MemPage *pPage = 0;
4713   int rc = SQLITE_OK;
4714 
4715   assert( sqlite3_mutex_held(pBt->mutex) );
4716   assert(pPgnoNext);
4717 
4718 #ifndef SQLITE_OMIT_AUTOVACUUM
4719   /* Try to find the next page in the overflow list using the
4720   ** autovacuum pointer-map pages. Guess that the next page in
4721   ** the overflow list is page number (ovfl+1). If that guess turns
4722   ** out to be wrong, fall back to loading the data of page
4723   ** number ovfl to determine the next page number.
4724   */
4725   if( pBt->autoVacuum ){
4726     Pgno pgno;
4727     Pgno iGuess = ovfl+1;
4728     u8 eType;
4729 
4730     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4731       iGuess++;
4732     }
4733 
4734     if( iGuess<=btreePagecount(pBt) ){
4735       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4736       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4737         next = iGuess;
4738         rc = SQLITE_DONE;
4739       }
4740     }
4741   }
4742 #endif
4743 
4744   assert( next==0 || rc==SQLITE_DONE );
4745   if( rc==SQLITE_OK ){
4746     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4747     assert( rc==SQLITE_OK || pPage==0 );
4748     if( rc==SQLITE_OK ){
4749       next = get4byte(pPage->aData);
4750     }
4751   }
4752 
4753   *pPgnoNext = next;
4754   if( ppPage ){
4755     *ppPage = pPage;
4756   }else{
4757     releasePage(pPage);
4758   }
4759   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4760 }
4761 
4762 /*
4763 ** Copy data from a buffer to a page, or from a page to a buffer.
4764 **
4765 ** pPayload is a pointer to data stored on database page pDbPage.
4766 ** If argument eOp is false, then nByte bytes of data are copied
4767 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4768 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4769 ** of data are copied from the buffer pBuf to pPayload.
4770 **
4771 ** SQLITE_OK is returned on success, otherwise an error code.
4772 */
4773 static int copyPayload(
4774   void *pPayload,           /* Pointer to page data */
4775   void *pBuf,               /* Pointer to buffer */
4776   int nByte,                /* Number of bytes to copy */
4777   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4778   DbPage *pDbPage           /* Page containing pPayload */
4779 ){
4780   if( eOp ){
4781     /* Copy data from buffer to page (a write operation) */
4782     int rc = sqlite3PagerWrite(pDbPage);
4783     if( rc!=SQLITE_OK ){
4784       return rc;
4785     }
4786     memcpy(pPayload, pBuf, nByte);
4787   }else{
4788     /* Copy data from page to buffer (a read operation) */
4789     memcpy(pBuf, pPayload, nByte);
4790   }
4791   return SQLITE_OK;
4792 }
4793 
4794 /*
4795 ** This function is used to read or overwrite payload information
4796 ** for the entry that the pCur cursor is pointing to. The eOp
4797 ** argument is interpreted as follows:
4798 **
4799 **   0: The operation is a read. Populate the overflow cache.
4800 **   1: The operation is a write. Populate the overflow cache.
4801 **
4802 ** A total of "amt" bytes are read or written beginning at "offset".
4803 ** Data is read to or from the buffer pBuf.
4804 **
4805 ** The content being read or written might appear on the main page
4806 ** or be scattered out on multiple overflow pages.
4807 **
4808 ** If the current cursor entry uses one or more overflow pages
4809 ** this function may allocate space for and lazily populate
4810 ** the overflow page-list cache array (BtCursor.aOverflow).
4811 ** Subsequent calls use this cache to make seeking to the supplied offset
4812 ** more efficient.
4813 **
4814 ** Once an overflow page-list cache has been allocated, it must be
4815 ** invalidated if some other cursor writes to the same table, or if
4816 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4817 ** mode, the following events may invalidate an overflow page-list cache.
4818 **
4819 **   * An incremental vacuum,
4820 **   * A commit in auto_vacuum="full" mode,
4821 **   * Creating a table (may require moving an overflow page).
4822 */
4823 static int accessPayload(
4824   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4825   u32 offset,          /* Begin reading this far into payload */
4826   u32 amt,             /* Read this many bytes */
4827   unsigned char *pBuf, /* Write the bytes into this buffer */
4828   int eOp              /* zero to read. non-zero to write. */
4829 ){
4830   unsigned char *aPayload;
4831   int rc = SQLITE_OK;
4832   int iIdx = 0;
4833   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
4834   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4835 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4836   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4837 #endif
4838 
4839   assert( pPage );
4840   assert( eOp==0 || eOp==1 );
4841   assert( pCur->eState==CURSOR_VALID );
4842   assert( pCur->ix<pPage->nCell );
4843   assert( cursorHoldsMutex(pCur) );
4844 
4845   getCellInfo(pCur);
4846   aPayload = pCur->info.pPayload;
4847   assert( offset+amt <= pCur->info.nPayload );
4848 
4849   assert( aPayload > pPage->aData );
4850   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4851     /* Trying to read or write past the end of the data is an error.  The
4852     ** conditional above is really:
4853     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4854     ** but is recast into its current form to avoid integer overflow problems
4855     */
4856     return SQLITE_CORRUPT_PAGE(pPage);
4857   }
4858 
4859   /* Check if data must be read/written to/from the btree page itself. */
4860   if( offset<pCur->info.nLocal ){
4861     int a = amt;
4862     if( a+offset>pCur->info.nLocal ){
4863       a = pCur->info.nLocal - offset;
4864     }
4865     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4866     offset = 0;
4867     pBuf += a;
4868     amt -= a;
4869   }else{
4870     offset -= pCur->info.nLocal;
4871   }
4872 
4873 
4874   if( rc==SQLITE_OK && amt>0 ){
4875     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4876     Pgno nextPage;
4877 
4878     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4879 
4880     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4881     **
4882     ** The aOverflow[] array is sized at one entry for each overflow page
4883     ** in the overflow chain. The page number of the first overflow page is
4884     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4885     ** means "not yet known" (the cache is lazily populated).
4886     */
4887     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4888       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4889       if( pCur->aOverflow==0
4890        || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4891       ){
4892         Pgno *aNew = (Pgno*)sqlite3Realloc(
4893             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4894         );
4895         if( aNew==0 ){
4896           return SQLITE_NOMEM_BKPT;
4897         }else{
4898           pCur->aOverflow = aNew;
4899         }
4900       }
4901       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4902       pCur->curFlags |= BTCF_ValidOvfl;
4903     }else{
4904       /* If the overflow page-list cache has been allocated and the
4905       ** entry for the first required overflow page is valid, skip
4906       ** directly to it.
4907       */
4908       if( pCur->aOverflow[offset/ovflSize] ){
4909         iIdx = (offset/ovflSize);
4910         nextPage = pCur->aOverflow[iIdx];
4911         offset = (offset%ovflSize);
4912       }
4913     }
4914 
4915     assert( rc==SQLITE_OK && amt>0 );
4916     while( nextPage ){
4917       /* If required, populate the overflow page-list cache. */
4918       if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4919       assert( pCur->aOverflow[iIdx]==0
4920               || pCur->aOverflow[iIdx]==nextPage
4921               || CORRUPT_DB );
4922       pCur->aOverflow[iIdx] = nextPage;
4923 
4924       if( offset>=ovflSize ){
4925         /* The only reason to read this page is to obtain the page
4926         ** number for the next page in the overflow chain. The page
4927         ** data is not required. So first try to lookup the overflow
4928         ** page-list cache, if any, then fall back to the getOverflowPage()
4929         ** function.
4930         */
4931         assert( pCur->curFlags & BTCF_ValidOvfl );
4932         assert( pCur->pBtree->db==pBt->db );
4933         if( pCur->aOverflow[iIdx+1] ){
4934           nextPage = pCur->aOverflow[iIdx+1];
4935         }else{
4936           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4937         }
4938         offset -= ovflSize;
4939       }else{
4940         /* Need to read this page properly. It contains some of the
4941         ** range of data that is being read (eOp==0) or written (eOp!=0).
4942         */
4943         int a = amt;
4944         if( a + offset > ovflSize ){
4945           a = ovflSize - offset;
4946         }
4947 
4948 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4949         /* If all the following are true:
4950         **
4951         **   1) this is a read operation, and
4952         **   2) data is required from the start of this overflow page, and
4953         **   3) there are no dirty pages in the page-cache
4954         **   4) the database is file-backed, and
4955         **   5) the page is not in the WAL file
4956         **   6) at least 4 bytes have already been read into the output buffer
4957         **
4958         ** then data can be read directly from the database file into the
4959         ** output buffer, bypassing the page-cache altogether. This speeds
4960         ** up loading large records that span many overflow pages.
4961         */
4962         if( eOp==0                                             /* (1) */
4963          && offset==0                                          /* (2) */
4964          && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
4965          && &pBuf[-4]>=pBufStart                               /* (6) */
4966         ){
4967           sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4968           u8 aSave[4];
4969           u8 *aWrite = &pBuf[-4];
4970           assert( aWrite>=pBufStart );                         /* due to (6) */
4971           memcpy(aSave, aWrite, 4);
4972           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4973           if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
4974           nextPage = get4byte(aWrite);
4975           memcpy(aWrite, aSave, 4);
4976         }else
4977 #endif
4978 
4979         {
4980           DbPage *pDbPage;
4981           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4982               (eOp==0 ? PAGER_GET_READONLY : 0)
4983           );
4984           if( rc==SQLITE_OK ){
4985             aPayload = sqlite3PagerGetData(pDbPage);
4986             nextPage = get4byte(aPayload);
4987             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4988             sqlite3PagerUnref(pDbPage);
4989             offset = 0;
4990           }
4991         }
4992         amt -= a;
4993         if( amt==0 ) return rc;
4994         pBuf += a;
4995       }
4996       if( rc ) break;
4997       iIdx++;
4998     }
4999   }
5000 
5001   if( rc==SQLITE_OK && amt>0 ){
5002     /* Overflow chain ends prematurely */
5003     return SQLITE_CORRUPT_PAGE(pPage);
5004   }
5005   return rc;
5006 }
5007 
5008 /*
5009 ** Read part of the payload for the row at which that cursor pCur is currently
5010 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
5011 ** begins at "offset".
5012 **
5013 ** pCur can be pointing to either a table or an index b-tree.
5014 ** If pointing to a table btree, then the content section is read.  If
5015 ** pCur is pointing to an index b-tree then the key section is read.
5016 **
5017 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5018 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
5019 ** cursor might be invalid or might need to be restored before being read.
5020 **
5021 ** Return SQLITE_OK on success or an error code if anything goes
5022 ** wrong.  An error is returned if "offset+amt" is larger than
5023 ** the available payload.
5024 */
5025 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5026   assert( cursorHoldsMutex(pCur) );
5027   assert( pCur->eState==CURSOR_VALID );
5028   assert( pCur->iPage>=0 && pCur->pPage );
5029   assert( pCur->ix<pCur->pPage->nCell );
5030   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5031 }
5032 
5033 /*
5034 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5035 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
5036 ** interface.
5037 */
5038 #ifndef SQLITE_OMIT_INCRBLOB
5039 static SQLITE_NOINLINE int accessPayloadChecked(
5040   BtCursor *pCur,
5041   u32 offset,
5042   u32 amt,
5043   void *pBuf
5044 ){
5045   int rc;
5046   if ( pCur->eState==CURSOR_INVALID ){
5047     return SQLITE_ABORT;
5048   }
5049   assert( cursorOwnsBtShared(pCur) );
5050   rc = btreeRestoreCursorPosition(pCur);
5051   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5052 }
5053 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5054   if( pCur->eState==CURSOR_VALID ){
5055     assert( cursorOwnsBtShared(pCur) );
5056     return accessPayload(pCur, offset, amt, pBuf, 0);
5057   }else{
5058     return accessPayloadChecked(pCur, offset, amt, pBuf);
5059   }
5060 }
5061 #endif /* SQLITE_OMIT_INCRBLOB */
5062 
5063 /*
5064 ** Return a pointer to payload information from the entry that the
5065 ** pCur cursor is pointing to.  The pointer is to the beginning of
5066 ** the key if index btrees (pPage->intKey==0) and is the data for
5067 ** table btrees (pPage->intKey==1). The number of bytes of available
5068 ** key/data is written into *pAmt.  If *pAmt==0, then the value
5069 ** returned will not be a valid pointer.
5070 **
5071 ** This routine is an optimization.  It is common for the entire key
5072 ** and data to fit on the local page and for there to be no overflow
5073 ** pages.  When that is so, this routine can be used to access the
5074 ** key and data without making a copy.  If the key and/or data spills
5075 ** onto overflow pages, then accessPayload() must be used to reassemble
5076 ** the key/data and copy it into a preallocated buffer.
5077 **
5078 ** The pointer returned by this routine looks directly into the cached
5079 ** page of the database.  The data might change or move the next time
5080 ** any btree routine is called.
5081 */
5082 static const void *fetchPayload(
5083   BtCursor *pCur,      /* Cursor pointing to entry to read from */
5084   u32 *pAmt            /* Write the number of available bytes here */
5085 ){
5086   int amt;
5087   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5088   assert( pCur->eState==CURSOR_VALID );
5089   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5090   assert( cursorOwnsBtShared(pCur) );
5091   assert( pCur->ix<pCur->pPage->nCell );
5092   assert( pCur->info.nSize>0 );
5093   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5094   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5095   amt = pCur->info.nLocal;
5096   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5097     /* There is too little space on the page for the expected amount
5098     ** of local content. Database must be corrupt. */
5099     assert( CORRUPT_DB );
5100     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5101   }
5102   *pAmt = (u32)amt;
5103   return (void*)pCur->info.pPayload;
5104 }
5105 
5106 
5107 /*
5108 ** For the entry that cursor pCur is point to, return as
5109 ** many bytes of the key or data as are available on the local
5110 ** b-tree page.  Write the number of available bytes into *pAmt.
5111 **
5112 ** The pointer returned is ephemeral.  The key/data may move
5113 ** or be destroyed on the next call to any Btree routine,
5114 ** including calls from other threads against the same cache.
5115 ** Hence, a mutex on the BtShared should be held prior to calling
5116 ** this routine.
5117 **
5118 ** These routines is used to get quick access to key and data
5119 ** in the common case where no overflow pages are used.
5120 */
5121 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5122   return fetchPayload(pCur, pAmt);
5123 }
5124 
5125 
5126 /*
5127 ** Move the cursor down to a new child page.  The newPgno argument is the
5128 ** page number of the child page to move to.
5129 **
5130 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5131 ** the new child page does not match the flags field of the parent (i.e.
5132 ** if an intkey page appears to be the parent of a non-intkey page, or
5133 ** vice-versa).
5134 */
5135 static int moveToChild(BtCursor *pCur, u32 newPgno){
5136   BtShared *pBt = pCur->pBt;
5137 
5138   assert( cursorOwnsBtShared(pCur) );
5139   assert( pCur->eState==CURSOR_VALID );
5140   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5141   assert( pCur->iPage>=0 );
5142   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5143     return SQLITE_CORRUPT_BKPT;
5144   }
5145   pCur->info.nSize = 0;
5146   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5147   pCur->aiIdx[pCur->iPage] = pCur->ix;
5148   pCur->apPage[pCur->iPage] = pCur->pPage;
5149   pCur->ix = 0;
5150   pCur->iPage++;
5151   return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5152 }
5153 
5154 #ifdef SQLITE_DEBUG
5155 /*
5156 ** Page pParent is an internal (non-leaf) tree page. This function
5157 ** asserts that page number iChild is the left-child if the iIdx'th
5158 ** cell in page pParent. Or, if iIdx is equal to the total number of
5159 ** cells in pParent, that page number iChild is the right-child of
5160 ** the page.
5161 */
5162 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5163   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
5164                             ** in a corrupt database */
5165   assert( iIdx<=pParent->nCell );
5166   if( iIdx==pParent->nCell ){
5167     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5168   }else{
5169     assert( get4byte(findCell(pParent, iIdx))==iChild );
5170   }
5171 }
5172 #else
5173 #  define assertParentIndex(x,y,z)
5174 #endif
5175 
5176 /*
5177 ** Move the cursor up to the parent page.
5178 **
5179 ** pCur->idx is set to the cell index that contains the pointer
5180 ** to the page we are coming from.  If we are coming from the
5181 ** right-most child page then pCur->idx is set to one more than
5182 ** the largest cell index.
5183 */
5184 static void moveToParent(BtCursor *pCur){
5185   MemPage *pLeaf;
5186   assert( cursorOwnsBtShared(pCur) );
5187   assert( pCur->eState==CURSOR_VALID );
5188   assert( pCur->iPage>0 );
5189   assert( pCur->pPage );
5190   assertParentIndex(
5191     pCur->apPage[pCur->iPage-1],
5192     pCur->aiIdx[pCur->iPage-1],
5193     pCur->pPage->pgno
5194   );
5195   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5196   pCur->info.nSize = 0;
5197   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5198   pCur->ix = pCur->aiIdx[pCur->iPage-1];
5199   pLeaf = pCur->pPage;
5200   pCur->pPage = pCur->apPage[--pCur->iPage];
5201   releasePageNotNull(pLeaf);
5202 }
5203 
5204 /*
5205 ** Move the cursor to point to the root page of its b-tree structure.
5206 **
5207 ** If the table has a virtual root page, then the cursor is moved to point
5208 ** to the virtual root page instead of the actual root page. A table has a
5209 ** virtual root page when the actual root page contains no cells and a
5210 ** single child page. This can only happen with the table rooted at page 1.
5211 **
5212 ** If the b-tree structure is empty, the cursor state is set to
5213 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5214 ** the cursor is set to point to the first cell located on the root
5215 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5216 **
5217 ** If this function returns successfully, it may be assumed that the
5218 ** page-header flags indicate that the [virtual] root-page is the expected
5219 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5220 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5221 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5222 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5223 ** b-tree).
5224 */
5225 static int moveToRoot(BtCursor *pCur){
5226   MemPage *pRoot;
5227   int rc = SQLITE_OK;
5228 
5229   assert( cursorOwnsBtShared(pCur) );
5230   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5231   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
5232   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
5233   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5234   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5235 
5236   if( pCur->iPage>=0 ){
5237     if( pCur->iPage ){
5238       releasePageNotNull(pCur->pPage);
5239       while( --pCur->iPage ){
5240         releasePageNotNull(pCur->apPage[pCur->iPage]);
5241       }
5242       pCur->pPage = pCur->apPage[0];
5243       goto skip_init;
5244     }
5245   }else if( pCur->pgnoRoot==0 ){
5246     pCur->eState = CURSOR_INVALID;
5247     return SQLITE_EMPTY;
5248   }else{
5249     assert( pCur->iPage==(-1) );
5250     if( pCur->eState>=CURSOR_REQUIRESEEK ){
5251       if( pCur->eState==CURSOR_FAULT ){
5252         assert( pCur->skipNext!=SQLITE_OK );
5253         return pCur->skipNext;
5254       }
5255       sqlite3BtreeClearCursor(pCur);
5256     }
5257     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5258                         0, pCur->curPagerFlags);
5259     if( rc!=SQLITE_OK ){
5260       pCur->eState = CURSOR_INVALID;
5261       return rc;
5262     }
5263     pCur->iPage = 0;
5264     pCur->curIntKey = pCur->pPage->intKey;
5265   }
5266   pRoot = pCur->pPage;
5267   assert( pRoot->pgno==pCur->pgnoRoot );
5268 
5269   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5270   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5271   ** NULL, the caller expects a table b-tree. If this is not the case,
5272   ** return an SQLITE_CORRUPT error.
5273   **
5274   ** Earlier versions of SQLite assumed that this test could not fail
5275   ** if the root page was already loaded when this function was called (i.e.
5276   ** if pCur->iPage>=0). But this is not so if the database is corrupted
5277   ** in such a way that page pRoot is linked into a second b-tree table
5278   ** (or the freelist).  */
5279   assert( pRoot->intKey==1 || pRoot->intKey==0 );
5280   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5281     return SQLITE_CORRUPT_PAGE(pCur->pPage);
5282   }
5283 
5284 skip_init:
5285   pCur->ix = 0;
5286   pCur->info.nSize = 0;
5287   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5288 
5289   pRoot = pCur->pPage;
5290   if( pRoot->nCell>0 ){
5291     pCur->eState = CURSOR_VALID;
5292   }else if( !pRoot->leaf ){
5293     Pgno subpage;
5294     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5295     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5296     pCur->eState = CURSOR_VALID;
5297     rc = moveToChild(pCur, subpage);
5298   }else{
5299     pCur->eState = CURSOR_INVALID;
5300     rc = SQLITE_EMPTY;
5301   }
5302   return rc;
5303 }
5304 
5305 /*
5306 ** Move the cursor down to the left-most leaf entry beneath the
5307 ** entry to which it is currently pointing.
5308 **
5309 ** The left-most leaf is the one with the smallest key - the first
5310 ** in ascending order.
5311 */
5312 static int moveToLeftmost(BtCursor *pCur){
5313   Pgno pgno;
5314   int rc = SQLITE_OK;
5315   MemPage *pPage;
5316 
5317   assert( cursorOwnsBtShared(pCur) );
5318   assert( pCur->eState==CURSOR_VALID );
5319   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5320     assert( pCur->ix<pPage->nCell );
5321     pgno = get4byte(findCell(pPage, pCur->ix));
5322     rc = moveToChild(pCur, pgno);
5323   }
5324   return rc;
5325 }
5326 
5327 /*
5328 ** Move the cursor down to the right-most leaf entry beneath the
5329 ** page to which it is currently pointing.  Notice the difference
5330 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5331 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5332 ** finds the right-most entry beneath the *page*.
5333 **
5334 ** The right-most entry is the one with the largest key - the last
5335 ** key in ascending order.
5336 */
5337 static int moveToRightmost(BtCursor *pCur){
5338   Pgno pgno;
5339   int rc = SQLITE_OK;
5340   MemPage *pPage = 0;
5341 
5342   assert( cursorOwnsBtShared(pCur) );
5343   assert( pCur->eState==CURSOR_VALID );
5344   while( !(pPage = pCur->pPage)->leaf ){
5345     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5346     pCur->ix = pPage->nCell;
5347     rc = moveToChild(pCur, pgno);
5348     if( rc ) return rc;
5349   }
5350   pCur->ix = pPage->nCell-1;
5351   assert( pCur->info.nSize==0 );
5352   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5353   return SQLITE_OK;
5354 }
5355 
5356 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5357 ** on success.  Set *pRes to 0 if the cursor actually points to something
5358 ** or set *pRes to 1 if the table is empty.
5359 */
5360 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5361   int rc;
5362 
5363   assert( cursorOwnsBtShared(pCur) );
5364   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5365   rc = moveToRoot(pCur);
5366   if( rc==SQLITE_OK ){
5367     assert( pCur->pPage->nCell>0 );
5368     *pRes = 0;
5369     rc = moveToLeftmost(pCur);
5370   }else if( rc==SQLITE_EMPTY ){
5371     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5372     *pRes = 1;
5373     rc = SQLITE_OK;
5374   }
5375   return rc;
5376 }
5377 
5378 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5379 ** on success.  Set *pRes to 0 if the cursor actually points to something
5380 ** or set *pRes to 1 if the table is empty.
5381 */
5382 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5383   int rc;
5384 
5385   assert( cursorOwnsBtShared(pCur) );
5386   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5387 
5388   /* If the cursor already points to the last entry, this is a no-op. */
5389   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5390 #ifdef SQLITE_DEBUG
5391     /* This block serves to assert() that the cursor really does point
5392     ** to the last entry in the b-tree. */
5393     int ii;
5394     for(ii=0; ii<pCur->iPage; ii++){
5395       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5396     }
5397     assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5398     testcase( pCur->ix!=pCur->pPage->nCell-1 );
5399     /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5400     assert( pCur->pPage->leaf );
5401 #endif
5402     *pRes = 0;
5403     return SQLITE_OK;
5404   }
5405 
5406   rc = moveToRoot(pCur);
5407   if( rc==SQLITE_OK ){
5408     assert( pCur->eState==CURSOR_VALID );
5409     *pRes = 0;
5410     rc = moveToRightmost(pCur);
5411     if( rc==SQLITE_OK ){
5412       pCur->curFlags |= BTCF_AtLast;
5413     }else{
5414       pCur->curFlags &= ~BTCF_AtLast;
5415     }
5416   }else if( rc==SQLITE_EMPTY ){
5417     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5418     *pRes = 1;
5419     rc = SQLITE_OK;
5420   }
5421   return rc;
5422 }
5423 
5424 /* Move the cursor so that it points to an entry near the key
5425 ** specified by pIdxKey or intKey.   Return a success code.
5426 **
5427 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
5428 ** must be NULL.  For index tables, pIdxKey is used and intKey
5429 ** is ignored.
5430 **
5431 ** If an exact match is not found, then the cursor is always
5432 ** left pointing at a leaf page which would hold the entry if it
5433 ** were present.  The cursor might point to an entry that comes
5434 ** before or after the key.
5435 **
5436 ** An integer is written into *pRes which is the result of
5437 ** comparing the key with the entry to which the cursor is
5438 ** pointing.  The meaning of the integer written into
5439 ** *pRes is as follows:
5440 **
5441 **     *pRes<0      The cursor is left pointing at an entry that
5442 **                  is smaller than intKey/pIdxKey or if the table is empty
5443 **                  and the cursor is therefore left point to nothing.
5444 **
5445 **     *pRes==0     The cursor is left pointing at an entry that
5446 **                  exactly matches intKey/pIdxKey.
5447 **
5448 **     *pRes>0      The cursor is left pointing at an entry that
5449 **                  is larger than intKey/pIdxKey.
5450 **
5451 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5452 ** exists an entry in the table that exactly matches pIdxKey.
5453 */
5454 int sqlite3BtreeMovetoUnpacked(
5455   BtCursor *pCur,          /* The cursor to be moved */
5456   UnpackedRecord *pIdxKey, /* Unpacked index key */
5457   i64 intKey,              /* The table key */
5458   int biasRight,           /* If true, bias the search to the high end */
5459   int *pRes                /* Write search results here */
5460 ){
5461   int rc;
5462   RecordCompare xRecordCompare;
5463 
5464   assert( cursorOwnsBtShared(pCur) );
5465   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5466   assert( pRes );
5467   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5468   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5469 
5470   /* If the cursor is already positioned at the point we are trying
5471   ** to move to, then just return without doing any work */
5472   if( pIdxKey==0
5473    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5474   ){
5475     if( pCur->info.nKey==intKey ){
5476       *pRes = 0;
5477       return SQLITE_OK;
5478     }
5479     if( pCur->info.nKey<intKey ){
5480       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5481         *pRes = -1;
5482         return SQLITE_OK;
5483       }
5484       /* If the requested key is one more than the previous key, then
5485       ** try to get there using sqlite3BtreeNext() rather than a full
5486       ** binary search.  This is an optimization only.  The correct answer
5487       ** is still obtained without this case, only a little more slowely */
5488       if( pCur->info.nKey+1==intKey ){
5489         *pRes = 0;
5490         rc = sqlite3BtreeNext(pCur, 0);
5491         if( rc==SQLITE_OK ){
5492           getCellInfo(pCur);
5493           if( pCur->info.nKey==intKey ){
5494             return SQLITE_OK;
5495           }
5496         }else if( rc==SQLITE_DONE ){
5497           rc = SQLITE_OK;
5498         }else{
5499           return rc;
5500         }
5501       }
5502     }
5503   }
5504 
5505 #ifdef SQLITE_DEBUG
5506   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
5507 #endif
5508 
5509   if( pIdxKey ){
5510     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5511     pIdxKey->errCode = 0;
5512     assert( pIdxKey->default_rc==1
5513          || pIdxKey->default_rc==0
5514          || pIdxKey->default_rc==-1
5515     );
5516   }else{
5517     xRecordCompare = 0; /* All keys are integers */
5518   }
5519 
5520   rc = moveToRoot(pCur);
5521   if( rc ){
5522     if( rc==SQLITE_EMPTY ){
5523       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5524       *pRes = -1;
5525       return SQLITE_OK;
5526     }
5527     return rc;
5528   }
5529   assert( pCur->pPage );
5530   assert( pCur->pPage->isInit );
5531   assert( pCur->eState==CURSOR_VALID );
5532   assert( pCur->pPage->nCell > 0 );
5533   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5534   assert( pCur->curIntKey || pIdxKey );
5535   for(;;){
5536     int lwr, upr, idx, c;
5537     Pgno chldPg;
5538     MemPage *pPage = pCur->pPage;
5539     u8 *pCell;                          /* Pointer to current cell in pPage */
5540 
5541     /* pPage->nCell must be greater than zero. If this is the root-page
5542     ** the cursor would have been INVALID above and this for(;;) loop
5543     ** not run. If this is not the root-page, then the moveToChild() routine
5544     ** would have already detected db corruption. Similarly, pPage must
5545     ** be the right kind (index or table) of b-tree page. Otherwise
5546     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5547     assert( pPage->nCell>0 );
5548     assert( pPage->intKey==(pIdxKey==0) );
5549     lwr = 0;
5550     upr = pPage->nCell-1;
5551     assert( biasRight==0 || biasRight==1 );
5552     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5553     pCur->ix = (u16)idx;
5554     if( xRecordCompare==0 ){
5555       for(;;){
5556         i64 nCellKey;
5557         pCell = findCellPastPtr(pPage, idx);
5558         if( pPage->intKeyLeaf ){
5559           while( 0x80 <= *(pCell++) ){
5560             if( pCell>=pPage->aDataEnd ){
5561               return SQLITE_CORRUPT_PAGE(pPage);
5562             }
5563           }
5564         }
5565         getVarint(pCell, (u64*)&nCellKey);
5566         if( nCellKey<intKey ){
5567           lwr = idx+1;
5568           if( lwr>upr ){ c = -1; break; }
5569         }else if( nCellKey>intKey ){
5570           upr = idx-1;
5571           if( lwr>upr ){ c = +1; break; }
5572         }else{
5573           assert( nCellKey==intKey );
5574           pCur->ix = (u16)idx;
5575           if( !pPage->leaf ){
5576             lwr = idx;
5577             goto moveto_next_layer;
5578           }else{
5579             pCur->curFlags |= BTCF_ValidNKey;
5580             pCur->info.nKey = nCellKey;
5581             pCur->info.nSize = 0;
5582             *pRes = 0;
5583             return SQLITE_OK;
5584           }
5585         }
5586         assert( lwr+upr>=0 );
5587         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5588       }
5589     }else{
5590       for(;;){
5591         int nCell;  /* Size of the pCell cell in bytes */
5592         pCell = findCellPastPtr(pPage, idx);
5593 
5594         /* The maximum supported page-size is 65536 bytes. This means that
5595         ** the maximum number of record bytes stored on an index B-Tree
5596         ** page is less than 16384 bytes and may be stored as a 2-byte
5597         ** varint. This information is used to attempt to avoid parsing
5598         ** the entire cell by checking for the cases where the record is
5599         ** stored entirely within the b-tree page by inspecting the first
5600         ** 2 bytes of the cell.
5601         */
5602         nCell = pCell[0];
5603         if( nCell<=pPage->max1bytePayload ){
5604           /* This branch runs if the record-size field of the cell is a
5605           ** single byte varint and the record fits entirely on the main
5606           ** b-tree page.  */
5607           testcase( pCell+nCell+1==pPage->aDataEnd );
5608           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5609         }else if( !(pCell[1] & 0x80)
5610           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5611         ){
5612           /* The record-size field is a 2 byte varint and the record
5613           ** fits entirely on the main b-tree page.  */
5614           testcase( pCell+nCell+2==pPage->aDataEnd );
5615           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5616         }else{
5617           /* The record flows over onto one or more overflow pages. In
5618           ** this case the whole cell needs to be parsed, a buffer allocated
5619           ** and accessPayload() used to retrieve the record into the
5620           ** buffer before VdbeRecordCompare() can be called.
5621           **
5622           ** If the record is corrupt, the xRecordCompare routine may read
5623           ** up to two varints past the end of the buffer. An extra 18
5624           ** bytes of padding is allocated at the end of the buffer in
5625           ** case this happens.  */
5626           void *pCellKey;
5627           u8 * const pCellBody = pCell - pPage->childPtrSize;
5628           const int nOverrun = 18;  /* Size of the overrun padding */
5629           pPage->xParseCell(pPage, pCellBody, &pCur->info);
5630           nCell = (int)pCur->info.nKey;
5631           testcase( nCell<0 );   /* True if key size is 2^32 or more */
5632           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5633           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5634           testcase( nCell==2 );  /* Minimum legal index key size */
5635           if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5636             rc = SQLITE_CORRUPT_PAGE(pPage);
5637             goto moveto_finish;
5638           }
5639           pCellKey = sqlite3Malloc( nCell+nOverrun );
5640           if( pCellKey==0 ){
5641             rc = SQLITE_NOMEM_BKPT;
5642             goto moveto_finish;
5643           }
5644           pCur->ix = (u16)idx;
5645           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5646           memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5647           pCur->curFlags &= ~BTCF_ValidOvfl;
5648           if( rc ){
5649             sqlite3_free(pCellKey);
5650             goto moveto_finish;
5651           }
5652           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5653           sqlite3_free(pCellKey);
5654         }
5655         assert(
5656             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5657          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5658         );
5659         if( c<0 ){
5660           lwr = idx+1;
5661         }else if( c>0 ){
5662           upr = idx-1;
5663         }else{
5664           assert( c==0 );
5665           *pRes = 0;
5666           rc = SQLITE_OK;
5667           pCur->ix = (u16)idx;
5668           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5669           goto moveto_finish;
5670         }
5671         if( lwr>upr ) break;
5672         assert( lwr+upr>=0 );
5673         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5674       }
5675     }
5676     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5677     assert( pPage->isInit );
5678     if( pPage->leaf ){
5679       assert( pCur->ix<pCur->pPage->nCell );
5680       pCur->ix = (u16)idx;
5681       *pRes = c;
5682       rc = SQLITE_OK;
5683       goto moveto_finish;
5684     }
5685 moveto_next_layer:
5686     if( lwr>=pPage->nCell ){
5687       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5688     }else{
5689       chldPg = get4byte(findCell(pPage, lwr));
5690     }
5691     pCur->ix = (u16)lwr;
5692     rc = moveToChild(pCur, chldPg);
5693     if( rc ) break;
5694   }
5695 moveto_finish:
5696   pCur->info.nSize = 0;
5697   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5698   return rc;
5699 }
5700 
5701 
5702 /*
5703 ** Return TRUE if the cursor is not pointing at an entry of the table.
5704 **
5705 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5706 ** past the last entry in the table or sqlite3BtreePrev() moves past
5707 ** the first entry.  TRUE is also returned if the table is empty.
5708 */
5709 int sqlite3BtreeEof(BtCursor *pCur){
5710   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5711   ** have been deleted? This API will need to change to return an error code
5712   ** as well as the boolean result value.
5713   */
5714   return (CURSOR_VALID!=pCur->eState);
5715 }
5716 
5717 /*
5718 ** Return an estimate for the number of rows in the table that pCur is
5719 ** pointing to.  Return a negative number if no estimate is currently
5720 ** available.
5721 */
5722 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5723   i64 n;
5724   u8 i;
5725 
5726   assert( cursorOwnsBtShared(pCur) );
5727   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5728 
5729   /* Currently this interface is only called by the OP_IfSmaller
5730   ** opcode, and it that case the cursor will always be valid and
5731   ** will always point to a leaf node. */
5732   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5733   if( NEVER(pCur->pPage->leaf==0) ) return -1;
5734 
5735   n = pCur->pPage->nCell;
5736   for(i=0; i<pCur->iPage; i++){
5737     n *= pCur->apPage[i]->nCell;
5738   }
5739   return n;
5740 }
5741 
5742 /*
5743 ** Advance the cursor to the next entry in the database.
5744 ** Return value:
5745 **
5746 **    SQLITE_OK        success
5747 **    SQLITE_DONE      cursor is already pointing at the last element
5748 **    otherwise        some kind of error occurred
5749 **
5750 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
5751 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5752 ** to the next cell on the current page.  The (slower) btreeNext() helper
5753 ** routine is called when it is necessary to move to a different page or
5754 ** to restore the cursor.
5755 **
5756 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5757 ** cursor corresponds to an SQL index and this routine could have been
5758 ** skipped if the SQL index had been a unique index.  The F argument
5759 ** is a hint to the implement.  SQLite btree implementation does not use
5760 ** this hint, but COMDB2 does.
5761 */
5762 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5763   int rc;
5764   int idx;
5765   MemPage *pPage;
5766 
5767   assert( cursorOwnsBtShared(pCur) );
5768   if( pCur->eState!=CURSOR_VALID ){
5769     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5770     rc = restoreCursorPosition(pCur);
5771     if( rc!=SQLITE_OK ){
5772       return rc;
5773     }
5774     if( CURSOR_INVALID==pCur->eState ){
5775       return SQLITE_DONE;
5776     }
5777     if( pCur->eState==CURSOR_SKIPNEXT ){
5778       pCur->eState = CURSOR_VALID;
5779       if( pCur->skipNext>0 ) return SQLITE_OK;
5780     }
5781   }
5782 
5783   pPage = pCur->pPage;
5784   idx = ++pCur->ix;
5785   if( !pPage->isInit || sqlite3FaultSim(412) ){
5786     /* The only known way for this to happen is for there to be a
5787     ** recursive SQL function that does a DELETE operation as part of a
5788     ** SELECT which deletes content out from under an active cursor
5789     ** in a corrupt database file where the table being DELETE-ed from
5790     ** has pages in common with the table being queried.  See TH3
5791     ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5792     ** example. */
5793     return SQLITE_CORRUPT_BKPT;
5794   }
5795 
5796   /* If the database file is corrupt, it is possible for the value of idx
5797   ** to be invalid here. This can only occur if a second cursor modifies
5798   ** the page while cursor pCur is holding a reference to it. Which can
5799   ** only happen if the database is corrupt in such a way as to link the
5800   ** page into more than one b-tree structure.
5801   **
5802   ** Update 2019-12-23: appears to long longer be possible after the
5803   ** addition of anotherValidCursor() condition on balance_deeper().  */
5804   harmless( idx>pPage->nCell );
5805 
5806   if( idx>=pPage->nCell ){
5807     if( !pPage->leaf ){
5808       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5809       if( rc ) return rc;
5810       return moveToLeftmost(pCur);
5811     }
5812     do{
5813       if( pCur->iPage==0 ){
5814         pCur->eState = CURSOR_INVALID;
5815         return SQLITE_DONE;
5816       }
5817       moveToParent(pCur);
5818       pPage = pCur->pPage;
5819     }while( pCur->ix>=pPage->nCell );
5820     if( pPage->intKey ){
5821       return sqlite3BtreeNext(pCur, 0);
5822     }else{
5823       return SQLITE_OK;
5824     }
5825   }
5826   if( pPage->leaf ){
5827     return SQLITE_OK;
5828   }else{
5829     return moveToLeftmost(pCur);
5830   }
5831 }
5832 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5833   MemPage *pPage;
5834   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5835   assert( cursorOwnsBtShared(pCur) );
5836   assert( flags==0 || flags==1 );
5837   pCur->info.nSize = 0;
5838   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5839   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5840   pPage = pCur->pPage;
5841   if( (++pCur->ix)>=pPage->nCell ){
5842     pCur->ix--;
5843     return btreeNext(pCur);
5844   }
5845   if( pPage->leaf ){
5846     return SQLITE_OK;
5847   }else{
5848     return moveToLeftmost(pCur);
5849   }
5850 }
5851 
5852 /*
5853 ** Step the cursor to the back to the previous entry in the database.
5854 ** Return values:
5855 **
5856 **     SQLITE_OK     success
5857 **     SQLITE_DONE   the cursor is already on the first element of the table
5858 **     otherwise     some kind of error occurred
5859 **
5860 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
5861 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5862 ** to the previous cell on the current page.  The (slower) btreePrevious()
5863 ** helper routine is called when it is necessary to move to a different page
5864 ** or to restore the cursor.
5865 **
5866 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5867 ** the cursor corresponds to an SQL index and this routine could have been
5868 ** skipped if the SQL index had been a unique index.  The F argument is a
5869 ** hint to the implement.  The native SQLite btree implementation does not
5870 ** use this hint, but COMDB2 does.
5871 */
5872 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5873   int rc;
5874   MemPage *pPage;
5875 
5876   assert( cursorOwnsBtShared(pCur) );
5877   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5878   assert( pCur->info.nSize==0 );
5879   if( pCur->eState!=CURSOR_VALID ){
5880     rc = restoreCursorPosition(pCur);
5881     if( rc!=SQLITE_OK ){
5882       return rc;
5883     }
5884     if( CURSOR_INVALID==pCur->eState ){
5885       return SQLITE_DONE;
5886     }
5887     if( CURSOR_SKIPNEXT==pCur->eState ){
5888       pCur->eState = CURSOR_VALID;
5889       if( pCur->skipNext<0 ) return SQLITE_OK;
5890     }
5891   }
5892 
5893   pPage = pCur->pPage;
5894   assert( pPage->isInit );
5895   if( !pPage->leaf ){
5896     int idx = pCur->ix;
5897     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5898     if( rc ) return rc;
5899     rc = moveToRightmost(pCur);
5900   }else{
5901     while( pCur->ix==0 ){
5902       if( pCur->iPage==0 ){
5903         pCur->eState = CURSOR_INVALID;
5904         return SQLITE_DONE;
5905       }
5906       moveToParent(pCur);
5907     }
5908     assert( pCur->info.nSize==0 );
5909     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5910 
5911     pCur->ix--;
5912     pPage = pCur->pPage;
5913     if( pPage->intKey && !pPage->leaf ){
5914       rc = sqlite3BtreePrevious(pCur, 0);
5915     }else{
5916       rc = SQLITE_OK;
5917     }
5918   }
5919   return rc;
5920 }
5921 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5922   assert( cursorOwnsBtShared(pCur) );
5923   assert( flags==0 || flags==1 );
5924   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5925   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5926   pCur->info.nSize = 0;
5927   if( pCur->eState!=CURSOR_VALID
5928    || pCur->ix==0
5929    || pCur->pPage->leaf==0
5930   ){
5931     return btreePrevious(pCur);
5932   }
5933   pCur->ix--;
5934   return SQLITE_OK;
5935 }
5936 
5937 /*
5938 ** Allocate a new page from the database file.
5939 **
5940 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
5941 ** has already been called on the new page.)  The new page has also
5942 ** been referenced and the calling routine is responsible for calling
5943 ** sqlite3PagerUnref() on the new page when it is done.
5944 **
5945 ** SQLITE_OK is returned on success.  Any other return value indicates
5946 ** an error.  *ppPage is set to NULL in the event of an error.
5947 **
5948 ** If the "nearby" parameter is not 0, then an effort is made to
5949 ** locate a page close to the page number "nearby".  This can be used in an
5950 ** attempt to keep related pages close to each other in the database file,
5951 ** which in turn can make database access faster.
5952 **
5953 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5954 ** anywhere on the free-list, then it is guaranteed to be returned.  If
5955 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5956 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
5957 ** are no restrictions on which page is returned.
5958 */
5959 static int allocateBtreePage(
5960   BtShared *pBt,         /* The btree */
5961   MemPage **ppPage,      /* Store pointer to the allocated page here */
5962   Pgno *pPgno,           /* Store the page number here */
5963   Pgno nearby,           /* Search for a page near this one */
5964   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5965 ){
5966   MemPage *pPage1;
5967   int rc;
5968   u32 n;     /* Number of pages on the freelist */
5969   u32 k;     /* Number of leaves on the trunk of the freelist */
5970   MemPage *pTrunk = 0;
5971   MemPage *pPrevTrunk = 0;
5972   Pgno mxPage;     /* Total size of the database file */
5973 
5974   assert( sqlite3_mutex_held(pBt->mutex) );
5975   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5976   pPage1 = pBt->pPage1;
5977   mxPage = btreePagecount(pBt);
5978   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5979   ** stores stores the total number of pages on the freelist. */
5980   n = get4byte(&pPage1->aData[36]);
5981   testcase( n==mxPage-1 );
5982   if( n>=mxPage ){
5983     return SQLITE_CORRUPT_BKPT;
5984   }
5985   if( n>0 ){
5986     /* There are pages on the freelist.  Reuse one of those pages. */
5987     Pgno iTrunk;
5988     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5989     u32 nSearch = 0;   /* Count of the number of search attempts */
5990 
5991     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5992     ** shows that the page 'nearby' is somewhere on the free-list, then
5993     ** the entire-list will be searched for that page.
5994     */
5995 #ifndef SQLITE_OMIT_AUTOVACUUM
5996     if( eMode==BTALLOC_EXACT ){
5997       if( nearby<=mxPage ){
5998         u8 eType;
5999         assert( nearby>0 );
6000         assert( pBt->autoVacuum );
6001         rc = ptrmapGet(pBt, nearby, &eType, 0);
6002         if( rc ) return rc;
6003         if( eType==PTRMAP_FREEPAGE ){
6004           searchList = 1;
6005         }
6006       }
6007     }else if( eMode==BTALLOC_LE ){
6008       searchList = 1;
6009     }
6010 #endif
6011 
6012     /* Decrement the free-list count by 1. Set iTrunk to the index of the
6013     ** first free-list trunk page. iPrevTrunk is initially 1.
6014     */
6015     rc = sqlite3PagerWrite(pPage1->pDbPage);
6016     if( rc ) return rc;
6017     put4byte(&pPage1->aData[36], n-1);
6018 
6019     /* The code within this loop is run only once if the 'searchList' variable
6020     ** is not true. Otherwise, it runs once for each trunk-page on the
6021     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6022     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6023     */
6024     do {
6025       pPrevTrunk = pTrunk;
6026       if( pPrevTrunk ){
6027         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6028         ** is the page number of the next freelist trunk page in the list or
6029         ** zero if this is the last freelist trunk page. */
6030         iTrunk = get4byte(&pPrevTrunk->aData[0]);
6031       }else{
6032         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6033         ** stores the page number of the first page of the freelist, or zero if
6034         ** the freelist is empty. */
6035         iTrunk = get4byte(&pPage1->aData[32]);
6036       }
6037       testcase( iTrunk==mxPage );
6038       if( iTrunk>mxPage || nSearch++ > n ){
6039         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6040       }else{
6041         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6042       }
6043       if( rc ){
6044         pTrunk = 0;
6045         goto end_allocate_page;
6046       }
6047       assert( pTrunk!=0 );
6048       assert( pTrunk->aData!=0 );
6049       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6050       ** is the number of leaf page pointers to follow. */
6051       k = get4byte(&pTrunk->aData[4]);
6052       if( k==0 && !searchList ){
6053         /* The trunk has no leaves and the list is not being searched.
6054         ** So extract the trunk page itself and use it as the newly
6055         ** allocated page */
6056         assert( pPrevTrunk==0 );
6057         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6058         if( rc ){
6059           goto end_allocate_page;
6060         }
6061         *pPgno = iTrunk;
6062         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6063         *ppPage = pTrunk;
6064         pTrunk = 0;
6065         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6066       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6067         /* Value of k is out of range.  Database corruption */
6068         rc = SQLITE_CORRUPT_PGNO(iTrunk);
6069         goto end_allocate_page;
6070 #ifndef SQLITE_OMIT_AUTOVACUUM
6071       }else if( searchList
6072             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6073       ){
6074         /* The list is being searched and this trunk page is the page
6075         ** to allocate, regardless of whether it has leaves.
6076         */
6077         *pPgno = iTrunk;
6078         *ppPage = pTrunk;
6079         searchList = 0;
6080         rc = sqlite3PagerWrite(pTrunk->pDbPage);
6081         if( rc ){
6082           goto end_allocate_page;
6083         }
6084         if( k==0 ){
6085           if( !pPrevTrunk ){
6086             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6087           }else{
6088             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6089             if( rc!=SQLITE_OK ){
6090               goto end_allocate_page;
6091             }
6092             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6093           }
6094         }else{
6095           /* The trunk page is required by the caller but it contains
6096           ** pointers to free-list leaves. The first leaf becomes a trunk
6097           ** page in this case.
6098           */
6099           MemPage *pNewTrunk;
6100           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6101           if( iNewTrunk>mxPage ){
6102             rc = SQLITE_CORRUPT_PGNO(iTrunk);
6103             goto end_allocate_page;
6104           }
6105           testcase( iNewTrunk==mxPage );
6106           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6107           if( rc!=SQLITE_OK ){
6108             goto end_allocate_page;
6109           }
6110           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6111           if( rc!=SQLITE_OK ){
6112             releasePage(pNewTrunk);
6113             goto end_allocate_page;
6114           }
6115           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6116           put4byte(&pNewTrunk->aData[4], k-1);
6117           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6118           releasePage(pNewTrunk);
6119           if( !pPrevTrunk ){
6120             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6121             put4byte(&pPage1->aData[32], iNewTrunk);
6122           }else{
6123             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6124             if( rc ){
6125               goto end_allocate_page;
6126             }
6127             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6128           }
6129         }
6130         pTrunk = 0;
6131         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6132 #endif
6133       }else if( k>0 ){
6134         /* Extract a leaf from the trunk */
6135         u32 closest;
6136         Pgno iPage;
6137         unsigned char *aData = pTrunk->aData;
6138         if( nearby>0 ){
6139           u32 i;
6140           closest = 0;
6141           if( eMode==BTALLOC_LE ){
6142             for(i=0; i<k; i++){
6143               iPage = get4byte(&aData[8+i*4]);
6144               if( iPage<=nearby ){
6145                 closest = i;
6146                 break;
6147               }
6148             }
6149           }else{
6150             int dist;
6151             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6152             for(i=1; i<k; i++){
6153               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6154               if( d2<dist ){
6155                 closest = i;
6156                 dist = d2;
6157               }
6158             }
6159           }
6160         }else{
6161           closest = 0;
6162         }
6163 
6164         iPage = get4byte(&aData[8+closest*4]);
6165         testcase( iPage==mxPage );
6166         if( iPage>mxPage || iPage<2 ){
6167           rc = SQLITE_CORRUPT_PGNO(iTrunk);
6168           goto end_allocate_page;
6169         }
6170         testcase( iPage==mxPage );
6171         if( !searchList
6172          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6173         ){
6174           int noContent;
6175           *pPgno = iPage;
6176           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6177                  ": %d more free pages\n",
6178                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
6179           rc = sqlite3PagerWrite(pTrunk->pDbPage);
6180           if( rc ) goto end_allocate_page;
6181           if( closest<k-1 ){
6182             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6183           }
6184           put4byte(&aData[4], k-1);
6185           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6186           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6187           if( rc==SQLITE_OK ){
6188             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6189             if( rc!=SQLITE_OK ){
6190               releasePage(*ppPage);
6191               *ppPage = 0;
6192             }
6193           }
6194           searchList = 0;
6195         }
6196       }
6197       releasePage(pPrevTrunk);
6198       pPrevTrunk = 0;
6199     }while( searchList );
6200   }else{
6201     /* There are no pages on the freelist, so append a new page to the
6202     ** database image.
6203     **
6204     ** Normally, new pages allocated by this block can be requested from the
6205     ** pager layer with the 'no-content' flag set. This prevents the pager
6206     ** from trying to read the pages content from disk. However, if the
6207     ** current transaction has already run one or more incremental-vacuum
6208     ** steps, then the page we are about to allocate may contain content
6209     ** that is required in the event of a rollback. In this case, do
6210     ** not set the no-content flag. This causes the pager to load and journal
6211     ** the current page content before overwriting it.
6212     **
6213     ** Note that the pager will not actually attempt to load or journal
6214     ** content for any page that really does lie past the end of the database
6215     ** file on disk. So the effects of disabling the no-content optimization
6216     ** here are confined to those pages that lie between the end of the
6217     ** database image and the end of the database file.
6218     */
6219     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6220 
6221     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6222     if( rc ) return rc;
6223     pBt->nPage++;
6224     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6225 
6226 #ifndef SQLITE_OMIT_AUTOVACUUM
6227     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6228       /* If *pPgno refers to a pointer-map page, allocate two new pages
6229       ** at the end of the file instead of one. The first allocated page
6230       ** becomes a new pointer-map page, the second is used by the caller.
6231       */
6232       MemPage *pPg = 0;
6233       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6234       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6235       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6236       if( rc==SQLITE_OK ){
6237         rc = sqlite3PagerWrite(pPg->pDbPage);
6238         releasePage(pPg);
6239       }
6240       if( rc ) return rc;
6241       pBt->nPage++;
6242       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6243     }
6244 #endif
6245     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6246     *pPgno = pBt->nPage;
6247 
6248     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6249     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6250     if( rc ) return rc;
6251     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6252     if( rc!=SQLITE_OK ){
6253       releasePage(*ppPage);
6254       *ppPage = 0;
6255     }
6256     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6257   }
6258 
6259   assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6260 
6261 end_allocate_page:
6262   releasePage(pTrunk);
6263   releasePage(pPrevTrunk);
6264   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6265   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6266   return rc;
6267 }
6268 
6269 /*
6270 ** This function is used to add page iPage to the database file free-list.
6271 ** It is assumed that the page is not already a part of the free-list.
6272 **
6273 ** The value passed as the second argument to this function is optional.
6274 ** If the caller happens to have a pointer to the MemPage object
6275 ** corresponding to page iPage handy, it may pass it as the second value.
6276 ** Otherwise, it may pass NULL.
6277 **
6278 ** If a pointer to a MemPage object is passed as the second argument,
6279 ** its reference count is not altered by this function.
6280 */
6281 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6282   MemPage *pTrunk = 0;                /* Free-list trunk page */
6283   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
6284   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
6285   MemPage *pPage;                     /* Page being freed. May be NULL. */
6286   int rc;                             /* Return Code */
6287   u32 nFree;                          /* Initial number of pages on free-list */
6288 
6289   assert( sqlite3_mutex_held(pBt->mutex) );
6290   assert( CORRUPT_DB || iPage>1 );
6291   assert( !pMemPage || pMemPage->pgno==iPage );
6292 
6293   if( iPage<2 || iPage>pBt->nPage ){
6294     return SQLITE_CORRUPT_BKPT;
6295   }
6296   if( pMemPage ){
6297     pPage = pMemPage;
6298     sqlite3PagerRef(pPage->pDbPage);
6299   }else{
6300     pPage = btreePageLookup(pBt, iPage);
6301   }
6302 
6303   /* Increment the free page count on pPage1 */
6304   rc = sqlite3PagerWrite(pPage1->pDbPage);
6305   if( rc ) goto freepage_out;
6306   nFree = get4byte(&pPage1->aData[36]);
6307   put4byte(&pPage1->aData[36], nFree+1);
6308 
6309   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6310     /* If the secure_delete option is enabled, then
6311     ** always fully overwrite deleted information with zeros.
6312     */
6313     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6314      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6315     ){
6316       goto freepage_out;
6317     }
6318     memset(pPage->aData, 0, pPage->pBt->pageSize);
6319   }
6320 
6321   /* If the database supports auto-vacuum, write an entry in the pointer-map
6322   ** to indicate that the page is free.
6323   */
6324   if( ISAUTOVACUUM ){
6325     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6326     if( rc ) goto freepage_out;
6327   }
6328 
6329   /* Now manipulate the actual database free-list structure. There are two
6330   ** possibilities. If the free-list is currently empty, or if the first
6331   ** trunk page in the free-list is full, then this page will become a
6332   ** new free-list trunk page. Otherwise, it will become a leaf of the
6333   ** first trunk page in the current free-list. This block tests if it
6334   ** is possible to add the page as a new free-list leaf.
6335   */
6336   if( nFree!=0 ){
6337     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6338 
6339     iTrunk = get4byte(&pPage1->aData[32]);
6340     if( iTrunk>btreePagecount(pBt) ){
6341       rc = SQLITE_CORRUPT_BKPT;
6342       goto freepage_out;
6343     }
6344     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6345     if( rc!=SQLITE_OK ){
6346       goto freepage_out;
6347     }
6348 
6349     nLeaf = get4byte(&pTrunk->aData[4]);
6350     assert( pBt->usableSize>32 );
6351     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6352       rc = SQLITE_CORRUPT_BKPT;
6353       goto freepage_out;
6354     }
6355     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6356       /* In this case there is room on the trunk page to insert the page
6357       ** being freed as a new leaf.
6358       **
6359       ** Note that the trunk page is not really full until it contains
6360       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6361       ** coded.  But due to a coding error in versions of SQLite prior to
6362       ** 3.6.0, databases with freelist trunk pages holding more than
6363       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6364       ** to maintain backwards compatibility with older versions of SQLite,
6365       ** we will continue to restrict the number of entries to usableSize/4 - 8
6366       ** for now.  At some point in the future (once everyone has upgraded
6367       ** to 3.6.0 or later) we should consider fixing the conditional above
6368       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6369       **
6370       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6371       ** avoid using the last six entries in the freelist trunk page array in
6372       ** order that database files created by newer versions of SQLite can be
6373       ** read by older versions of SQLite.
6374       */
6375       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6376       if( rc==SQLITE_OK ){
6377         put4byte(&pTrunk->aData[4], nLeaf+1);
6378         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6379         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6380           sqlite3PagerDontWrite(pPage->pDbPage);
6381         }
6382         rc = btreeSetHasContent(pBt, iPage);
6383       }
6384       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6385       goto freepage_out;
6386     }
6387   }
6388 
6389   /* If control flows to this point, then it was not possible to add the
6390   ** the page being freed as a leaf page of the first trunk in the free-list.
6391   ** Possibly because the free-list is empty, or possibly because the
6392   ** first trunk in the free-list is full. Either way, the page being freed
6393   ** will become the new first trunk page in the free-list.
6394   */
6395   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6396     goto freepage_out;
6397   }
6398   rc = sqlite3PagerWrite(pPage->pDbPage);
6399   if( rc!=SQLITE_OK ){
6400     goto freepage_out;
6401   }
6402   put4byte(pPage->aData, iTrunk);
6403   put4byte(&pPage->aData[4], 0);
6404   put4byte(&pPage1->aData[32], iPage);
6405   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6406 
6407 freepage_out:
6408   if( pPage ){
6409     pPage->isInit = 0;
6410   }
6411   releasePage(pPage);
6412   releasePage(pTrunk);
6413   return rc;
6414 }
6415 static void freePage(MemPage *pPage, int *pRC){
6416   if( (*pRC)==SQLITE_OK ){
6417     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6418   }
6419 }
6420 
6421 /*
6422 ** Free any overflow pages associated with the given Cell.  Store
6423 ** size information about the cell in pInfo.
6424 */
6425 static int clearCell(
6426   MemPage *pPage,          /* The page that contains the Cell */
6427   unsigned char *pCell,    /* First byte of the Cell */
6428   CellInfo *pInfo          /* Size information about the cell */
6429 ){
6430   BtShared *pBt;
6431   Pgno ovflPgno;
6432   int rc;
6433   int nOvfl;
6434   u32 ovflPageSize;
6435 
6436   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6437   pPage->xParseCell(pPage, pCell, pInfo);
6438   if( pInfo->nLocal==pInfo->nPayload ){
6439     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
6440   }
6441   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6442   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6443   if( pCell + pInfo->nSize > pPage->aDataEnd ){
6444     /* Cell extends past end of page */
6445     return SQLITE_CORRUPT_PAGE(pPage);
6446   }
6447   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6448   pBt = pPage->pBt;
6449   assert( pBt->usableSize > 4 );
6450   ovflPageSize = pBt->usableSize - 4;
6451   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6452   assert( nOvfl>0 ||
6453     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6454   );
6455   while( nOvfl-- ){
6456     Pgno iNext = 0;
6457     MemPage *pOvfl = 0;
6458     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6459       /* 0 is not a legal page number and page 1 cannot be an
6460       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6461       ** file the database must be corrupt. */
6462       return SQLITE_CORRUPT_BKPT;
6463     }
6464     if( nOvfl ){
6465       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6466       if( rc ) return rc;
6467     }
6468 
6469     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6470      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6471     ){
6472       /* There is no reason any cursor should have an outstanding reference
6473       ** to an overflow page belonging to a cell that is being deleted/updated.
6474       ** So if there exists more than one reference to this page, then it
6475       ** must not really be an overflow page and the database must be corrupt.
6476       ** It is helpful to detect this before calling freePage2(), as
6477       ** freePage2() may zero the page contents if secure-delete mode is
6478       ** enabled. If this 'overflow' page happens to be a page that the
6479       ** caller is iterating through or using in some other way, this
6480       ** can be problematic.
6481       */
6482       rc = SQLITE_CORRUPT_BKPT;
6483     }else{
6484       rc = freePage2(pBt, pOvfl, ovflPgno);
6485     }
6486 
6487     if( pOvfl ){
6488       sqlite3PagerUnref(pOvfl->pDbPage);
6489     }
6490     if( rc ) return rc;
6491     ovflPgno = iNext;
6492   }
6493   return SQLITE_OK;
6494 }
6495 
6496 /*
6497 ** Create the byte sequence used to represent a cell on page pPage
6498 ** and write that byte sequence into pCell[].  Overflow pages are
6499 ** allocated and filled in as necessary.  The calling procedure
6500 ** is responsible for making sure sufficient space has been allocated
6501 ** for pCell[].
6502 **
6503 ** Note that pCell does not necessary need to point to the pPage->aData
6504 ** area.  pCell might point to some temporary storage.  The cell will
6505 ** be constructed in this temporary area then copied into pPage->aData
6506 ** later.
6507 */
6508 static int fillInCell(
6509   MemPage *pPage,                /* The page that contains the cell */
6510   unsigned char *pCell,          /* Complete text of the cell */
6511   const BtreePayload *pX,        /* Payload with which to construct the cell */
6512   int *pnSize                    /* Write cell size here */
6513 ){
6514   int nPayload;
6515   const u8 *pSrc;
6516   int nSrc, n, rc, mn;
6517   int spaceLeft;
6518   MemPage *pToRelease;
6519   unsigned char *pPrior;
6520   unsigned char *pPayload;
6521   BtShared *pBt;
6522   Pgno pgnoOvfl;
6523   int nHeader;
6524 
6525   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6526 
6527   /* pPage is not necessarily writeable since pCell might be auxiliary
6528   ** buffer space that is separate from the pPage buffer area */
6529   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6530             || sqlite3PagerIswriteable(pPage->pDbPage) );
6531 
6532   /* Fill in the header. */
6533   nHeader = pPage->childPtrSize;
6534   if( pPage->intKey ){
6535     nPayload = pX->nData + pX->nZero;
6536     pSrc = pX->pData;
6537     nSrc = pX->nData;
6538     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6539     nHeader += putVarint32(&pCell[nHeader], nPayload);
6540     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6541   }else{
6542     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6543     nSrc = nPayload = (int)pX->nKey;
6544     pSrc = pX->pKey;
6545     nHeader += putVarint32(&pCell[nHeader], nPayload);
6546   }
6547 
6548   /* Fill in the payload */
6549   pPayload = &pCell[nHeader];
6550   if( nPayload<=pPage->maxLocal ){
6551     /* This is the common case where everything fits on the btree page
6552     ** and no overflow pages are required. */
6553     n = nHeader + nPayload;
6554     testcase( n==3 );
6555     testcase( n==4 );
6556     if( n<4 ) n = 4;
6557     *pnSize = n;
6558     assert( nSrc<=nPayload );
6559     testcase( nSrc<nPayload );
6560     memcpy(pPayload, pSrc, nSrc);
6561     memset(pPayload+nSrc, 0, nPayload-nSrc);
6562     return SQLITE_OK;
6563   }
6564 
6565   /* If we reach this point, it means that some of the content will need
6566   ** to spill onto overflow pages.
6567   */
6568   mn = pPage->minLocal;
6569   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6570   testcase( n==pPage->maxLocal );
6571   testcase( n==pPage->maxLocal+1 );
6572   if( n > pPage->maxLocal ) n = mn;
6573   spaceLeft = n;
6574   *pnSize = n + nHeader + 4;
6575   pPrior = &pCell[nHeader+n];
6576   pToRelease = 0;
6577   pgnoOvfl = 0;
6578   pBt = pPage->pBt;
6579 
6580   /* At this point variables should be set as follows:
6581   **
6582   **   nPayload           Total payload size in bytes
6583   **   pPayload           Begin writing payload here
6584   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6585   **                      that means content must spill into overflow pages.
6586   **   *pnSize            Size of the local cell (not counting overflow pages)
6587   **   pPrior             Where to write the pgno of the first overflow page
6588   **
6589   ** Use a call to btreeParseCellPtr() to verify that the values above
6590   ** were computed correctly.
6591   */
6592 #ifdef SQLITE_DEBUG
6593   {
6594     CellInfo info;
6595     pPage->xParseCell(pPage, pCell, &info);
6596     assert( nHeader==(int)(info.pPayload - pCell) );
6597     assert( info.nKey==pX->nKey );
6598     assert( *pnSize == info.nSize );
6599     assert( spaceLeft == info.nLocal );
6600   }
6601 #endif
6602 
6603   /* Write the payload into the local Cell and any extra into overflow pages */
6604   while( 1 ){
6605     n = nPayload;
6606     if( n>spaceLeft ) n = spaceLeft;
6607 
6608     /* If pToRelease is not zero than pPayload points into the data area
6609     ** of pToRelease.  Make sure pToRelease is still writeable. */
6610     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6611 
6612     /* If pPayload is part of the data area of pPage, then make sure pPage
6613     ** is still writeable */
6614     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6615             || sqlite3PagerIswriteable(pPage->pDbPage) );
6616 
6617     if( nSrc>=n ){
6618       memcpy(pPayload, pSrc, n);
6619     }else if( nSrc>0 ){
6620       n = nSrc;
6621       memcpy(pPayload, pSrc, n);
6622     }else{
6623       memset(pPayload, 0, n);
6624     }
6625     nPayload -= n;
6626     if( nPayload<=0 ) break;
6627     pPayload += n;
6628     pSrc += n;
6629     nSrc -= n;
6630     spaceLeft -= n;
6631     if( spaceLeft==0 ){
6632       MemPage *pOvfl = 0;
6633 #ifndef SQLITE_OMIT_AUTOVACUUM
6634       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6635       if( pBt->autoVacuum ){
6636         do{
6637           pgnoOvfl++;
6638         } while(
6639           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6640         );
6641       }
6642 #endif
6643       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6644 #ifndef SQLITE_OMIT_AUTOVACUUM
6645       /* If the database supports auto-vacuum, and the second or subsequent
6646       ** overflow page is being allocated, add an entry to the pointer-map
6647       ** for that page now.
6648       **
6649       ** If this is the first overflow page, then write a partial entry
6650       ** to the pointer-map. If we write nothing to this pointer-map slot,
6651       ** then the optimistic overflow chain processing in clearCell()
6652       ** may misinterpret the uninitialized values and delete the
6653       ** wrong pages from the database.
6654       */
6655       if( pBt->autoVacuum && rc==SQLITE_OK ){
6656         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6657         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6658         if( rc ){
6659           releasePage(pOvfl);
6660         }
6661       }
6662 #endif
6663       if( rc ){
6664         releasePage(pToRelease);
6665         return rc;
6666       }
6667 
6668       /* If pToRelease is not zero than pPrior points into the data area
6669       ** of pToRelease.  Make sure pToRelease is still writeable. */
6670       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6671 
6672       /* If pPrior is part of the data area of pPage, then make sure pPage
6673       ** is still writeable */
6674       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6675             || sqlite3PagerIswriteable(pPage->pDbPage) );
6676 
6677       put4byte(pPrior, pgnoOvfl);
6678       releasePage(pToRelease);
6679       pToRelease = pOvfl;
6680       pPrior = pOvfl->aData;
6681       put4byte(pPrior, 0);
6682       pPayload = &pOvfl->aData[4];
6683       spaceLeft = pBt->usableSize - 4;
6684     }
6685   }
6686   releasePage(pToRelease);
6687   return SQLITE_OK;
6688 }
6689 
6690 /*
6691 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6692 ** The cell content is not freed or deallocated.  It is assumed that
6693 ** the cell content has been copied someplace else.  This routine just
6694 ** removes the reference to the cell from pPage.
6695 **
6696 ** "sz" must be the number of bytes in the cell.
6697 */
6698 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6699   u32 pc;         /* Offset to cell content of cell being deleted */
6700   u8 *data;       /* pPage->aData */
6701   u8 *ptr;        /* Used to move bytes around within data[] */
6702   int rc;         /* The return code */
6703   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6704 
6705   if( *pRC ) return;
6706   assert( idx>=0 && idx<pPage->nCell );
6707   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6708   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6709   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6710   assert( pPage->nFree>=0 );
6711   data = pPage->aData;
6712   ptr = &pPage->aCellIdx[2*idx];
6713   pc = get2byte(ptr);
6714   hdr = pPage->hdrOffset;
6715   testcase( pc==get2byte(&data[hdr+5]) );
6716   testcase( pc+sz==pPage->pBt->usableSize );
6717   if( pc+sz > pPage->pBt->usableSize ){
6718     *pRC = SQLITE_CORRUPT_BKPT;
6719     return;
6720   }
6721   rc = freeSpace(pPage, pc, sz);
6722   if( rc ){
6723     *pRC = rc;
6724     return;
6725   }
6726   pPage->nCell--;
6727   if( pPage->nCell==0 ){
6728     memset(&data[hdr+1], 0, 4);
6729     data[hdr+7] = 0;
6730     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6731     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6732                        - pPage->childPtrSize - 8;
6733   }else{
6734     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6735     put2byte(&data[hdr+3], pPage->nCell);
6736     pPage->nFree += 2;
6737   }
6738 }
6739 
6740 /*
6741 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6742 ** content of the cell.
6743 **
6744 ** If the cell content will fit on the page, then put it there.  If it
6745 ** will not fit, then make a copy of the cell content into pTemp if
6746 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6747 ** in pPage->apOvfl[] and make it point to the cell content (either
6748 ** in pTemp or the original pCell) and also record its index.
6749 ** Allocating a new entry in pPage->aCell[] implies that
6750 ** pPage->nOverflow is incremented.
6751 **
6752 ** *pRC must be SQLITE_OK when this routine is called.
6753 */
6754 static void insertCell(
6755   MemPage *pPage,   /* Page into which we are copying */
6756   int i,            /* New cell becomes the i-th cell of the page */
6757   u8 *pCell,        /* Content of the new cell */
6758   int sz,           /* Bytes of content in pCell */
6759   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6760   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6761   int *pRC          /* Read and write return code from here */
6762 ){
6763   int idx = 0;      /* Where to write new cell content in data[] */
6764   int j;            /* Loop counter */
6765   u8 *data;         /* The content of the whole page */
6766   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6767 
6768   assert( *pRC==SQLITE_OK );
6769   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6770   assert( MX_CELL(pPage->pBt)<=10921 );
6771   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6772   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6773   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6774   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6775   assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6776   assert( pPage->nFree>=0 );
6777   if( pPage->nOverflow || sz+2>pPage->nFree ){
6778     if( pTemp ){
6779       memcpy(pTemp, pCell, sz);
6780       pCell = pTemp;
6781     }
6782     if( iChild ){
6783       put4byte(pCell, iChild);
6784     }
6785     j = pPage->nOverflow++;
6786     /* Comparison against ArraySize-1 since we hold back one extra slot
6787     ** as a contingency.  In other words, never need more than 3 overflow
6788     ** slots but 4 are allocated, just to be safe. */
6789     assert( j < ArraySize(pPage->apOvfl)-1 );
6790     pPage->apOvfl[j] = pCell;
6791     pPage->aiOvfl[j] = (u16)i;
6792 
6793     /* When multiple overflows occur, they are always sequential and in
6794     ** sorted order.  This invariants arise because multiple overflows can
6795     ** only occur when inserting divider cells into the parent page during
6796     ** balancing, and the dividers are adjacent and sorted.
6797     */
6798     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6799     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6800   }else{
6801     int rc = sqlite3PagerWrite(pPage->pDbPage);
6802     if( rc!=SQLITE_OK ){
6803       *pRC = rc;
6804       return;
6805     }
6806     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6807     data = pPage->aData;
6808     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6809     rc = allocateSpace(pPage, sz, &idx);
6810     if( rc ){ *pRC = rc; return; }
6811     /* The allocateSpace() routine guarantees the following properties
6812     ** if it returns successfully */
6813     assert( idx >= 0 );
6814     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6815     assert( idx+sz <= (int)pPage->pBt->usableSize );
6816     pPage->nFree -= (u16)(2 + sz);
6817     if( iChild ){
6818       /* In a corrupt database where an entry in the cell index section of
6819       ** a btree page has a value of 3 or less, the pCell value might point
6820       ** as many as 4 bytes in front of the start of the aData buffer for
6821       ** the source page.  Make sure this does not cause problems by not
6822       ** reading the first 4 bytes */
6823       memcpy(&data[idx+4], pCell+4, sz-4);
6824       put4byte(&data[idx], iChild);
6825     }else{
6826       memcpy(&data[idx], pCell, sz);
6827     }
6828     pIns = pPage->aCellIdx + i*2;
6829     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6830     put2byte(pIns, idx);
6831     pPage->nCell++;
6832     /* increment the cell count */
6833     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6834     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6835 #ifndef SQLITE_OMIT_AUTOVACUUM
6836     if( pPage->pBt->autoVacuum ){
6837       /* The cell may contain a pointer to an overflow page. If so, write
6838       ** the entry for the overflow page into the pointer map.
6839       */
6840       ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6841     }
6842 #endif
6843   }
6844 }
6845 
6846 /*
6847 ** The following parameters determine how many adjacent pages get involved
6848 ** in a balancing operation.  NN is the number of neighbors on either side
6849 ** of the page that participate in the balancing operation.  NB is the
6850 ** total number of pages that participate, including the target page and
6851 ** NN neighbors on either side.
6852 **
6853 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
6854 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6855 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6856 ** The value of NN appears to give the best results overall.
6857 **
6858 ** (Later:) The description above makes it seem as if these values are
6859 ** tunable - as if you could change them and recompile and it would all work.
6860 ** But that is unlikely.  NB has been 3 since the inception of SQLite and
6861 ** we have never tested any other value.
6862 */
6863 #define NN 1             /* Number of neighbors on either side of pPage */
6864 #define NB 3             /* (NN*2+1): Total pages involved in the balance */
6865 
6866 /*
6867 ** A CellArray object contains a cache of pointers and sizes for a
6868 ** consecutive sequence of cells that might be held on multiple pages.
6869 **
6870 ** The cells in this array are the divider cell or cells from the pParent
6871 ** page plus up to three child pages.  There are a total of nCell cells.
6872 **
6873 ** pRef is a pointer to one of the pages that contributes cells.  This is
6874 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6875 ** which should be common to all pages that contribute cells to this array.
6876 **
6877 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6878 ** cell and the size of each cell.  Some of the apCell[] pointers might refer
6879 ** to overflow cells.  In other words, some apCel[] pointers might not point
6880 ** to content area of the pages.
6881 **
6882 ** A szCell[] of zero means the size of that cell has not yet been computed.
6883 **
6884 ** The cells come from as many as four different pages:
6885 **
6886 **             -----------
6887 **             | Parent  |
6888 **             -----------
6889 **            /     |     \
6890 **           /      |      \
6891 **  ---------   ---------   ---------
6892 **  |Child-1|   |Child-2|   |Child-3|
6893 **  ---------   ---------   ---------
6894 **
6895 ** The order of cells is in the array is for an index btree is:
6896 **
6897 **       1.  All cells from Child-1 in order
6898 **       2.  The first divider cell from Parent
6899 **       3.  All cells from Child-2 in order
6900 **       4.  The second divider cell from Parent
6901 **       5.  All cells from Child-3 in order
6902 **
6903 ** For a table-btree (with rowids) the items 2 and 4 are empty because
6904 ** content exists only in leaves and there are no divider cells.
6905 **
6906 ** For an index btree, the apEnd[] array holds pointer to the end of page
6907 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
6908 ** respectively. The ixNx[] array holds the number of cells contained in
6909 ** each of these 5 stages, and all stages to the left.  Hence:
6910 **
6911 **    ixNx[0] = Number of cells in Child-1.
6912 **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
6913 **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
6914 **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
6915 **    ixNx[4] = Total number of cells.
6916 **
6917 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
6918 ** are used and they point to the leaf pages only, and the ixNx value are:
6919 **
6920 **    ixNx[0] = Number of cells in Child-1.
6921 **    ixNx[1] = Number of cells in Child-1 and Child-2.
6922 **    ixNx[2] = Total number of cells.
6923 **
6924 ** Sometimes when deleting, a child page can have zero cells.  In those
6925 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
6926 ** entries, shift down.  The end result is that each ixNx[] entry should
6927 ** be larger than the previous
6928 */
6929 typedef struct CellArray CellArray;
6930 struct CellArray {
6931   int nCell;              /* Number of cells in apCell[] */
6932   MemPage *pRef;          /* Reference page */
6933   u8 **apCell;            /* All cells begin balanced */
6934   u16 *szCell;            /* Local size of all cells in apCell[] */
6935   u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
6936   int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
6937 };
6938 
6939 /*
6940 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6941 ** computed.
6942 */
6943 static void populateCellCache(CellArray *p, int idx, int N){
6944   assert( idx>=0 && idx+N<=p->nCell );
6945   while( N>0 ){
6946     assert( p->apCell[idx]!=0 );
6947     if( p->szCell[idx]==0 ){
6948       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6949     }else{
6950       assert( CORRUPT_DB ||
6951               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6952     }
6953     idx++;
6954     N--;
6955   }
6956 }
6957 
6958 /*
6959 ** Return the size of the Nth element of the cell array
6960 */
6961 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6962   assert( N>=0 && N<p->nCell );
6963   assert( p->szCell[N]==0 );
6964   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6965   return p->szCell[N];
6966 }
6967 static u16 cachedCellSize(CellArray *p, int N){
6968   assert( N>=0 && N<p->nCell );
6969   if( p->szCell[N] ) return p->szCell[N];
6970   return computeCellSize(p, N);
6971 }
6972 
6973 /*
6974 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6975 ** szCell[] array contains the size in bytes of each cell. This function
6976 ** replaces the current contents of page pPg with the contents of the cell
6977 ** array.
6978 **
6979 ** Some of the cells in apCell[] may currently be stored in pPg. This
6980 ** function works around problems caused by this by making a copy of any
6981 ** such cells before overwriting the page data.
6982 **
6983 ** The MemPage.nFree field is invalidated by this function. It is the
6984 ** responsibility of the caller to set it correctly.
6985 */
6986 static int rebuildPage(
6987   CellArray *pCArray,             /* Content to be added to page pPg */
6988   int iFirst,                     /* First cell in pCArray to use */
6989   int nCell,                      /* Final number of cells on page */
6990   MemPage *pPg                    /* The page to be reconstructed */
6991 ){
6992   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
6993   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
6994   const int usableSize = pPg->pBt->usableSize;
6995   u8 * const pEnd = &aData[usableSize];
6996   int i = iFirst;                 /* Which cell to copy from pCArray*/
6997   u32 j;                          /* Start of cell content area */
6998   int iEnd = i+nCell;             /* Loop terminator */
6999   u8 *pCellptr = pPg->aCellIdx;
7000   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7001   u8 *pData;
7002   int k;                          /* Current slot in pCArray->apEnd[] */
7003   u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
7004 
7005   assert( i<iEnd );
7006   j = get2byte(&aData[hdr+5]);
7007   if( NEVER(j>(u32)usableSize) ){ j = 0; }
7008   memcpy(&pTmp[j], &aData[j], usableSize - j);
7009 
7010   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7011   pSrcEnd = pCArray->apEnd[k];
7012 
7013   pData = pEnd;
7014   while( 1/*exit by break*/ ){
7015     u8 *pCell = pCArray->apCell[i];
7016     u16 sz = pCArray->szCell[i];
7017     assert( sz>0 );
7018     if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7019       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7020       pCell = &pTmp[pCell - aData];
7021     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7022            && (uptr)(pCell)<(uptr)pSrcEnd
7023     ){
7024       return SQLITE_CORRUPT_BKPT;
7025     }
7026 
7027     pData -= sz;
7028     put2byte(pCellptr, (pData - aData));
7029     pCellptr += 2;
7030     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7031     memmove(pData, pCell, sz);
7032     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7033     i++;
7034     if( i>=iEnd ) break;
7035     if( pCArray->ixNx[k]<=i ){
7036       k++;
7037       pSrcEnd = pCArray->apEnd[k];
7038     }
7039   }
7040 
7041   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7042   pPg->nCell = nCell;
7043   pPg->nOverflow = 0;
7044 
7045   put2byte(&aData[hdr+1], 0);
7046   put2byte(&aData[hdr+3], pPg->nCell);
7047   put2byte(&aData[hdr+5], pData - aData);
7048   aData[hdr+7] = 0x00;
7049   return SQLITE_OK;
7050 }
7051 
7052 /*
7053 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7054 ** This function attempts to add the cells stored in the array to page pPg.
7055 ** If it cannot (because the page needs to be defragmented before the cells
7056 ** will fit), non-zero is returned. Otherwise, if the cells are added
7057 ** successfully, zero is returned.
7058 **
7059 ** Argument pCellptr points to the first entry in the cell-pointer array
7060 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7061 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7062 ** cell in the array. It is the responsibility of the caller to ensure
7063 ** that it is safe to overwrite this part of the cell-pointer array.
7064 **
7065 ** When this function is called, *ppData points to the start of the
7066 ** content area on page pPg. If the size of the content area is extended,
7067 ** *ppData is updated to point to the new start of the content area
7068 ** before returning.
7069 **
7070 ** Finally, argument pBegin points to the byte immediately following the
7071 ** end of the space required by this page for the cell-pointer area (for
7072 ** all cells - not just those inserted by the current call). If the content
7073 ** area must be extended to before this point in order to accomodate all
7074 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7075 */
7076 static int pageInsertArray(
7077   MemPage *pPg,                   /* Page to add cells to */
7078   u8 *pBegin,                     /* End of cell-pointer array */
7079   u8 **ppData,                    /* IN/OUT: Page content-area pointer */
7080   u8 *pCellptr,                   /* Pointer to cell-pointer area */
7081   int iFirst,                     /* Index of first cell to add */
7082   int nCell,                      /* Number of cells to add to pPg */
7083   CellArray *pCArray              /* Array of cells */
7084 ){
7085   int i = iFirst;                 /* Loop counter - cell index to insert */
7086   u8 *aData = pPg->aData;         /* Complete page */
7087   u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
7088   int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
7089   int k;                          /* Current slot in pCArray->apEnd[] */
7090   u8 *pEnd;                       /* Maximum extent of cell data */
7091   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
7092   if( iEnd<=iFirst ) return 0;
7093   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7094   pEnd = pCArray->apEnd[k];
7095   while( 1 /*Exit by break*/ ){
7096     int sz, rc;
7097     u8 *pSlot;
7098     assert( pCArray->szCell[i]!=0 );
7099     sz = pCArray->szCell[i];
7100     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7101       if( (pData - pBegin)<sz ) return 1;
7102       pData -= sz;
7103       pSlot = pData;
7104     }
7105     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7106     ** database.  But they might for a corrupt database.  Hence use memmove()
7107     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7108     assert( (pSlot+sz)<=pCArray->apCell[i]
7109          || pSlot>=(pCArray->apCell[i]+sz)
7110          || CORRUPT_DB );
7111     if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7112      && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7113     ){
7114       assert( CORRUPT_DB );
7115       (void)SQLITE_CORRUPT_BKPT;
7116       return 1;
7117     }
7118     memmove(pSlot, pCArray->apCell[i], sz);
7119     put2byte(pCellptr, (pSlot - aData));
7120     pCellptr += 2;
7121     i++;
7122     if( i>=iEnd ) break;
7123     if( pCArray->ixNx[k]<=i ){
7124       k++;
7125       pEnd = pCArray->apEnd[k];
7126     }
7127   }
7128   *ppData = pData;
7129   return 0;
7130 }
7131 
7132 /*
7133 ** The pCArray object contains pointers to b-tree cells and their sizes.
7134 **
7135 ** This function adds the space associated with each cell in the array
7136 ** that is currently stored within the body of pPg to the pPg free-list.
7137 ** The cell-pointers and other fields of the page are not updated.
7138 **
7139 ** This function returns the total number of cells added to the free-list.
7140 */
7141 static int pageFreeArray(
7142   MemPage *pPg,                   /* Page to edit */
7143   int iFirst,                     /* First cell to delete */
7144   int nCell,                      /* Cells to delete */
7145   CellArray *pCArray              /* Array of cells */
7146 ){
7147   u8 * const aData = pPg->aData;
7148   u8 * const pEnd = &aData[pPg->pBt->usableSize];
7149   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7150   int nRet = 0;
7151   int i;
7152   int iEnd = iFirst + nCell;
7153   u8 *pFree = 0;
7154   int szFree = 0;
7155 
7156   for(i=iFirst; i<iEnd; i++){
7157     u8 *pCell = pCArray->apCell[i];
7158     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7159       int sz;
7160       /* No need to use cachedCellSize() here.  The sizes of all cells that
7161       ** are to be freed have already been computing while deciding which
7162       ** cells need freeing */
7163       sz = pCArray->szCell[i];  assert( sz>0 );
7164       if( pFree!=(pCell + sz) ){
7165         if( pFree ){
7166           assert( pFree>aData && (pFree - aData)<65536 );
7167           freeSpace(pPg, (u16)(pFree - aData), szFree);
7168         }
7169         pFree = pCell;
7170         szFree = sz;
7171         if( pFree+sz>pEnd ) return 0;
7172       }else{
7173         pFree = pCell;
7174         szFree += sz;
7175       }
7176       nRet++;
7177     }
7178   }
7179   if( pFree ){
7180     assert( pFree>aData && (pFree - aData)<65536 );
7181     freeSpace(pPg, (u16)(pFree - aData), szFree);
7182   }
7183   return nRet;
7184 }
7185 
7186 /*
7187 ** pCArray contains pointers to and sizes of all cells in the page being
7188 ** balanced.  The current page, pPg, has pPg->nCell cells starting with
7189 ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
7190 ** starting at apCell[iNew].
7191 **
7192 ** This routine makes the necessary adjustments to pPg so that it contains
7193 ** the correct cells after being balanced.
7194 **
7195 ** The pPg->nFree field is invalid when this function returns. It is the
7196 ** responsibility of the caller to set it correctly.
7197 */
7198 static int editPage(
7199   MemPage *pPg,                   /* Edit this page */
7200   int iOld,                       /* Index of first cell currently on page */
7201   int iNew,                       /* Index of new first cell on page */
7202   int nNew,                       /* Final number of cells on page */
7203   CellArray *pCArray              /* Array of cells and sizes */
7204 ){
7205   u8 * const aData = pPg->aData;
7206   const int hdr = pPg->hdrOffset;
7207   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7208   int nCell = pPg->nCell;       /* Cells stored on pPg */
7209   u8 *pData;
7210   u8 *pCellptr;
7211   int i;
7212   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7213   int iNewEnd = iNew + nNew;
7214 
7215 #ifdef SQLITE_DEBUG
7216   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7217   memcpy(pTmp, aData, pPg->pBt->usableSize);
7218 #endif
7219 
7220   /* Remove cells from the start and end of the page */
7221   assert( nCell>=0 );
7222   if( iOld<iNew ){
7223     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7224     if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7225     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7226     nCell -= nShift;
7227   }
7228   if( iNewEnd < iOldEnd ){
7229     int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7230     assert( nCell>=nTail );
7231     nCell -= nTail;
7232   }
7233 
7234   pData = &aData[get2byteNotZero(&aData[hdr+5])];
7235   if( pData<pBegin ) goto editpage_fail;
7236 
7237   /* Add cells to the start of the page */
7238   if( iNew<iOld ){
7239     int nAdd = MIN(nNew,iOld-iNew);
7240     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7241     assert( nAdd>=0 );
7242     pCellptr = pPg->aCellIdx;
7243     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7244     if( pageInsertArray(
7245           pPg, pBegin, &pData, pCellptr,
7246           iNew, nAdd, pCArray
7247     ) ) goto editpage_fail;
7248     nCell += nAdd;
7249   }
7250 
7251   /* Add any overflow cells */
7252   for(i=0; i<pPg->nOverflow; i++){
7253     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7254     if( iCell>=0 && iCell<nNew ){
7255       pCellptr = &pPg->aCellIdx[iCell * 2];
7256       if( nCell>iCell ){
7257         memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7258       }
7259       nCell++;
7260       cachedCellSize(pCArray, iCell+iNew);
7261       if( pageInsertArray(
7262             pPg, pBegin, &pData, pCellptr,
7263             iCell+iNew, 1, pCArray
7264       ) ) goto editpage_fail;
7265     }
7266   }
7267 
7268   /* Append cells to the end of the page */
7269   assert( nCell>=0 );
7270   pCellptr = &pPg->aCellIdx[nCell*2];
7271   if( pageInsertArray(
7272         pPg, pBegin, &pData, pCellptr,
7273         iNew+nCell, nNew-nCell, pCArray
7274   ) ) goto editpage_fail;
7275 
7276   pPg->nCell = nNew;
7277   pPg->nOverflow = 0;
7278 
7279   put2byte(&aData[hdr+3], pPg->nCell);
7280   put2byte(&aData[hdr+5], pData - aData);
7281 
7282 #ifdef SQLITE_DEBUG
7283   for(i=0; i<nNew && !CORRUPT_DB; i++){
7284     u8 *pCell = pCArray->apCell[i+iNew];
7285     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7286     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7287       pCell = &pTmp[pCell - aData];
7288     }
7289     assert( 0==memcmp(pCell, &aData[iOff],
7290             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7291   }
7292 #endif
7293 
7294   return SQLITE_OK;
7295  editpage_fail:
7296   /* Unable to edit this page. Rebuild it from scratch instead. */
7297   populateCellCache(pCArray, iNew, nNew);
7298   return rebuildPage(pCArray, iNew, nNew, pPg);
7299 }
7300 
7301 
7302 #ifndef SQLITE_OMIT_QUICKBALANCE
7303 /*
7304 ** This version of balance() handles the common special case where
7305 ** a new entry is being inserted on the extreme right-end of the
7306 ** tree, in other words, when the new entry will become the largest
7307 ** entry in the tree.
7308 **
7309 ** Instead of trying to balance the 3 right-most leaf pages, just add
7310 ** a new page to the right-hand side and put the one new entry in
7311 ** that page.  This leaves the right side of the tree somewhat
7312 ** unbalanced.  But odds are that we will be inserting new entries
7313 ** at the end soon afterwards so the nearly empty page will quickly
7314 ** fill up.  On average.
7315 **
7316 ** pPage is the leaf page which is the right-most page in the tree.
7317 ** pParent is its parent.  pPage must have a single overflow entry
7318 ** which is also the right-most entry on the page.
7319 **
7320 ** The pSpace buffer is used to store a temporary copy of the divider
7321 ** cell that will be inserted into pParent. Such a cell consists of a 4
7322 ** byte page number followed by a variable length integer. In other
7323 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7324 ** least 13 bytes in size.
7325 */
7326 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7327   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
7328   MemPage *pNew;                       /* Newly allocated page */
7329   int rc;                              /* Return Code */
7330   Pgno pgnoNew;                        /* Page number of pNew */
7331 
7332   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7333   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7334   assert( pPage->nOverflow==1 );
7335 
7336   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
7337   assert( pPage->nFree>=0 );
7338   assert( pParent->nFree>=0 );
7339 
7340   /* Allocate a new page. This page will become the right-sibling of
7341   ** pPage. Make the parent page writable, so that the new divider cell
7342   ** may be inserted. If both these operations are successful, proceed.
7343   */
7344   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7345 
7346   if( rc==SQLITE_OK ){
7347 
7348     u8 *pOut = &pSpace[4];
7349     u8 *pCell = pPage->apOvfl[0];
7350     u16 szCell = pPage->xCellSize(pPage, pCell);
7351     u8 *pStop;
7352     CellArray b;
7353 
7354     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7355     assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7356     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7357     b.nCell = 1;
7358     b.pRef = pPage;
7359     b.apCell = &pCell;
7360     b.szCell = &szCell;
7361     b.apEnd[0] = pPage->aDataEnd;
7362     b.ixNx[0] = 2;
7363     rc = rebuildPage(&b, 0, 1, pNew);
7364     if( NEVER(rc) ){
7365       releasePage(pNew);
7366       return rc;
7367     }
7368     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7369 
7370     /* If this is an auto-vacuum database, update the pointer map
7371     ** with entries for the new page, and any pointer from the
7372     ** cell on the page to an overflow page. If either of these
7373     ** operations fails, the return code is set, but the contents
7374     ** of the parent page are still manipulated by thh code below.
7375     ** That is Ok, at this point the parent page is guaranteed to
7376     ** be marked as dirty. Returning an error code will cause a
7377     ** rollback, undoing any changes made to the parent page.
7378     */
7379     if( ISAUTOVACUUM ){
7380       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7381       if( szCell>pNew->minLocal ){
7382         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7383       }
7384     }
7385 
7386     /* Create a divider cell to insert into pParent. The divider cell
7387     ** consists of a 4-byte page number (the page number of pPage) and
7388     ** a variable length key value (which must be the same value as the
7389     ** largest key on pPage).
7390     **
7391     ** To find the largest key value on pPage, first find the right-most
7392     ** cell on pPage. The first two fields of this cell are the
7393     ** record-length (a variable length integer at most 32-bits in size)
7394     ** and the key value (a variable length integer, may have any value).
7395     ** The first of the while(...) loops below skips over the record-length
7396     ** field. The second while(...) loop copies the key value from the
7397     ** cell on pPage into the pSpace buffer.
7398     */
7399     pCell = findCell(pPage, pPage->nCell-1);
7400     pStop = &pCell[9];
7401     while( (*(pCell++)&0x80) && pCell<pStop );
7402     pStop = &pCell[9];
7403     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7404 
7405     /* Insert the new divider cell into pParent. */
7406     if( rc==SQLITE_OK ){
7407       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7408                    0, pPage->pgno, &rc);
7409     }
7410 
7411     /* Set the right-child pointer of pParent to point to the new page. */
7412     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7413 
7414     /* Release the reference to the new page. */
7415     releasePage(pNew);
7416   }
7417 
7418   return rc;
7419 }
7420 #endif /* SQLITE_OMIT_QUICKBALANCE */
7421 
7422 #if 0
7423 /*
7424 ** This function does not contribute anything to the operation of SQLite.
7425 ** it is sometimes activated temporarily while debugging code responsible
7426 ** for setting pointer-map entries.
7427 */
7428 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7429   int i, j;
7430   for(i=0; i<nPage; i++){
7431     Pgno n;
7432     u8 e;
7433     MemPage *pPage = apPage[i];
7434     BtShared *pBt = pPage->pBt;
7435     assert( pPage->isInit );
7436 
7437     for(j=0; j<pPage->nCell; j++){
7438       CellInfo info;
7439       u8 *z;
7440 
7441       z = findCell(pPage, j);
7442       pPage->xParseCell(pPage, z, &info);
7443       if( info.nLocal<info.nPayload ){
7444         Pgno ovfl = get4byte(&z[info.nSize-4]);
7445         ptrmapGet(pBt, ovfl, &e, &n);
7446         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7447       }
7448       if( !pPage->leaf ){
7449         Pgno child = get4byte(z);
7450         ptrmapGet(pBt, child, &e, &n);
7451         assert( n==pPage->pgno && e==PTRMAP_BTREE );
7452       }
7453     }
7454     if( !pPage->leaf ){
7455       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7456       ptrmapGet(pBt, child, &e, &n);
7457       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7458     }
7459   }
7460   return 1;
7461 }
7462 #endif
7463 
7464 /*
7465 ** This function is used to copy the contents of the b-tree node stored
7466 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7467 ** the pointer-map entries for each child page are updated so that the
7468 ** parent page stored in the pointer map is page pTo. If pFrom contained
7469 ** any cells with overflow page pointers, then the corresponding pointer
7470 ** map entries are also updated so that the parent page is page pTo.
7471 **
7472 ** If pFrom is currently carrying any overflow cells (entries in the
7473 ** MemPage.apOvfl[] array), they are not copied to pTo.
7474 **
7475 ** Before returning, page pTo is reinitialized using btreeInitPage().
7476 **
7477 ** The performance of this function is not critical. It is only used by
7478 ** the balance_shallower() and balance_deeper() procedures, neither of
7479 ** which are called often under normal circumstances.
7480 */
7481 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7482   if( (*pRC)==SQLITE_OK ){
7483     BtShared * const pBt = pFrom->pBt;
7484     u8 * const aFrom = pFrom->aData;
7485     u8 * const aTo = pTo->aData;
7486     int const iFromHdr = pFrom->hdrOffset;
7487     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7488     int rc;
7489     int iData;
7490 
7491 
7492     assert( pFrom->isInit );
7493     assert( pFrom->nFree>=iToHdr );
7494     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7495 
7496     /* Copy the b-tree node content from page pFrom to page pTo. */
7497     iData = get2byte(&aFrom[iFromHdr+5]);
7498     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7499     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7500 
7501     /* Reinitialize page pTo so that the contents of the MemPage structure
7502     ** match the new data. The initialization of pTo can actually fail under
7503     ** fairly obscure circumstances, even though it is a copy of initialized
7504     ** page pFrom.
7505     */
7506     pTo->isInit = 0;
7507     rc = btreeInitPage(pTo);
7508     if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7509     if( rc!=SQLITE_OK ){
7510       *pRC = rc;
7511       return;
7512     }
7513 
7514     /* If this is an auto-vacuum database, update the pointer-map entries
7515     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7516     */
7517     if( ISAUTOVACUUM ){
7518       *pRC = setChildPtrmaps(pTo);
7519     }
7520   }
7521 }
7522 
7523 /*
7524 ** This routine redistributes cells on the iParentIdx'th child of pParent
7525 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7526 ** same amount of free space. Usually a single sibling on either side of the
7527 ** page are used in the balancing, though both siblings might come from one
7528 ** side if the page is the first or last child of its parent. If the page
7529 ** has fewer than 2 siblings (something which can only happen if the page
7530 ** is a root page or a child of a root page) then all available siblings
7531 ** participate in the balancing.
7532 **
7533 ** The number of siblings of the page might be increased or decreased by
7534 ** one or two in an effort to keep pages nearly full but not over full.
7535 **
7536 ** Note that when this routine is called, some of the cells on the page
7537 ** might not actually be stored in MemPage.aData[]. This can happen
7538 ** if the page is overfull. This routine ensures that all cells allocated
7539 ** to the page and its siblings fit into MemPage.aData[] before returning.
7540 **
7541 ** In the course of balancing the page and its siblings, cells may be
7542 ** inserted into or removed from the parent page (pParent). Doing so
7543 ** may cause the parent page to become overfull or underfull. If this
7544 ** happens, it is the responsibility of the caller to invoke the correct
7545 ** balancing routine to fix this problem (see the balance() routine).
7546 **
7547 ** If this routine fails for any reason, it might leave the database
7548 ** in a corrupted state. So if this routine fails, the database should
7549 ** be rolled back.
7550 **
7551 ** The third argument to this function, aOvflSpace, is a pointer to a
7552 ** buffer big enough to hold one page. If while inserting cells into the parent
7553 ** page (pParent) the parent page becomes overfull, this buffer is
7554 ** used to store the parent's overflow cells. Because this function inserts
7555 ** a maximum of four divider cells into the parent page, and the maximum
7556 ** size of a cell stored within an internal node is always less than 1/4
7557 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7558 ** enough for all overflow cells.
7559 **
7560 ** If aOvflSpace is set to a null pointer, this function returns
7561 ** SQLITE_NOMEM.
7562 */
7563 static int balance_nonroot(
7564   MemPage *pParent,               /* Parent page of siblings being balanced */
7565   int iParentIdx,                 /* Index of "the page" in pParent */
7566   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7567   int isRoot,                     /* True if pParent is a root-page */
7568   int bBulk                       /* True if this call is part of a bulk load */
7569 ){
7570   BtShared *pBt;               /* The whole database */
7571   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7572   int nNew = 0;                /* Number of pages in apNew[] */
7573   int nOld;                    /* Number of pages in apOld[] */
7574   int i, j, k;                 /* Loop counters */
7575   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7576   int rc = SQLITE_OK;          /* The return code */
7577   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7578   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7579   int usableSpace;             /* Bytes in pPage beyond the header */
7580   int pageFlags;               /* Value of pPage->aData[0] */
7581   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7582   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7583   int szScratch;               /* Size of scratch memory requested */
7584   MemPage *apOld[NB];          /* pPage and up to two siblings */
7585   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7586   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7587   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7588   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7589   int cntOld[NB+2];            /* Old index in b.apCell[] */
7590   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7591   u8 *aSpace1;                 /* Space for copies of dividers cells */
7592   Pgno pgno;                   /* Temp var to store a page number in */
7593   u8 abDone[NB+2];             /* True after i'th new page is populated */
7594   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7595   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7596   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7597   CellArray b;                  /* Parsed information on cells being balanced */
7598 
7599   memset(abDone, 0, sizeof(abDone));
7600   b.nCell = 0;
7601   b.apCell = 0;
7602   pBt = pParent->pBt;
7603   assert( sqlite3_mutex_held(pBt->mutex) );
7604   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7605 
7606   /* At this point pParent may have at most one overflow cell. And if
7607   ** this overflow cell is present, it must be the cell with
7608   ** index iParentIdx. This scenario comes about when this function
7609   ** is called (indirectly) from sqlite3BtreeDelete().
7610   */
7611   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7612   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7613 
7614   if( !aOvflSpace ){
7615     return SQLITE_NOMEM_BKPT;
7616   }
7617   assert( pParent->nFree>=0 );
7618 
7619   /* Find the sibling pages to balance. Also locate the cells in pParent
7620   ** that divide the siblings. An attempt is made to find NN siblings on
7621   ** either side of pPage. More siblings are taken from one side, however,
7622   ** if there are fewer than NN siblings on the other side. If pParent
7623   ** has NB or fewer children then all children of pParent are taken.
7624   **
7625   ** This loop also drops the divider cells from the parent page. This
7626   ** way, the remainder of the function does not have to deal with any
7627   ** overflow cells in the parent page, since if any existed they will
7628   ** have already been removed.
7629   */
7630   i = pParent->nOverflow + pParent->nCell;
7631   if( i<2 ){
7632     nxDiv = 0;
7633   }else{
7634     assert( bBulk==0 || bBulk==1 );
7635     if( iParentIdx==0 ){
7636       nxDiv = 0;
7637     }else if( iParentIdx==i ){
7638       nxDiv = i-2+bBulk;
7639     }else{
7640       nxDiv = iParentIdx-1;
7641     }
7642     i = 2-bBulk;
7643   }
7644   nOld = i+1;
7645   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7646     pRight = &pParent->aData[pParent->hdrOffset+8];
7647   }else{
7648     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7649   }
7650   pgno = get4byte(pRight);
7651   while( 1 ){
7652     if( rc==SQLITE_OK ){
7653       rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7654     }
7655     if( rc ){
7656       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7657       goto balance_cleanup;
7658     }
7659     if( apOld[i]->nFree<0 ){
7660       rc = btreeComputeFreeSpace(apOld[i]);
7661       if( rc ){
7662         memset(apOld, 0, (i)*sizeof(MemPage*));
7663         goto balance_cleanup;
7664       }
7665     }
7666     if( (i--)==0 ) break;
7667 
7668     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7669       apDiv[i] = pParent->apOvfl[0];
7670       pgno = get4byte(apDiv[i]);
7671       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7672       pParent->nOverflow = 0;
7673     }else{
7674       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7675       pgno = get4byte(apDiv[i]);
7676       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7677 
7678       /* Drop the cell from the parent page. apDiv[i] still points to
7679       ** the cell within the parent, even though it has been dropped.
7680       ** This is safe because dropping a cell only overwrites the first
7681       ** four bytes of it, and this function does not need the first
7682       ** four bytes of the divider cell. So the pointer is safe to use
7683       ** later on.
7684       **
7685       ** But not if we are in secure-delete mode. In secure-delete mode,
7686       ** the dropCell() routine will overwrite the entire cell with zeroes.
7687       ** In this case, temporarily copy the cell into the aOvflSpace[]
7688       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7689       ** is allocated.  */
7690       if( pBt->btsFlags & BTS_FAST_SECURE ){
7691         int iOff;
7692 
7693         /* If the following if() condition is not true, the db is corrupted.
7694         ** The call to dropCell() below will detect this.  */
7695         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7696         if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7697           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7698           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7699         }
7700       }
7701       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7702     }
7703   }
7704 
7705   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7706   ** alignment */
7707   nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
7708   nMaxCells = (nMaxCells + 3)&~3;
7709 
7710   /*
7711   ** Allocate space for memory structures
7712   */
7713   szScratch =
7714        nMaxCells*sizeof(u8*)                       /* b.apCell */
7715      + nMaxCells*sizeof(u16)                       /* b.szCell */
7716      + pBt->pageSize;                              /* aSpace1 */
7717 
7718   assert( szScratch<=7*(int)pBt->pageSize );
7719   b.apCell = sqlite3StackAllocRaw(0, szScratch );
7720   if( b.apCell==0 ){
7721     rc = SQLITE_NOMEM_BKPT;
7722     goto balance_cleanup;
7723   }
7724   b.szCell = (u16*)&b.apCell[nMaxCells];
7725   aSpace1 = (u8*)&b.szCell[nMaxCells];
7726   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7727 
7728   /*
7729   ** Load pointers to all cells on sibling pages and the divider cells
7730   ** into the local b.apCell[] array.  Make copies of the divider cells
7731   ** into space obtained from aSpace1[]. The divider cells have already
7732   ** been removed from pParent.
7733   **
7734   ** If the siblings are on leaf pages, then the child pointers of the
7735   ** divider cells are stripped from the cells before they are copied
7736   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7737   ** child pointers.  If siblings are not leaves, then all cell in
7738   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7739   ** are alike.
7740   **
7741   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7742   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7743   */
7744   b.pRef = apOld[0];
7745   leafCorrection = b.pRef->leaf*4;
7746   leafData = b.pRef->intKeyLeaf;
7747   for(i=0; i<nOld; i++){
7748     MemPage *pOld = apOld[i];
7749     int limit = pOld->nCell;
7750     u8 *aData = pOld->aData;
7751     u16 maskPage = pOld->maskPage;
7752     u8 *piCell = aData + pOld->cellOffset;
7753     u8 *piEnd;
7754     VVA_ONLY( int nCellAtStart = b.nCell; )
7755 
7756     /* Verify that all sibling pages are of the same "type" (table-leaf,
7757     ** table-interior, index-leaf, or index-interior).
7758     */
7759     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7760       rc = SQLITE_CORRUPT_BKPT;
7761       goto balance_cleanup;
7762     }
7763 
7764     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7765     ** contains overflow cells, include them in the b.apCell[] array
7766     ** in the correct spot.
7767     **
7768     ** Note that when there are multiple overflow cells, it is always the
7769     ** case that they are sequential and adjacent.  This invariant arises
7770     ** because multiple overflows can only occurs when inserting divider
7771     ** cells into a parent on a prior balance, and divider cells are always
7772     ** adjacent and are inserted in order.  There is an assert() tagged
7773     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7774     ** invariant.
7775     **
7776     ** This must be done in advance.  Once the balance starts, the cell
7777     ** offset section of the btree page will be overwritten and we will no
7778     ** long be able to find the cells if a pointer to each cell is not saved
7779     ** first.
7780     */
7781     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7782     if( pOld->nOverflow>0 ){
7783       if( NEVER(limit<pOld->aiOvfl[0]) ){
7784         rc = SQLITE_CORRUPT_BKPT;
7785         goto balance_cleanup;
7786       }
7787       limit = pOld->aiOvfl[0];
7788       for(j=0; j<limit; j++){
7789         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7790         piCell += 2;
7791         b.nCell++;
7792       }
7793       for(k=0; k<pOld->nOverflow; k++){
7794         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7795         b.apCell[b.nCell] = pOld->apOvfl[k];
7796         b.nCell++;
7797       }
7798     }
7799     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7800     while( piCell<piEnd ){
7801       assert( b.nCell<nMaxCells );
7802       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7803       piCell += 2;
7804       b.nCell++;
7805     }
7806     assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7807 
7808     cntOld[i] = b.nCell;
7809     if( i<nOld-1 && !leafData){
7810       u16 sz = (u16)szNew[i];
7811       u8 *pTemp;
7812       assert( b.nCell<nMaxCells );
7813       b.szCell[b.nCell] = sz;
7814       pTemp = &aSpace1[iSpace1];
7815       iSpace1 += sz;
7816       assert( sz<=pBt->maxLocal+23 );
7817       assert( iSpace1 <= (int)pBt->pageSize );
7818       memcpy(pTemp, apDiv[i], sz);
7819       b.apCell[b.nCell] = pTemp+leafCorrection;
7820       assert( leafCorrection==0 || leafCorrection==4 );
7821       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7822       if( !pOld->leaf ){
7823         assert( leafCorrection==0 );
7824         assert( pOld->hdrOffset==0 || CORRUPT_DB );
7825         /* The right pointer of the child page pOld becomes the left
7826         ** pointer of the divider cell */
7827         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7828       }else{
7829         assert( leafCorrection==4 );
7830         while( b.szCell[b.nCell]<4 ){
7831           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7832           ** does exist, pad it with 0x00 bytes. */
7833           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7834           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7835           aSpace1[iSpace1++] = 0x00;
7836           b.szCell[b.nCell]++;
7837         }
7838       }
7839       b.nCell++;
7840     }
7841   }
7842 
7843   /*
7844   ** Figure out the number of pages needed to hold all b.nCell cells.
7845   ** Store this number in "k".  Also compute szNew[] which is the total
7846   ** size of all cells on the i-th page and cntNew[] which is the index
7847   ** in b.apCell[] of the cell that divides page i from page i+1.
7848   ** cntNew[k] should equal b.nCell.
7849   **
7850   ** Values computed by this block:
7851   **
7852   **           k: The total number of sibling pages
7853   **    szNew[i]: Spaced used on the i-th sibling page.
7854   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7855   **              the right of the i-th sibling page.
7856   ** usableSpace: Number of bytes of space available on each sibling.
7857   **
7858   */
7859   usableSpace = pBt->usableSize - 12 + leafCorrection;
7860   for(i=k=0; i<nOld; i++, k++){
7861     MemPage *p = apOld[i];
7862     b.apEnd[k] = p->aDataEnd;
7863     b.ixNx[k] = cntOld[i];
7864     if( k && b.ixNx[k]==b.ixNx[k-1] ){
7865       k--;  /* Omit b.ixNx[] entry for child pages with no cells */
7866     }
7867     if( !leafData ){
7868       k++;
7869       b.apEnd[k] = pParent->aDataEnd;
7870       b.ixNx[k] = cntOld[i]+1;
7871     }
7872     assert( p->nFree>=0 );
7873     szNew[i] = usableSpace - p->nFree;
7874     for(j=0; j<p->nOverflow; j++){
7875       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7876     }
7877     cntNew[i] = cntOld[i];
7878   }
7879   k = nOld;
7880   for(i=0; i<k; i++){
7881     int sz;
7882     while( szNew[i]>usableSpace ){
7883       if( i+1>=k ){
7884         k = i+2;
7885         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7886         szNew[k-1] = 0;
7887         cntNew[k-1] = b.nCell;
7888       }
7889       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7890       szNew[i] -= sz;
7891       if( !leafData ){
7892         if( cntNew[i]<b.nCell ){
7893           sz = 2 + cachedCellSize(&b, cntNew[i]);
7894         }else{
7895           sz = 0;
7896         }
7897       }
7898       szNew[i+1] += sz;
7899       cntNew[i]--;
7900     }
7901     while( cntNew[i]<b.nCell ){
7902       sz = 2 + cachedCellSize(&b, cntNew[i]);
7903       if( szNew[i]+sz>usableSpace ) break;
7904       szNew[i] += sz;
7905       cntNew[i]++;
7906       if( !leafData ){
7907         if( cntNew[i]<b.nCell ){
7908           sz = 2 + cachedCellSize(&b, cntNew[i]);
7909         }else{
7910           sz = 0;
7911         }
7912       }
7913       szNew[i+1] -= sz;
7914     }
7915     if( cntNew[i]>=b.nCell ){
7916       k = i+1;
7917     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7918       rc = SQLITE_CORRUPT_BKPT;
7919       goto balance_cleanup;
7920     }
7921   }
7922 
7923   /*
7924   ** The packing computed by the previous block is biased toward the siblings
7925   ** on the left side (siblings with smaller keys). The left siblings are
7926   ** always nearly full, while the right-most sibling might be nearly empty.
7927   ** The next block of code attempts to adjust the packing of siblings to
7928   ** get a better balance.
7929   **
7930   ** This adjustment is more than an optimization.  The packing above might
7931   ** be so out of balance as to be illegal.  For example, the right-most
7932   ** sibling might be completely empty.  This adjustment is not optional.
7933   */
7934   for(i=k-1; i>0; i--){
7935     int szRight = szNew[i];  /* Size of sibling on the right */
7936     int szLeft = szNew[i-1]; /* Size of sibling on the left */
7937     int r;              /* Index of right-most cell in left sibling */
7938     int d;              /* Index of first cell to the left of right sibling */
7939 
7940     r = cntNew[i-1] - 1;
7941     d = r + 1 - leafData;
7942     (void)cachedCellSize(&b, d);
7943     do{
7944       assert( d<nMaxCells );
7945       assert( r<nMaxCells );
7946       (void)cachedCellSize(&b, r);
7947       if( szRight!=0
7948        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7949         break;
7950       }
7951       szRight += b.szCell[d] + 2;
7952       szLeft -= b.szCell[r] + 2;
7953       cntNew[i-1] = r;
7954       r--;
7955       d--;
7956     }while( r>=0 );
7957     szNew[i] = szRight;
7958     szNew[i-1] = szLeft;
7959     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7960       rc = SQLITE_CORRUPT_BKPT;
7961       goto balance_cleanup;
7962     }
7963   }
7964 
7965   /* Sanity check:  For a non-corrupt database file one of the follwing
7966   ** must be true:
7967   **    (1) We found one or more cells (cntNew[0])>0), or
7968   **    (2) pPage is a virtual root page.  A virtual root page is when
7969   **        the real root page is page 1 and we are the only child of
7970   **        that page.
7971   */
7972   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7973   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7974     apOld[0]->pgno, apOld[0]->nCell,
7975     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7976     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7977   ));
7978 
7979   /*
7980   ** Allocate k new pages.  Reuse old pages where possible.
7981   */
7982   pageFlags = apOld[0]->aData[0];
7983   for(i=0; i<k; i++){
7984     MemPage *pNew;
7985     if( i<nOld ){
7986       pNew = apNew[i] = apOld[i];
7987       apOld[i] = 0;
7988       rc = sqlite3PagerWrite(pNew->pDbPage);
7989       nNew++;
7990       if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) ){
7991         rc = SQLITE_CORRUPT_BKPT;
7992       }
7993       if( rc ) goto balance_cleanup;
7994     }else{
7995       assert( i>0 );
7996       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7997       if( rc ) goto balance_cleanup;
7998       zeroPage(pNew, pageFlags);
7999       apNew[i] = pNew;
8000       nNew++;
8001       cntOld[i] = b.nCell;
8002 
8003       /* Set the pointer-map entry for the new sibling page. */
8004       if( ISAUTOVACUUM ){
8005         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8006         if( rc!=SQLITE_OK ){
8007           goto balance_cleanup;
8008         }
8009       }
8010     }
8011   }
8012 
8013   /*
8014   ** Reassign page numbers so that the new pages are in ascending order.
8015   ** This helps to keep entries in the disk file in order so that a scan
8016   ** of the table is closer to a linear scan through the file. That in turn
8017   ** helps the operating system to deliver pages from the disk more rapidly.
8018   **
8019   ** An O(n^2) insertion sort algorithm is used, but since n is never more
8020   ** than (NB+2) (a small constant), that should not be a problem.
8021   **
8022   ** When NB==3, this one optimization makes the database about 25% faster
8023   ** for large insertions and deletions.
8024   */
8025   for(i=0; i<nNew; i++){
8026     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8027     aPgFlags[i] = apNew[i]->pDbPage->flags;
8028     for(j=0; j<i; j++){
8029       if( NEVER(aPgno[j]==aPgno[i]) ){
8030         /* This branch is taken if the set of sibling pages somehow contains
8031         ** duplicate entries. This can happen if the database is corrupt.
8032         ** It would be simpler to detect this as part of the loop below, but
8033         ** we do the detection here in order to avoid populating the pager
8034         ** cache with two separate objects associated with the same
8035         ** page number.  */
8036         assert( CORRUPT_DB );
8037         rc = SQLITE_CORRUPT_BKPT;
8038         goto balance_cleanup;
8039       }
8040     }
8041   }
8042   for(i=0; i<nNew; i++){
8043     int iBest = 0;                /* aPgno[] index of page number to use */
8044     for(j=1; j<nNew; j++){
8045       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8046     }
8047     pgno = aPgOrder[iBest];
8048     aPgOrder[iBest] = 0xffffffff;
8049     if( iBest!=i ){
8050       if( iBest>i ){
8051         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8052       }
8053       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8054       apNew[i]->pgno = pgno;
8055     }
8056   }
8057 
8058   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8059          "%d(%d nc=%d) %d(%d nc=%d)\n",
8060     apNew[0]->pgno, szNew[0], cntNew[0],
8061     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8062     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8063     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8064     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8065     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8066     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8067     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8068     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8069   ));
8070 
8071   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8072   assert( nNew>=1 && nNew<=ArraySize(apNew) );
8073   assert( apNew[nNew-1]!=0 );
8074   put4byte(pRight, apNew[nNew-1]->pgno);
8075 
8076   /* If the sibling pages are not leaves, ensure that the right-child pointer
8077   ** of the right-most new sibling page is set to the value that was
8078   ** originally in the same field of the right-most old sibling page. */
8079   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8080     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8081     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8082   }
8083 
8084   /* Make any required updates to pointer map entries associated with
8085   ** cells stored on sibling pages following the balance operation. Pointer
8086   ** map entries associated with divider cells are set by the insertCell()
8087   ** routine. The associated pointer map entries are:
8088   **
8089   **   a) if the cell contains a reference to an overflow chain, the
8090   **      entry associated with the first page in the overflow chain, and
8091   **
8092   **   b) if the sibling pages are not leaves, the child page associated
8093   **      with the cell.
8094   **
8095   ** If the sibling pages are not leaves, then the pointer map entry
8096   ** associated with the right-child of each sibling may also need to be
8097   ** updated. This happens below, after the sibling pages have been
8098   ** populated, not here.
8099   */
8100   if( ISAUTOVACUUM ){
8101     MemPage *pOld;
8102     MemPage *pNew = pOld = apNew[0];
8103     int cntOldNext = pNew->nCell + pNew->nOverflow;
8104     int iNew = 0;
8105     int iOld = 0;
8106 
8107     for(i=0; i<b.nCell; i++){
8108       u8 *pCell = b.apCell[i];
8109       while( i==cntOldNext ){
8110         iOld++;
8111         assert( iOld<nNew || iOld<nOld );
8112         assert( iOld>=0 && iOld<NB );
8113         pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8114         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8115       }
8116       if( i==cntNew[iNew] ){
8117         pNew = apNew[++iNew];
8118         if( !leafData ) continue;
8119       }
8120 
8121       /* Cell pCell is destined for new sibling page pNew. Originally, it
8122       ** was either part of sibling page iOld (possibly an overflow cell),
8123       ** or else the divider cell to the left of sibling page iOld. So,
8124       ** if sibling page iOld had the same page number as pNew, and if
8125       ** pCell really was a part of sibling page iOld (not a divider or
8126       ** overflow cell), we can skip updating the pointer map entries.  */
8127       if( iOld>=nNew
8128        || pNew->pgno!=aPgno[iOld]
8129        || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8130       ){
8131         if( !leafCorrection ){
8132           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8133         }
8134         if( cachedCellSize(&b,i)>pNew->minLocal ){
8135           ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8136         }
8137         if( rc ) goto balance_cleanup;
8138       }
8139     }
8140   }
8141 
8142   /* Insert new divider cells into pParent. */
8143   for(i=0; i<nNew-1; i++){
8144     u8 *pCell;
8145     u8 *pTemp;
8146     int sz;
8147     MemPage *pNew = apNew[i];
8148     j = cntNew[i];
8149 
8150     assert( j<nMaxCells );
8151     assert( b.apCell[j]!=0 );
8152     pCell = b.apCell[j];
8153     sz = b.szCell[j] + leafCorrection;
8154     pTemp = &aOvflSpace[iOvflSpace];
8155     if( !pNew->leaf ){
8156       memcpy(&pNew->aData[8], pCell, 4);
8157     }else if( leafData ){
8158       /* If the tree is a leaf-data tree, and the siblings are leaves,
8159       ** then there is no divider cell in b.apCell[]. Instead, the divider
8160       ** cell consists of the integer key for the right-most cell of
8161       ** the sibling-page assembled above only.
8162       */
8163       CellInfo info;
8164       j--;
8165       pNew->xParseCell(pNew, b.apCell[j], &info);
8166       pCell = pTemp;
8167       sz = 4 + putVarint(&pCell[4], info.nKey);
8168       pTemp = 0;
8169     }else{
8170       pCell -= 4;
8171       /* Obscure case for non-leaf-data trees: If the cell at pCell was
8172       ** previously stored on a leaf node, and its reported size was 4
8173       ** bytes, then it may actually be smaller than this
8174       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8175       ** any cell). But it is important to pass the correct size to
8176       ** insertCell(), so reparse the cell now.
8177       **
8178       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8179       ** and WITHOUT ROWID tables with exactly one column which is the
8180       ** primary key.
8181       */
8182       if( b.szCell[j]==4 ){
8183         assert(leafCorrection==4);
8184         sz = pParent->xCellSize(pParent, pCell);
8185       }
8186     }
8187     iOvflSpace += sz;
8188     assert( sz<=pBt->maxLocal+23 );
8189     assert( iOvflSpace <= (int)pBt->pageSize );
8190     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8191     if( rc!=SQLITE_OK ) goto balance_cleanup;
8192     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8193   }
8194 
8195   /* Now update the actual sibling pages. The order in which they are updated
8196   ** is important, as this code needs to avoid disrupting any page from which
8197   ** cells may still to be read. In practice, this means:
8198   **
8199   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8200   **      then it is not safe to update page apNew[iPg] until after
8201   **      the left-hand sibling apNew[iPg-1] has been updated.
8202   **
8203   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8204   **      then it is not safe to update page apNew[iPg] until after
8205   **      the right-hand sibling apNew[iPg+1] has been updated.
8206   **
8207   ** If neither of the above apply, the page is safe to update.
8208   **
8209   ** The iPg value in the following loop starts at nNew-1 goes down
8210   ** to 0, then back up to nNew-1 again, thus making two passes over
8211   ** the pages.  On the initial downward pass, only condition (1) above
8212   ** needs to be tested because (2) will always be true from the previous
8213   ** step.  On the upward pass, both conditions are always true, so the
8214   ** upwards pass simply processes pages that were missed on the downward
8215   ** pass.
8216   */
8217   for(i=1-nNew; i<nNew; i++){
8218     int iPg = i<0 ? -i : i;
8219     assert( iPg>=0 && iPg<nNew );
8220     if( abDone[iPg] ) continue;         /* Skip pages already processed */
8221     if( i>=0                            /* On the upwards pass, or... */
8222      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
8223     ){
8224       int iNew;
8225       int iOld;
8226       int nNewCell;
8227 
8228       /* Verify condition (1):  If cells are moving left, update iPg
8229       ** only after iPg-1 has already been updated. */
8230       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8231 
8232       /* Verify condition (2):  If cells are moving right, update iPg
8233       ** only after iPg+1 has already been updated. */
8234       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8235 
8236       if( iPg==0 ){
8237         iNew = iOld = 0;
8238         nNewCell = cntNew[0];
8239       }else{
8240         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8241         iNew = cntNew[iPg-1] + !leafData;
8242         nNewCell = cntNew[iPg] - iNew;
8243       }
8244 
8245       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8246       if( rc ) goto balance_cleanup;
8247       abDone[iPg]++;
8248       apNew[iPg]->nFree = usableSpace-szNew[iPg];
8249       assert( apNew[iPg]->nOverflow==0 );
8250       assert( apNew[iPg]->nCell==nNewCell );
8251     }
8252   }
8253 
8254   /* All pages have been processed exactly once */
8255   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8256 
8257   assert( nOld>0 );
8258   assert( nNew>0 );
8259 
8260   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8261     /* The root page of the b-tree now contains no cells. The only sibling
8262     ** page is the right-child of the parent. Copy the contents of the
8263     ** child page into the parent, decreasing the overall height of the
8264     ** b-tree structure by one. This is described as the "balance-shallower"
8265     ** sub-algorithm in some documentation.
8266     **
8267     ** If this is an auto-vacuum database, the call to copyNodeContent()
8268     ** sets all pointer-map entries corresponding to database image pages
8269     ** for which the pointer is stored within the content being copied.
8270     **
8271     ** It is critical that the child page be defragmented before being
8272     ** copied into the parent, because if the parent is page 1 then it will
8273     ** by smaller than the child due to the database header, and so all the
8274     ** free space needs to be up front.
8275     */
8276     assert( nNew==1 || CORRUPT_DB );
8277     rc = defragmentPage(apNew[0], -1);
8278     testcase( rc!=SQLITE_OK );
8279     assert( apNew[0]->nFree ==
8280         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8281           - apNew[0]->nCell*2)
8282       || rc!=SQLITE_OK
8283     );
8284     copyNodeContent(apNew[0], pParent, &rc);
8285     freePage(apNew[0], &rc);
8286   }else if( ISAUTOVACUUM && !leafCorrection ){
8287     /* Fix the pointer map entries associated with the right-child of each
8288     ** sibling page. All other pointer map entries have already been taken
8289     ** care of.  */
8290     for(i=0; i<nNew; i++){
8291       u32 key = get4byte(&apNew[i]->aData[8]);
8292       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8293     }
8294   }
8295 
8296   assert( pParent->isInit );
8297   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8298           nOld, nNew, b.nCell));
8299 
8300   /* Free any old pages that were not reused as new pages.
8301   */
8302   for(i=nNew; i<nOld; i++){
8303     freePage(apOld[i], &rc);
8304   }
8305 
8306 #if 0
8307   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8308     /* The ptrmapCheckPages() contains assert() statements that verify that
8309     ** all pointer map pages are set correctly. This is helpful while
8310     ** debugging. This is usually disabled because a corrupt database may
8311     ** cause an assert() statement to fail.  */
8312     ptrmapCheckPages(apNew, nNew);
8313     ptrmapCheckPages(&pParent, 1);
8314   }
8315 #endif
8316 
8317   /*
8318   ** Cleanup before returning.
8319   */
8320 balance_cleanup:
8321   sqlite3StackFree(0, b.apCell);
8322   for(i=0; i<nOld; i++){
8323     releasePage(apOld[i]);
8324   }
8325   for(i=0; i<nNew; i++){
8326     releasePage(apNew[i]);
8327   }
8328 
8329   return rc;
8330 }
8331 
8332 
8333 /*
8334 ** This function is called when the root page of a b-tree structure is
8335 ** overfull (has one or more overflow pages).
8336 **
8337 ** A new child page is allocated and the contents of the current root
8338 ** page, including overflow cells, are copied into the child. The root
8339 ** page is then overwritten to make it an empty page with the right-child
8340 ** pointer pointing to the new page.
8341 **
8342 ** Before returning, all pointer-map entries corresponding to pages
8343 ** that the new child-page now contains pointers to are updated. The
8344 ** entry corresponding to the new right-child pointer of the root
8345 ** page is also updated.
8346 **
8347 ** If successful, *ppChild is set to contain a reference to the child
8348 ** page and SQLITE_OK is returned. In this case the caller is required
8349 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8350 ** an error code is returned and *ppChild is set to 0.
8351 */
8352 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8353   int rc;                        /* Return value from subprocedures */
8354   MemPage *pChild = 0;           /* Pointer to a new child page */
8355   Pgno pgnoChild = 0;            /* Page number of the new child page */
8356   BtShared *pBt = pRoot->pBt;    /* The BTree */
8357 
8358   assert( pRoot->nOverflow>0 );
8359   assert( sqlite3_mutex_held(pBt->mutex) );
8360 
8361   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8362   ** page that will become the new right-child of pPage. Copy the contents
8363   ** of the node stored on pRoot into the new child page.
8364   */
8365   rc = sqlite3PagerWrite(pRoot->pDbPage);
8366   if( rc==SQLITE_OK ){
8367     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8368     copyNodeContent(pRoot, pChild, &rc);
8369     if( ISAUTOVACUUM ){
8370       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8371     }
8372   }
8373   if( rc ){
8374     *ppChild = 0;
8375     releasePage(pChild);
8376     return rc;
8377   }
8378   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8379   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8380   assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8381 
8382   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8383 
8384   /* Copy the overflow cells from pRoot to pChild */
8385   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8386          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8387   memcpy(pChild->apOvfl, pRoot->apOvfl,
8388          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8389   pChild->nOverflow = pRoot->nOverflow;
8390 
8391   /* Zero the contents of pRoot. Then install pChild as the right-child. */
8392   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8393   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8394 
8395   *ppChild = pChild;
8396   return SQLITE_OK;
8397 }
8398 
8399 /*
8400 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8401 ** on the same B-tree as pCur.
8402 **
8403 ** This can if a database is corrupt with two or more SQL tables
8404 ** pointing to the same b-tree.  If an insert occurs on one SQL table
8405 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8406 ** table linked to the same b-tree.  If the secondary insert causes a
8407 ** rebalance, that can change content out from under the cursor on the
8408 ** first SQL table, violating invariants on the first insert.
8409 */
8410 static int anotherValidCursor(BtCursor *pCur){
8411   BtCursor *pOther;
8412   for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8413     if( pOther!=pCur
8414      && pOther->eState==CURSOR_VALID
8415      && pOther->pPage==pCur->pPage
8416     ){
8417       return SQLITE_CORRUPT_BKPT;
8418     }
8419   }
8420   return SQLITE_OK;
8421 }
8422 
8423 /*
8424 ** The page that pCur currently points to has just been modified in
8425 ** some way. This function figures out if this modification means the
8426 ** tree needs to be balanced, and if so calls the appropriate balancing
8427 ** routine. Balancing routines are:
8428 **
8429 **   balance_quick()
8430 **   balance_deeper()
8431 **   balance_nonroot()
8432 */
8433 static int balance(BtCursor *pCur){
8434   int rc = SQLITE_OK;
8435   const int nMin = pCur->pBt->usableSize * 2 / 3;
8436   u8 aBalanceQuickSpace[13];
8437   u8 *pFree = 0;
8438 
8439   VVA_ONLY( int balance_quick_called = 0 );
8440   VVA_ONLY( int balance_deeper_called = 0 );
8441 
8442   do {
8443     int iPage;
8444     MemPage *pPage = pCur->pPage;
8445 
8446     if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8447     if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8448       break;
8449     }else if( (iPage = pCur->iPage)==0 ){
8450       if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8451         /* The root page of the b-tree is overfull. In this case call the
8452         ** balance_deeper() function to create a new child for the root-page
8453         ** and copy the current contents of the root-page to it. The
8454         ** next iteration of the do-loop will balance the child page.
8455         */
8456         assert( balance_deeper_called==0 );
8457         VVA_ONLY( balance_deeper_called++ );
8458         rc = balance_deeper(pPage, &pCur->apPage[1]);
8459         if( rc==SQLITE_OK ){
8460           pCur->iPage = 1;
8461           pCur->ix = 0;
8462           pCur->aiIdx[0] = 0;
8463           pCur->apPage[0] = pPage;
8464           pCur->pPage = pCur->apPage[1];
8465           assert( pCur->pPage->nOverflow );
8466         }
8467       }else{
8468         break;
8469       }
8470     }else{
8471       MemPage * const pParent = pCur->apPage[iPage-1];
8472       int const iIdx = pCur->aiIdx[iPage-1];
8473 
8474       rc = sqlite3PagerWrite(pParent->pDbPage);
8475       if( rc==SQLITE_OK && pParent->nFree<0 ){
8476         rc = btreeComputeFreeSpace(pParent);
8477       }
8478       if( rc==SQLITE_OK ){
8479 #ifndef SQLITE_OMIT_QUICKBALANCE
8480         if( pPage->intKeyLeaf
8481          && pPage->nOverflow==1
8482          && pPage->aiOvfl[0]==pPage->nCell
8483          && pParent->pgno!=1
8484          && pParent->nCell==iIdx
8485         ){
8486           /* Call balance_quick() to create a new sibling of pPage on which
8487           ** to store the overflow cell. balance_quick() inserts a new cell
8488           ** into pParent, which may cause pParent overflow. If this
8489           ** happens, the next iteration of the do-loop will balance pParent
8490           ** use either balance_nonroot() or balance_deeper(). Until this
8491           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8492           ** buffer.
8493           **
8494           ** The purpose of the following assert() is to check that only a
8495           ** single call to balance_quick() is made for each call to this
8496           ** function. If this were not verified, a subtle bug involving reuse
8497           ** of the aBalanceQuickSpace[] might sneak in.
8498           */
8499           assert( balance_quick_called==0 );
8500           VVA_ONLY( balance_quick_called++ );
8501           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8502         }else
8503 #endif
8504         {
8505           /* In this case, call balance_nonroot() to redistribute cells
8506           ** between pPage and up to 2 of its sibling pages. This involves
8507           ** modifying the contents of pParent, which may cause pParent to
8508           ** become overfull or underfull. The next iteration of the do-loop
8509           ** will balance the parent page to correct this.
8510           **
8511           ** If the parent page becomes overfull, the overflow cell or cells
8512           ** are stored in the pSpace buffer allocated immediately below.
8513           ** A subsequent iteration of the do-loop will deal with this by
8514           ** calling balance_nonroot() (balance_deeper() may be called first,
8515           ** but it doesn't deal with overflow cells - just moves them to a
8516           ** different page). Once this subsequent call to balance_nonroot()
8517           ** has completed, it is safe to release the pSpace buffer used by
8518           ** the previous call, as the overflow cell data will have been
8519           ** copied either into the body of a database page or into the new
8520           ** pSpace buffer passed to the latter call to balance_nonroot().
8521           */
8522           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8523           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8524                                pCur->hints&BTREE_BULKLOAD);
8525           if( pFree ){
8526             /* If pFree is not NULL, it points to the pSpace buffer used
8527             ** by a previous call to balance_nonroot(). Its contents are
8528             ** now stored either on real database pages or within the
8529             ** new pSpace buffer, so it may be safely freed here. */
8530             sqlite3PageFree(pFree);
8531           }
8532 
8533           /* The pSpace buffer will be freed after the next call to
8534           ** balance_nonroot(), or just before this function returns, whichever
8535           ** comes first. */
8536           pFree = pSpace;
8537         }
8538       }
8539 
8540       pPage->nOverflow = 0;
8541 
8542       /* The next iteration of the do-loop balances the parent page. */
8543       releasePage(pPage);
8544       pCur->iPage--;
8545       assert( pCur->iPage>=0 );
8546       pCur->pPage = pCur->apPage[pCur->iPage];
8547     }
8548   }while( rc==SQLITE_OK );
8549 
8550   if( pFree ){
8551     sqlite3PageFree(pFree);
8552   }
8553   return rc;
8554 }
8555 
8556 /* Overwrite content from pX into pDest.  Only do the write if the
8557 ** content is different from what is already there.
8558 */
8559 static int btreeOverwriteContent(
8560   MemPage *pPage,           /* MemPage on which writing will occur */
8561   u8 *pDest,                /* Pointer to the place to start writing */
8562   const BtreePayload *pX,   /* Source of data to write */
8563   int iOffset,              /* Offset of first byte to write */
8564   int iAmt                  /* Number of bytes to be written */
8565 ){
8566   int nData = pX->nData - iOffset;
8567   if( nData<=0 ){
8568     /* Overwritting with zeros */
8569     int i;
8570     for(i=0; i<iAmt && pDest[i]==0; i++){}
8571     if( i<iAmt ){
8572       int rc = sqlite3PagerWrite(pPage->pDbPage);
8573       if( rc ) return rc;
8574       memset(pDest + i, 0, iAmt - i);
8575     }
8576   }else{
8577     if( nData<iAmt ){
8578       /* Mixed read data and zeros at the end.  Make a recursive call
8579       ** to write the zeros then fall through to write the real data */
8580       int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8581                                  iAmt-nData);
8582       if( rc ) return rc;
8583       iAmt = nData;
8584     }
8585     if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8586       int rc = sqlite3PagerWrite(pPage->pDbPage);
8587       if( rc ) return rc;
8588       /* In a corrupt database, it is possible for the source and destination
8589       ** buffers to overlap.  This is harmless since the database is already
8590       ** corrupt but it does cause valgrind and ASAN warnings.  So use
8591       ** memmove(). */
8592       memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8593     }
8594   }
8595   return SQLITE_OK;
8596 }
8597 
8598 /*
8599 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8600 ** contained in pX.
8601 */
8602 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8603   int iOffset;                        /* Next byte of pX->pData to write */
8604   int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8605   int rc;                             /* Return code */
8606   MemPage *pPage = pCur->pPage;       /* Page being written */
8607   BtShared *pBt;                      /* Btree */
8608   Pgno ovflPgno;                      /* Next overflow page to write */
8609   u32 ovflPageSize;                   /* Size to write on overflow page */
8610 
8611   if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8612    || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8613   ){
8614     return SQLITE_CORRUPT_BKPT;
8615   }
8616   /* Overwrite the local portion first */
8617   rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8618                              0, pCur->info.nLocal);
8619   if( rc ) return rc;
8620   if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8621 
8622   /* Now overwrite the overflow pages */
8623   iOffset = pCur->info.nLocal;
8624   assert( nTotal>=0 );
8625   assert( iOffset>=0 );
8626   ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8627   pBt = pPage->pBt;
8628   ovflPageSize = pBt->usableSize - 4;
8629   do{
8630     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8631     if( rc ) return rc;
8632     if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8633       rc = SQLITE_CORRUPT_BKPT;
8634     }else{
8635       if( iOffset+ovflPageSize<(u32)nTotal ){
8636         ovflPgno = get4byte(pPage->aData);
8637       }else{
8638         ovflPageSize = nTotal - iOffset;
8639       }
8640       rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8641                                  iOffset, ovflPageSize);
8642     }
8643     sqlite3PagerUnref(pPage->pDbPage);
8644     if( rc ) return rc;
8645     iOffset += ovflPageSize;
8646   }while( iOffset<nTotal );
8647   return SQLITE_OK;
8648 }
8649 
8650 
8651 /*
8652 ** Insert a new record into the BTree.  The content of the new record
8653 ** is described by the pX object.  The pCur cursor is used only to
8654 ** define what table the record should be inserted into, and is left
8655 ** pointing at a random location.
8656 **
8657 ** For a table btree (used for rowid tables), only the pX.nKey value of
8658 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8659 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8660 ** hold the content of the row.
8661 **
8662 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8663 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8664 ** pX.pData,nData,nZero fields must be zero.
8665 **
8666 ** If the seekResult parameter is non-zero, then a successful call to
8667 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8668 ** been performed.  In other words, if seekResult!=0 then the cursor
8669 ** is currently pointing to a cell that will be adjacent to the cell
8670 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8671 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8672 ** that is larger than (pKey,nKey).
8673 **
8674 ** If seekResult==0, that means pCur is pointing at some unknown location.
8675 ** In that case, this routine must seek the cursor to the correct insertion
8676 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8677 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8678 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8679 ** to decode the key.
8680 */
8681 int sqlite3BtreeInsert(
8682   BtCursor *pCur,                /* Insert data into the table of this cursor */
8683   const BtreePayload *pX,        /* Content of the row to be inserted */
8684   int flags,                     /* True if this is likely an append */
8685   int seekResult                 /* Result of prior MovetoUnpacked() call */
8686 ){
8687   int rc;
8688   int loc = seekResult;          /* -1: before desired location  +1: after */
8689   int szNew = 0;
8690   int idx;
8691   MemPage *pPage;
8692   Btree *p = pCur->pBtree;
8693   BtShared *pBt = p->pBt;
8694   unsigned char *oldCell;
8695   unsigned char *newCell = 0;
8696 
8697   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8698   assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8699 
8700   if( pCur->eState==CURSOR_FAULT ){
8701     assert( pCur->skipNext!=SQLITE_OK );
8702     return pCur->skipNext;
8703   }
8704 
8705   assert( cursorOwnsBtShared(pCur) );
8706   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8707               && pBt->inTransaction==TRANS_WRITE
8708               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8709   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8710 
8711   /* Assert that the caller has been consistent. If this cursor was opened
8712   ** expecting an index b-tree, then the caller should be inserting blob
8713   ** keys with no associated data. If the cursor was opened expecting an
8714   ** intkey table, the caller should be inserting integer keys with a
8715   ** blob of associated data.  */
8716   assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
8717 
8718   /* Save the positions of any other cursors open on this table.
8719   **
8720   ** In some cases, the call to btreeMoveto() below is a no-op. For
8721   ** example, when inserting data into a table with auto-generated integer
8722   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8723   ** integer key to use. It then calls this function to actually insert the
8724   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8725   ** that the cursor is already where it needs to be and returns without
8726   ** doing any work. To avoid thwarting these optimizations, it is important
8727   ** not to clear the cursor here.
8728   */
8729   if( pCur->curFlags & BTCF_Multiple ){
8730     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8731     if( rc ) return rc;
8732     if( loc && pCur->iPage<0 ){
8733       /* This can only happen if the schema is corrupt such that there is more
8734       ** than one table or index with the same root page as used by the cursor.
8735       ** Which can only happen if the SQLITE_NoSchemaError flag was set when
8736       ** the schema was loaded. This cannot be asserted though, as a user might
8737       ** set the flag, load the schema, and then unset the flag.  */
8738       return SQLITE_CORRUPT_BKPT;
8739     }
8740   }
8741 
8742   if( pCur->pKeyInfo==0 ){
8743     assert( pX->pKey==0 );
8744     /* If this is an insert into a table b-tree, invalidate any incrblob
8745     ** cursors open on the row being replaced */
8746     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8747 
8748     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8749     ** to a row with the same key as the new entry being inserted.
8750     */
8751 #ifdef SQLITE_DEBUG
8752     if( flags & BTREE_SAVEPOSITION ){
8753       assert( pCur->curFlags & BTCF_ValidNKey );
8754       assert( pX->nKey==pCur->info.nKey );
8755       assert( loc==0 );
8756     }
8757 #endif
8758 
8759     /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8760     ** that the cursor is not pointing to a row to be overwritten.
8761     ** So do a complete check.
8762     */
8763     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8764       /* The cursor is pointing to the entry that is to be
8765       ** overwritten */
8766       assert( pX->nData>=0 && pX->nZero>=0 );
8767       if( pCur->info.nSize!=0
8768        && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8769       ){
8770         /* New entry is the same size as the old.  Do an overwrite */
8771         return btreeOverwriteCell(pCur, pX);
8772       }
8773       assert( loc==0 );
8774     }else if( loc==0 ){
8775       /* The cursor is *not* pointing to the cell to be overwritten, nor
8776       ** to an adjacent cell.  Move the cursor so that it is pointing either
8777       ** to the cell to be overwritten or an adjacent cell.
8778       */
8779       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8780       if( rc ) return rc;
8781     }
8782   }else{
8783     /* This is an index or a WITHOUT ROWID table */
8784 
8785     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8786     ** to a row with the same key as the new entry being inserted.
8787     */
8788     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8789 
8790     /* If the cursor is not already pointing either to the cell to be
8791     ** overwritten, or if a new cell is being inserted, if the cursor is
8792     ** not pointing to an immediately adjacent cell, then move the cursor
8793     ** so that it does.
8794     */
8795     if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8796       if( pX->nMem ){
8797         UnpackedRecord r;
8798         r.pKeyInfo = pCur->pKeyInfo;
8799         r.aMem = pX->aMem;
8800         r.nField = pX->nMem;
8801         r.default_rc = 0;
8802         r.errCode = 0;
8803         r.r1 = 0;
8804         r.r2 = 0;
8805         r.eqSeen = 0;
8806         rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8807       }else{
8808         rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8809       }
8810       if( rc ) return rc;
8811     }
8812 
8813     /* If the cursor is currently pointing to an entry to be overwritten
8814     ** and the new content is the same as as the old, then use the
8815     ** overwrite optimization.
8816     */
8817     if( loc==0 ){
8818       getCellInfo(pCur);
8819       if( pCur->info.nKey==pX->nKey ){
8820         BtreePayload x2;
8821         x2.pData = pX->pKey;
8822         x2.nData = pX->nKey;
8823         x2.nZero = 0;
8824         return btreeOverwriteCell(pCur, &x2);
8825       }
8826     }
8827   }
8828   assert( pCur->eState==CURSOR_VALID
8829        || (pCur->eState==CURSOR_INVALID && loc)
8830        || CORRUPT_DB );
8831 
8832   pPage = pCur->pPage;
8833   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8834   assert( pPage->leaf || !pPage->intKey );
8835   if( pPage->nFree<0 ){
8836     if( NEVER(pCur->eState>CURSOR_INVALID) ){
8837       rc = SQLITE_CORRUPT_BKPT;
8838     }else{
8839       rc = btreeComputeFreeSpace(pPage);
8840     }
8841     if( rc ) return rc;
8842   }
8843 
8844   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8845           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8846           loc==0 ? "overwrite" : "new entry"));
8847   assert( pPage->isInit );
8848   newCell = pBt->pTmpSpace;
8849   assert( newCell!=0 );
8850   if( flags & BTREE_PREFORMAT ){
8851     rc = SQLITE_OK;
8852     szNew = pBt->nPreformatSize;
8853     if( szNew<4 ) szNew = 4;
8854     if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
8855       CellInfo info;
8856       pPage->xParseCell(pPage, newCell, &info);
8857       if( info.nPayload!=info.nLocal ){
8858         Pgno ovfl = get4byte(&newCell[szNew-4]);
8859         ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
8860       }
8861     }
8862   }else{
8863     rc = fillInCell(pPage, newCell, pX, &szNew);
8864   }
8865   if( rc ) goto end_insert;
8866   assert( szNew==pPage->xCellSize(pPage, newCell) );
8867   assert( szNew <= MX_CELL_SIZE(pBt) );
8868   idx = pCur->ix;
8869   if( loc==0 ){
8870     CellInfo info;
8871     assert( idx<pPage->nCell );
8872     rc = sqlite3PagerWrite(pPage->pDbPage);
8873     if( rc ){
8874       goto end_insert;
8875     }
8876     oldCell = findCell(pPage, idx);
8877     if( !pPage->leaf ){
8878       memcpy(newCell, oldCell, 4);
8879     }
8880     rc = clearCell(pPage, oldCell, &info);
8881     testcase( pCur->curFlags & BTCF_ValidOvfl );
8882     invalidateOverflowCache(pCur);
8883     if( info.nSize==szNew && info.nLocal==info.nPayload
8884      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8885     ){
8886       /* Overwrite the old cell with the new if they are the same size.
8887       ** We could also try to do this if the old cell is smaller, then add
8888       ** the leftover space to the free list.  But experiments show that
8889       ** doing that is no faster then skipping this optimization and just
8890       ** calling dropCell() and insertCell().
8891       **
8892       ** This optimization cannot be used on an autovacuum database if the
8893       ** new entry uses overflow pages, as the insertCell() call below is
8894       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
8895       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8896       if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
8897         return SQLITE_CORRUPT_BKPT;
8898       }
8899       if( oldCell+szNew > pPage->aDataEnd ){
8900         return SQLITE_CORRUPT_BKPT;
8901       }
8902       memcpy(oldCell, newCell, szNew);
8903       return SQLITE_OK;
8904     }
8905     dropCell(pPage, idx, info.nSize, &rc);
8906     if( rc ) goto end_insert;
8907   }else if( loc<0 && pPage->nCell>0 ){
8908     assert( pPage->leaf );
8909     idx = ++pCur->ix;
8910     pCur->curFlags &= ~BTCF_ValidNKey;
8911   }else{
8912     assert( pPage->leaf );
8913   }
8914   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8915   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8916   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8917 
8918   /* If no error has occurred and pPage has an overflow cell, call balance()
8919   ** to redistribute the cells within the tree. Since balance() may move
8920   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8921   ** variables.
8922   **
8923   ** Previous versions of SQLite called moveToRoot() to move the cursor
8924   ** back to the root page as balance() used to invalidate the contents
8925   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8926   ** set the cursor state to "invalid". This makes common insert operations
8927   ** slightly faster.
8928   **
8929   ** There is a subtle but important optimization here too. When inserting
8930   ** multiple records into an intkey b-tree using a single cursor (as can
8931   ** happen while processing an "INSERT INTO ... SELECT" statement), it
8932   ** is advantageous to leave the cursor pointing to the last entry in
8933   ** the b-tree if possible. If the cursor is left pointing to the last
8934   ** entry in the table, and the next row inserted has an integer key
8935   ** larger than the largest existing key, it is possible to insert the
8936   ** row without seeking the cursor. This can be a big performance boost.
8937   */
8938   pCur->info.nSize = 0;
8939   if( pPage->nOverflow ){
8940     assert( rc==SQLITE_OK );
8941     pCur->curFlags &= ~(BTCF_ValidNKey);
8942     rc = balance(pCur);
8943 
8944     /* Must make sure nOverflow is reset to zero even if the balance()
8945     ** fails. Internal data structure corruption will result otherwise.
8946     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8947     ** from trying to save the current position of the cursor.  */
8948     pCur->pPage->nOverflow = 0;
8949     pCur->eState = CURSOR_INVALID;
8950     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8951       btreeReleaseAllCursorPages(pCur);
8952       if( pCur->pKeyInfo ){
8953         assert( pCur->pKey==0 );
8954         pCur->pKey = sqlite3Malloc( pX->nKey );
8955         if( pCur->pKey==0 ){
8956           rc = SQLITE_NOMEM;
8957         }else{
8958           memcpy(pCur->pKey, pX->pKey, pX->nKey);
8959         }
8960       }
8961       pCur->eState = CURSOR_REQUIRESEEK;
8962       pCur->nKey = pX->nKey;
8963     }
8964   }
8965   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8966 
8967 end_insert:
8968   return rc;
8969 }
8970 
8971 /*
8972 ** This function is used as part of copying the current row from cursor
8973 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
8974 ** parameter iKey is used as the rowid value when the record is copied
8975 ** into pDest. Otherwise, the record is copied verbatim.
8976 **
8977 ** This function does not actually write the new value to cursor pDest.
8978 ** Instead, it creates and populates any required overflow pages and
8979 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
8980 ** for the destination database. The size of the cell, in bytes, is left
8981 ** in BtShared.nPreformatSize. The caller completes the insertion by
8982 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
8983 **
8984 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
8985 */
8986 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
8987   int rc = SQLITE_OK;
8988   BtShared *pBt = pDest->pBt;
8989   u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
8990   const u8 *aIn;                /* Pointer to next input buffer */
8991   u32 nIn;                      /* Size of input buffer aIn[] */
8992   u32 nRem;                     /* Bytes of data still to copy */
8993 
8994   getCellInfo(pSrc);
8995   aOut += putVarint32(aOut, pSrc->info.nPayload);
8996   if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
8997   nIn = pSrc->info.nLocal;
8998   aIn = pSrc->info.pPayload;
8999   if( aIn+nIn>pSrc->pPage->aDataEnd ){
9000     return SQLITE_CORRUPT_BKPT;
9001   }
9002   nRem = pSrc->info.nPayload;
9003   if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9004     memcpy(aOut, aIn, nIn);
9005     pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9006   }else{
9007     Pager *pSrcPager = pSrc->pBt->pPager;
9008     u8 *pPgnoOut = 0;
9009     Pgno ovflIn = 0;
9010     DbPage *pPageIn = 0;
9011     MemPage *pPageOut = 0;
9012     u32 nOut;                     /* Size of output buffer aOut[] */
9013 
9014     nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9015     pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9016     if( nOut<pSrc->info.nPayload ){
9017       pPgnoOut = &aOut[nOut];
9018       pBt->nPreformatSize += 4;
9019     }
9020 
9021     if( nRem>nIn ){
9022       if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9023         return SQLITE_CORRUPT_BKPT;
9024       }
9025       ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9026     }
9027 
9028     do {
9029       nRem -= nOut;
9030       do{
9031         assert( nOut>0 );
9032         if( nIn>0 ){
9033           int nCopy = MIN(nOut, nIn);
9034           memcpy(aOut, aIn, nCopy);
9035           nOut -= nCopy;
9036           nIn -= nCopy;
9037           aOut += nCopy;
9038           aIn += nCopy;
9039         }
9040         if( nOut>0 ){
9041           sqlite3PagerUnref(pPageIn);
9042           pPageIn = 0;
9043           rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9044           if( rc==SQLITE_OK ){
9045             aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9046             ovflIn = get4byte(aIn);
9047             aIn += 4;
9048             nIn = pSrc->pBt->usableSize - 4;
9049           }
9050         }
9051       }while( rc==SQLITE_OK && nOut>0 );
9052 
9053       if( rc==SQLITE_OK && nRem>0 ){
9054         Pgno pgnoNew;
9055         MemPage *pNew = 0;
9056         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9057         put4byte(pPgnoOut, pgnoNew);
9058         if( ISAUTOVACUUM && pPageOut ){
9059           ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9060         }
9061         releasePage(pPageOut);
9062         pPageOut = pNew;
9063         if( pPageOut ){
9064           pPgnoOut = pPageOut->aData;
9065           put4byte(pPgnoOut, 0);
9066           aOut = &pPgnoOut[4];
9067           nOut = MIN(pBt->usableSize - 4, nRem);
9068         }
9069       }
9070     }while( nRem>0 && rc==SQLITE_OK );
9071 
9072     releasePage(pPageOut);
9073     sqlite3PagerUnref(pPageIn);
9074   }
9075 
9076   return rc;
9077 }
9078 
9079 /*
9080 ** Delete the entry that the cursor is pointing to.
9081 **
9082 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9083 ** the cursor is left pointing at an arbitrary location after the delete.
9084 ** But if that bit is set, then the cursor is left in a state such that
9085 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9086 ** as it would have been on if the call to BtreeDelete() had been omitted.
9087 **
9088 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9089 ** associated with a single table entry and its indexes.  Only one of those
9090 ** deletes is considered the "primary" delete.  The primary delete occurs
9091 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
9092 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9093 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9094 ** but which might be used by alternative storage engines.
9095 */
9096 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9097   Btree *p = pCur->pBtree;
9098   BtShared *pBt = p->pBt;
9099   int rc;                              /* Return code */
9100   MemPage *pPage;                      /* Page to delete cell from */
9101   unsigned char *pCell;                /* Pointer to cell to delete */
9102   int iCellIdx;                        /* Index of cell to delete */
9103   int iCellDepth;                      /* Depth of node containing pCell */
9104   CellInfo info;                       /* Size of the cell being deleted */
9105   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
9106   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
9107 
9108   assert( cursorOwnsBtShared(pCur) );
9109   assert( pBt->inTransaction==TRANS_WRITE );
9110   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9111   assert( pCur->curFlags & BTCF_WriteFlag );
9112   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9113   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9114   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9115   if( pCur->eState==CURSOR_REQUIRESEEK ){
9116     rc = btreeRestoreCursorPosition(pCur);
9117     assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9118     if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9119   }
9120   assert( CORRUPT_DB || pCur->eState==CURSOR_VALID );
9121 
9122   iCellDepth = pCur->iPage;
9123   iCellIdx = pCur->ix;
9124   pPage = pCur->pPage;
9125   pCell = findCell(pPage, iCellIdx);
9126   if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
9127 
9128   /* If the bPreserve flag is set to true, then the cursor position must
9129   ** be preserved following this delete operation. If the current delete
9130   ** will cause a b-tree rebalance, then this is done by saving the cursor
9131   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9132   ** returning.
9133   **
9134   ** Or, if the current delete will not cause a rebalance, then the cursor
9135   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9136   ** before or after the deleted entry. In this case set bSkipnext to true.  */
9137   if( bPreserve ){
9138     if( !pPage->leaf
9139      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9140      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
9141     ){
9142       /* A b-tree rebalance will be required after deleting this entry.
9143       ** Save the cursor key.  */
9144       rc = saveCursorKey(pCur);
9145       if( rc ) return rc;
9146     }else{
9147       bSkipnext = 1;
9148     }
9149   }
9150 
9151   /* If the page containing the entry to delete is not a leaf page, move
9152   ** the cursor to the largest entry in the tree that is smaller than
9153   ** the entry being deleted. This cell will replace the cell being deleted
9154   ** from the internal node. The 'previous' entry is used for this instead
9155   ** of the 'next' entry, as the previous entry is always a part of the
9156   ** sub-tree headed by the child page of the cell being deleted. This makes
9157   ** balancing the tree following the delete operation easier.  */
9158   if( !pPage->leaf ){
9159     rc = sqlite3BtreePrevious(pCur, 0);
9160     assert( rc!=SQLITE_DONE );
9161     if( rc ) return rc;
9162   }
9163 
9164   /* Save the positions of any other cursors open on this table before
9165   ** making any modifications.  */
9166   if( pCur->curFlags & BTCF_Multiple ){
9167     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9168     if( rc ) return rc;
9169   }
9170 
9171   /* If this is a delete operation to remove a row from a table b-tree,
9172   ** invalidate any incrblob cursors open on the row being deleted.  */
9173   if( pCur->pKeyInfo==0 ){
9174     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9175   }
9176 
9177   /* Make the page containing the entry to be deleted writable. Then free any
9178   ** overflow pages associated with the entry and finally remove the cell
9179   ** itself from within the page.  */
9180   rc = sqlite3PagerWrite(pPage->pDbPage);
9181   if( rc ) return rc;
9182   rc = clearCell(pPage, pCell, &info);
9183   dropCell(pPage, iCellIdx, info.nSize, &rc);
9184   if( rc ) return rc;
9185 
9186   /* If the cell deleted was not located on a leaf page, then the cursor
9187   ** is currently pointing to the largest entry in the sub-tree headed
9188   ** by the child-page of the cell that was just deleted from an internal
9189   ** node. The cell from the leaf node needs to be moved to the internal
9190   ** node to replace the deleted cell.  */
9191   if( !pPage->leaf ){
9192     MemPage *pLeaf = pCur->pPage;
9193     int nCell;
9194     Pgno n;
9195     unsigned char *pTmp;
9196 
9197     if( pLeaf->nFree<0 ){
9198       rc = btreeComputeFreeSpace(pLeaf);
9199       if( rc ) return rc;
9200     }
9201     if( iCellDepth<pCur->iPage-1 ){
9202       n = pCur->apPage[iCellDepth+1]->pgno;
9203     }else{
9204       n = pCur->pPage->pgno;
9205     }
9206     pCell = findCell(pLeaf, pLeaf->nCell-1);
9207     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9208     nCell = pLeaf->xCellSize(pLeaf, pCell);
9209     assert( MX_CELL_SIZE(pBt) >= nCell );
9210     pTmp = pBt->pTmpSpace;
9211     assert( pTmp!=0 );
9212     rc = sqlite3PagerWrite(pLeaf->pDbPage);
9213     if( rc==SQLITE_OK ){
9214       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9215     }
9216     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9217     if( rc ) return rc;
9218   }
9219 
9220   /* Balance the tree. If the entry deleted was located on a leaf page,
9221   ** then the cursor still points to that page. In this case the first
9222   ** call to balance() repairs the tree, and the if(...) condition is
9223   ** never true.
9224   **
9225   ** Otherwise, if the entry deleted was on an internal node page, then
9226   ** pCur is pointing to the leaf page from which a cell was removed to
9227   ** replace the cell deleted from the internal node. This is slightly
9228   ** tricky as the leaf node may be underfull, and the internal node may
9229   ** be either under or overfull. In this case run the balancing algorithm
9230   ** on the leaf node first. If the balance proceeds far enough up the
9231   ** tree that we can be sure that any problem in the internal node has
9232   ** been corrected, so be it. Otherwise, after balancing the leaf node,
9233   ** walk the cursor up the tree to the internal node and balance it as
9234   ** well.  */
9235   rc = balance(pCur);
9236   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9237     releasePageNotNull(pCur->pPage);
9238     pCur->iPage--;
9239     while( pCur->iPage>iCellDepth ){
9240       releasePage(pCur->apPage[pCur->iPage--]);
9241     }
9242     pCur->pPage = pCur->apPage[pCur->iPage];
9243     rc = balance(pCur);
9244   }
9245 
9246   if( rc==SQLITE_OK ){
9247     if( bSkipnext ){
9248       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9249       assert( pPage==pCur->pPage || CORRUPT_DB );
9250       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9251       pCur->eState = CURSOR_SKIPNEXT;
9252       if( iCellIdx>=pPage->nCell ){
9253         pCur->skipNext = -1;
9254         pCur->ix = pPage->nCell-1;
9255       }else{
9256         pCur->skipNext = 1;
9257       }
9258     }else{
9259       rc = moveToRoot(pCur);
9260       if( bPreserve ){
9261         btreeReleaseAllCursorPages(pCur);
9262         pCur->eState = CURSOR_REQUIRESEEK;
9263       }
9264       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9265     }
9266   }
9267   return rc;
9268 }
9269 
9270 /*
9271 ** Create a new BTree table.  Write into *piTable the page
9272 ** number for the root page of the new table.
9273 **
9274 ** The type of type is determined by the flags parameter.  Only the
9275 ** following values of flags are currently in use.  Other values for
9276 ** flags might not work:
9277 **
9278 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
9279 **     BTREE_ZERODATA                  Used for SQL indices
9280 */
9281 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9282   BtShared *pBt = p->pBt;
9283   MemPage *pRoot;
9284   Pgno pgnoRoot;
9285   int rc;
9286   int ptfFlags;          /* Page-type flage for the root page of new table */
9287 
9288   assert( sqlite3BtreeHoldsMutex(p) );
9289   assert( pBt->inTransaction==TRANS_WRITE );
9290   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9291 
9292 #ifdef SQLITE_OMIT_AUTOVACUUM
9293   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9294   if( rc ){
9295     return rc;
9296   }
9297 #else
9298   if( pBt->autoVacuum ){
9299     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
9300     MemPage *pPageMove; /* The page to move to. */
9301 
9302     /* Creating a new table may probably require moving an existing database
9303     ** to make room for the new tables root page. In case this page turns
9304     ** out to be an overflow page, delete all overflow page-map caches
9305     ** held by open cursors.
9306     */
9307     invalidateAllOverflowCache(pBt);
9308 
9309     /* Read the value of meta[3] from the database to determine where the
9310     ** root page of the new table should go. meta[3] is the largest root-page
9311     ** created so far, so the new root-page is (meta[3]+1).
9312     */
9313     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9314     if( pgnoRoot>btreePagecount(pBt) ){
9315       return SQLITE_CORRUPT_BKPT;
9316     }
9317     pgnoRoot++;
9318 
9319     /* The new root-page may not be allocated on a pointer-map page, or the
9320     ** PENDING_BYTE page.
9321     */
9322     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9323         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9324       pgnoRoot++;
9325     }
9326     assert( pgnoRoot>=3 );
9327 
9328     /* Allocate a page. The page that currently resides at pgnoRoot will
9329     ** be moved to the allocated page (unless the allocated page happens
9330     ** to reside at pgnoRoot).
9331     */
9332     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9333     if( rc!=SQLITE_OK ){
9334       return rc;
9335     }
9336 
9337     if( pgnoMove!=pgnoRoot ){
9338       /* pgnoRoot is the page that will be used for the root-page of
9339       ** the new table (assuming an error did not occur). But we were
9340       ** allocated pgnoMove. If required (i.e. if it was not allocated
9341       ** by extending the file), the current page at position pgnoMove
9342       ** is already journaled.
9343       */
9344       u8 eType = 0;
9345       Pgno iPtrPage = 0;
9346 
9347       /* Save the positions of any open cursors. This is required in
9348       ** case they are holding a reference to an xFetch reference
9349       ** corresponding to page pgnoRoot.  */
9350       rc = saveAllCursors(pBt, 0, 0);
9351       releasePage(pPageMove);
9352       if( rc!=SQLITE_OK ){
9353         return rc;
9354       }
9355 
9356       /* Move the page currently at pgnoRoot to pgnoMove. */
9357       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9358       if( rc!=SQLITE_OK ){
9359         return rc;
9360       }
9361       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9362       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9363         rc = SQLITE_CORRUPT_BKPT;
9364       }
9365       if( rc!=SQLITE_OK ){
9366         releasePage(pRoot);
9367         return rc;
9368       }
9369       assert( eType!=PTRMAP_ROOTPAGE );
9370       assert( eType!=PTRMAP_FREEPAGE );
9371       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9372       releasePage(pRoot);
9373 
9374       /* Obtain the page at pgnoRoot */
9375       if( rc!=SQLITE_OK ){
9376         return rc;
9377       }
9378       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9379       if( rc!=SQLITE_OK ){
9380         return rc;
9381       }
9382       rc = sqlite3PagerWrite(pRoot->pDbPage);
9383       if( rc!=SQLITE_OK ){
9384         releasePage(pRoot);
9385         return rc;
9386       }
9387     }else{
9388       pRoot = pPageMove;
9389     }
9390 
9391     /* Update the pointer-map and meta-data with the new root-page number. */
9392     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9393     if( rc ){
9394       releasePage(pRoot);
9395       return rc;
9396     }
9397 
9398     /* When the new root page was allocated, page 1 was made writable in
9399     ** order either to increase the database filesize, or to decrement the
9400     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9401     */
9402     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9403     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9404     if( NEVER(rc) ){
9405       releasePage(pRoot);
9406       return rc;
9407     }
9408 
9409   }else{
9410     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9411     if( rc ) return rc;
9412   }
9413 #endif
9414   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9415   if( createTabFlags & BTREE_INTKEY ){
9416     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9417   }else{
9418     ptfFlags = PTF_ZERODATA | PTF_LEAF;
9419   }
9420   zeroPage(pRoot, ptfFlags);
9421   sqlite3PagerUnref(pRoot->pDbPage);
9422   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9423   *piTable = pgnoRoot;
9424   return SQLITE_OK;
9425 }
9426 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9427   int rc;
9428   sqlite3BtreeEnter(p);
9429   rc = btreeCreateTable(p, piTable, flags);
9430   sqlite3BtreeLeave(p);
9431   return rc;
9432 }
9433 
9434 /*
9435 ** Erase the given database page and all its children.  Return
9436 ** the page to the freelist.
9437 */
9438 static int clearDatabasePage(
9439   BtShared *pBt,           /* The BTree that contains the table */
9440   Pgno pgno,               /* Page number to clear */
9441   int freePageFlag,        /* Deallocate page if true */
9442   int *pnChange            /* Add number of Cells freed to this counter */
9443 ){
9444   MemPage *pPage;
9445   int rc;
9446   unsigned char *pCell;
9447   int i;
9448   int hdr;
9449   CellInfo info;
9450 
9451   assert( sqlite3_mutex_held(pBt->mutex) );
9452   if( pgno>btreePagecount(pBt) ){
9453     return SQLITE_CORRUPT_BKPT;
9454   }
9455   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9456   if( rc ) return rc;
9457   if( pPage->bBusy ){
9458     rc = SQLITE_CORRUPT_BKPT;
9459     goto cleardatabasepage_out;
9460   }
9461   pPage->bBusy = 1;
9462   hdr = pPage->hdrOffset;
9463   for(i=0; i<pPage->nCell; i++){
9464     pCell = findCell(pPage, i);
9465     if( !pPage->leaf ){
9466       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9467       if( rc ) goto cleardatabasepage_out;
9468     }
9469     rc = clearCell(pPage, pCell, &info);
9470     if( rc ) goto cleardatabasepage_out;
9471   }
9472   if( !pPage->leaf ){
9473     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9474     if( rc ) goto cleardatabasepage_out;
9475   }else if( pnChange ){
9476     assert( pPage->intKey || CORRUPT_DB );
9477     testcase( !pPage->intKey );
9478     *pnChange += pPage->nCell;
9479   }
9480   if( freePageFlag ){
9481     freePage(pPage, &rc);
9482   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9483     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9484   }
9485 
9486 cleardatabasepage_out:
9487   pPage->bBusy = 0;
9488   releasePage(pPage);
9489   return rc;
9490 }
9491 
9492 /*
9493 ** Delete all information from a single table in the database.  iTable is
9494 ** the page number of the root of the table.  After this routine returns,
9495 ** the root page is empty, but still exists.
9496 **
9497 ** This routine will fail with SQLITE_LOCKED if there are any open
9498 ** read cursors on the table.  Open write cursors are moved to the
9499 ** root of the table.
9500 **
9501 ** If pnChange is not NULL, then table iTable must be an intkey table. The
9502 ** integer value pointed to by pnChange is incremented by the number of
9503 ** entries in the table.
9504 */
9505 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
9506   int rc;
9507   BtShared *pBt = p->pBt;
9508   sqlite3BtreeEnter(p);
9509   assert( p->inTrans==TRANS_WRITE );
9510 
9511   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9512 
9513   if( SQLITE_OK==rc ){
9514     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9515     ** is the root of a table b-tree - if it is not, the following call is
9516     ** a no-op).  */
9517     invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9518     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9519   }
9520   sqlite3BtreeLeave(p);
9521   return rc;
9522 }
9523 
9524 /*
9525 ** Delete all information from the single table that pCur is open on.
9526 **
9527 ** This routine only work for pCur on an ephemeral table.
9528 */
9529 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9530   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9531 }
9532 
9533 /*
9534 ** Erase all information in a table and add the root of the table to
9535 ** the freelist.  Except, the root of the principle table (the one on
9536 ** page 1) is never added to the freelist.
9537 **
9538 ** This routine will fail with SQLITE_LOCKED if there are any open
9539 ** cursors on the table.
9540 **
9541 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9542 ** root page in the database file, then the last root page
9543 ** in the database file is moved into the slot formerly occupied by
9544 ** iTable and that last slot formerly occupied by the last root page
9545 ** is added to the freelist instead of iTable.  In this say, all
9546 ** root pages are kept at the beginning of the database file, which
9547 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
9548 ** page number that used to be the last root page in the file before
9549 ** the move.  If no page gets moved, *piMoved is set to 0.
9550 ** The last root page is recorded in meta[3] and the value of
9551 ** meta[3] is updated by this procedure.
9552 */
9553 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9554   int rc;
9555   MemPage *pPage = 0;
9556   BtShared *pBt = p->pBt;
9557 
9558   assert( sqlite3BtreeHoldsMutex(p) );
9559   assert( p->inTrans==TRANS_WRITE );
9560   assert( iTable>=2 );
9561   if( iTable>btreePagecount(pBt) ){
9562     return SQLITE_CORRUPT_BKPT;
9563   }
9564 
9565   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9566   if( rc ) return rc;
9567   rc = sqlite3BtreeClearTable(p, iTable, 0);
9568   if( rc ){
9569     releasePage(pPage);
9570     return rc;
9571   }
9572 
9573   *piMoved = 0;
9574 
9575 #ifdef SQLITE_OMIT_AUTOVACUUM
9576   freePage(pPage, &rc);
9577   releasePage(pPage);
9578 #else
9579   if( pBt->autoVacuum ){
9580     Pgno maxRootPgno;
9581     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9582 
9583     if( iTable==maxRootPgno ){
9584       /* If the table being dropped is the table with the largest root-page
9585       ** number in the database, put the root page on the free list.
9586       */
9587       freePage(pPage, &rc);
9588       releasePage(pPage);
9589       if( rc!=SQLITE_OK ){
9590         return rc;
9591       }
9592     }else{
9593       /* The table being dropped does not have the largest root-page
9594       ** number in the database. So move the page that does into the
9595       ** gap left by the deleted root-page.
9596       */
9597       MemPage *pMove;
9598       releasePage(pPage);
9599       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9600       if( rc!=SQLITE_OK ){
9601         return rc;
9602       }
9603       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9604       releasePage(pMove);
9605       if( rc!=SQLITE_OK ){
9606         return rc;
9607       }
9608       pMove = 0;
9609       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9610       freePage(pMove, &rc);
9611       releasePage(pMove);
9612       if( rc!=SQLITE_OK ){
9613         return rc;
9614       }
9615       *piMoved = maxRootPgno;
9616     }
9617 
9618     /* Set the new 'max-root-page' value in the database header. This
9619     ** is the old value less one, less one more if that happens to
9620     ** be a root-page number, less one again if that is the
9621     ** PENDING_BYTE_PAGE.
9622     */
9623     maxRootPgno--;
9624     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9625            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9626       maxRootPgno--;
9627     }
9628     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9629 
9630     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9631   }else{
9632     freePage(pPage, &rc);
9633     releasePage(pPage);
9634   }
9635 #endif
9636   return rc;
9637 }
9638 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9639   int rc;
9640   sqlite3BtreeEnter(p);
9641   rc = btreeDropTable(p, iTable, piMoved);
9642   sqlite3BtreeLeave(p);
9643   return rc;
9644 }
9645 
9646 
9647 /*
9648 ** This function may only be called if the b-tree connection already
9649 ** has a read or write transaction open on the database.
9650 **
9651 ** Read the meta-information out of a database file.  Meta[0]
9652 ** is the number of free pages currently in the database.  Meta[1]
9653 ** through meta[15] are available for use by higher layers.  Meta[0]
9654 ** is read-only, the others are read/write.
9655 **
9656 ** The schema layer numbers meta values differently.  At the schema
9657 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9658 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
9659 **
9660 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
9661 ** of reading the value out of the header, it instead loads the "DataVersion"
9662 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
9663 ** database file.  It is a number computed by the pager.  But its access
9664 ** pattern is the same as header meta values, and so it is convenient to
9665 ** read it from this routine.
9666 */
9667 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9668   BtShared *pBt = p->pBt;
9669 
9670   sqlite3BtreeEnter(p);
9671   assert( p->inTrans>TRANS_NONE );
9672   assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9673   assert( pBt->pPage1 );
9674   assert( idx>=0 && idx<=15 );
9675 
9676   if( idx==BTREE_DATA_VERSION ){
9677     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
9678   }else{
9679     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9680   }
9681 
9682   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9683   ** database, mark the database as read-only.  */
9684 #ifdef SQLITE_OMIT_AUTOVACUUM
9685   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9686     pBt->btsFlags |= BTS_READ_ONLY;
9687   }
9688 #endif
9689 
9690   sqlite3BtreeLeave(p);
9691 }
9692 
9693 /*
9694 ** Write meta-information back into the database.  Meta[0] is
9695 ** read-only and may not be written.
9696 */
9697 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9698   BtShared *pBt = p->pBt;
9699   unsigned char *pP1;
9700   int rc;
9701   assert( idx>=1 && idx<=15 );
9702   sqlite3BtreeEnter(p);
9703   assert( p->inTrans==TRANS_WRITE );
9704   assert( pBt->pPage1!=0 );
9705   pP1 = pBt->pPage1->aData;
9706   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9707   if( rc==SQLITE_OK ){
9708     put4byte(&pP1[36 + idx*4], iMeta);
9709 #ifndef SQLITE_OMIT_AUTOVACUUM
9710     if( idx==BTREE_INCR_VACUUM ){
9711       assert( pBt->autoVacuum || iMeta==0 );
9712       assert( iMeta==0 || iMeta==1 );
9713       pBt->incrVacuum = (u8)iMeta;
9714     }
9715 #endif
9716   }
9717   sqlite3BtreeLeave(p);
9718   return rc;
9719 }
9720 
9721 /*
9722 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9723 ** number of entries in the b-tree and write the result to *pnEntry.
9724 **
9725 ** SQLITE_OK is returned if the operation is successfully executed.
9726 ** Otherwise, if an error is encountered (i.e. an IO error or database
9727 ** corruption) an SQLite error code is returned.
9728 */
9729 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9730   i64 nEntry = 0;                      /* Value to return in *pnEntry */
9731   int rc;                              /* Return code */
9732 
9733   rc = moveToRoot(pCur);
9734   if( rc==SQLITE_EMPTY ){
9735     *pnEntry = 0;
9736     return SQLITE_OK;
9737   }
9738 
9739   /* Unless an error occurs, the following loop runs one iteration for each
9740   ** page in the B-Tree structure (not including overflow pages).
9741   */
9742   while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9743     int iIdx;                          /* Index of child node in parent */
9744     MemPage *pPage;                    /* Current page of the b-tree */
9745 
9746     /* If this is a leaf page or the tree is not an int-key tree, then
9747     ** this page contains countable entries. Increment the entry counter
9748     ** accordingly.
9749     */
9750     pPage = pCur->pPage;
9751     if( pPage->leaf || !pPage->intKey ){
9752       nEntry += pPage->nCell;
9753     }
9754 
9755     /* pPage is a leaf node. This loop navigates the cursor so that it
9756     ** points to the first interior cell that it points to the parent of
9757     ** the next page in the tree that has not yet been visited. The
9758     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9759     ** of the page, or to the number of cells in the page if the next page
9760     ** to visit is the right-child of its parent.
9761     **
9762     ** If all pages in the tree have been visited, return SQLITE_OK to the
9763     ** caller.
9764     */
9765     if( pPage->leaf ){
9766       do {
9767         if( pCur->iPage==0 ){
9768           /* All pages of the b-tree have been visited. Return successfully. */
9769           *pnEntry = nEntry;
9770           return moveToRoot(pCur);
9771         }
9772         moveToParent(pCur);
9773       }while ( pCur->ix>=pCur->pPage->nCell );
9774 
9775       pCur->ix++;
9776       pPage = pCur->pPage;
9777     }
9778 
9779     /* Descend to the child node of the cell that the cursor currently
9780     ** points at. This is the right-child if (iIdx==pPage->nCell).
9781     */
9782     iIdx = pCur->ix;
9783     if( iIdx==pPage->nCell ){
9784       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9785     }else{
9786       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9787     }
9788   }
9789 
9790   /* An error has occurred. Return an error code. */
9791   return rc;
9792 }
9793 
9794 /*
9795 ** Return the pager associated with a BTree.  This routine is used for
9796 ** testing and debugging only.
9797 */
9798 Pager *sqlite3BtreePager(Btree *p){
9799   return p->pBt->pPager;
9800 }
9801 
9802 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9803 /*
9804 ** Append a message to the error message string.
9805 */
9806 static void checkAppendMsg(
9807   IntegrityCk *pCheck,
9808   const char *zFormat,
9809   ...
9810 ){
9811   va_list ap;
9812   if( !pCheck->mxErr ) return;
9813   pCheck->mxErr--;
9814   pCheck->nErr++;
9815   va_start(ap, zFormat);
9816   if( pCheck->errMsg.nChar ){
9817     sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9818   }
9819   if( pCheck->zPfx ){
9820     sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9821   }
9822   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9823   va_end(ap);
9824   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9825     pCheck->bOomFault = 1;
9826   }
9827 }
9828 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9829 
9830 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9831 
9832 /*
9833 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9834 ** corresponds to page iPg is already set.
9835 */
9836 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9837   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9838   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9839 }
9840 
9841 /*
9842 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9843 */
9844 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9845   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9846   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9847 }
9848 
9849 
9850 /*
9851 ** Add 1 to the reference count for page iPage.  If this is the second
9852 ** reference to the page, add an error message to pCheck->zErrMsg.
9853 ** Return 1 if there are 2 or more references to the page and 0 if
9854 ** if this is the first reference to the page.
9855 **
9856 ** Also check that the page number is in bounds.
9857 */
9858 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9859   if( iPage>pCheck->nPage || iPage==0 ){
9860     checkAppendMsg(pCheck, "invalid page number %d", iPage);
9861     return 1;
9862   }
9863   if( getPageReferenced(pCheck, iPage) ){
9864     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9865     return 1;
9866   }
9867   if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9868   setPageReferenced(pCheck, iPage);
9869   return 0;
9870 }
9871 
9872 #ifndef SQLITE_OMIT_AUTOVACUUM
9873 /*
9874 ** Check that the entry in the pointer-map for page iChild maps to
9875 ** page iParent, pointer type ptrType. If not, append an error message
9876 ** to pCheck.
9877 */
9878 static void checkPtrmap(
9879   IntegrityCk *pCheck,   /* Integrity check context */
9880   Pgno iChild,           /* Child page number */
9881   u8 eType,              /* Expected pointer map type */
9882   Pgno iParent           /* Expected pointer map parent page number */
9883 ){
9884   int rc;
9885   u8 ePtrmapType;
9886   Pgno iPtrmapParent;
9887 
9888   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9889   if( rc!=SQLITE_OK ){
9890     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
9891     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9892     return;
9893   }
9894 
9895   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9896     checkAppendMsg(pCheck,
9897       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9898       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9899   }
9900 }
9901 #endif
9902 
9903 /*
9904 ** Check the integrity of the freelist or of an overflow page list.
9905 ** Verify that the number of pages on the list is N.
9906 */
9907 static void checkList(
9908   IntegrityCk *pCheck,  /* Integrity checking context */
9909   int isFreeList,       /* True for a freelist.  False for overflow page list */
9910   Pgno iPage,           /* Page number for first page in the list */
9911   u32 N                 /* Expected number of pages in the list */
9912 ){
9913   int i;
9914   u32 expected = N;
9915   int nErrAtStart = pCheck->nErr;
9916   while( iPage!=0 && pCheck->mxErr ){
9917     DbPage *pOvflPage;
9918     unsigned char *pOvflData;
9919     if( checkRef(pCheck, iPage) ) break;
9920     N--;
9921     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9922       checkAppendMsg(pCheck, "failed to get page %d", iPage);
9923       break;
9924     }
9925     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9926     if( isFreeList ){
9927       u32 n = (u32)get4byte(&pOvflData[4]);
9928 #ifndef SQLITE_OMIT_AUTOVACUUM
9929       if( pCheck->pBt->autoVacuum ){
9930         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9931       }
9932 #endif
9933       if( n>pCheck->pBt->usableSize/4-2 ){
9934         checkAppendMsg(pCheck,
9935            "freelist leaf count too big on page %d", iPage);
9936         N--;
9937       }else{
9938         for(i=0; i<(int)n; i++){
9939           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9940 #ifndef SQLITE_OMIT_AUTOVACUUM
9941           if( pCheck->pBt->autoVacuum ){
9942             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9943           }
9944 #endif
9945           checkRef(pCheck, iFreePage);
9946         }
9947         N -= n;
9948       }
9949     }
9950 #ifndef SQLITE_OMIT_AUTOVACUUM
9951     else{
9952       /* If this database supports auto-vacuum and iPage is not the last
9953       ** page in this overflow list, check that the pointer-map entry for
9954       ** the following page matches iPage.
9955       */
9956       if( pCheck->pBt->autoVacuum && N>0 ){
9957         i = get4byte(pOvflData);
9958         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9959       }
9960     }
9961 #endif
9962     iPage = get4byte(pOvflData);
9963     sqlite3PagerUnref(pOvflPage);
9964   }
9965   if( N && nErrAtStart==pCheck->nErr ){
9966     checkAppendMsg(pCheck,
9967       "%s is %d but should be %d",
9968       isFreeList ? "size" : "overflow list length",
9969       expected-N, expected);
9970   }
9971 }
9972 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9973 
9974 /*
9975 ** An implementation of a min-heap.
9976 **
9977 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
9978 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
9979 ** and aHeap[N*2+1].
9980 **
9981 ** The heap property is this:  Every node is less than or equal to both
9982 ** of its daughter nodes.  A consequence of the heap property is that the
9983 ** root node aHeap[1] is always the minimum value currently in the heap.
9984 **
9985 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9986 ** the heap, preserving the heap property.  The btreeHeapPull() routine
9987 ** removes the root element from the heap (the minimum value in the heap)
9988 ** and then moves other nodes around as necessary to preserve the heap
9989 ** property.
9990 **
9991 ** This heap is used for cell overlap and coverage testing.  Each u32
9992 ** entry represents the span of a cell or freeblock on a btree page.
9993 ** The upper 16 bits are the index of the first byte of a range and the
9994 ** lower 16 bits are the index of the last byte of that range.
9995 */
9996 static void btreeHeapInsert(u32 *aHeap, u32 x){
9997   u32 j, i = ++aHeap[0];
9998   aHeap[i] = x;
9999   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10000     x = aHeap[j];
10001     aHeap[j] = aHeap[i];
10002     aHeap[i] = x;
10003     i = j;
10004   }
10005 }
10006 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10007   u32 j, i, x;
10008   if( (x = aHeap[0])==0 ) return 0;
10009   *pOut = aHeap[1];
10010   aHeap[1] = aHeap[x];
10011   aHeap[x] = 0xffffffff;
10012   aHeap[0]--;
10013   i = 1;
10014   while( (j = i*2)<=aHeap[0] ){
10015     if( aHeap[j]>aHeap[j+1] ) j++;
10016     if( aHeap[i]<aHeap[j] ) break;
10017     x = aHeap[i];
10018     aHeap[i] = aHeap[j];
10019     aHeap[j] = x;
10020     i = j;
10021   }
10022   return 1;
10023 }
10024 
10025 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10026 /*
10027 ** Do various sanity checks on a single page of a tree.  Return
10028 ** the tree depth.  Root pages return 0.  Parents of root pages
10029 ** return 1, and so forth.
10030 **
10031 ** These checks are done:
10032 **
10033 **      1.  Make sure that cells and freeblocks do not overlap
10034 **          but combine to completely cover the page.
10035 **      2.  Make sure integer cell keys are in order.
10036 **      3.  Check the integrity of overflow pages.
10037 **      4.  Recursively call checkTreePage on all children.
10038 **      5.  Verify that the depth of all children is the same.
10039 */
10040 static int checkTreePage(
10041   IntegrityCk *pCheck,  /* Context for the sanity check */
10042   Pgno iPage,           /* Page number of the page to check */
10043   i64 *piMinKey,        /* Write minimum integer primary key here */
10044   i64 maxKey            /* Error if integer primary key greater than this */
10045 ){
10046   MemPage *pPage = 0;      /* The page being analyzed */
10047   int i;                   /* Loop counter */
10048   int rc;                  /* Result code from subroutine call */
10049   int depth = -1, d2;      /* Depth of a subtree */
10050   int pgno;                /* Page number */
10051   int nFrag;               /* Number of fragmented bytes on the page */
10052   int hdr;                 /* Offset to the page header */
10053   int cellStart;           /* Offset to the start of the cell pointer array */
10054   int nCell;               /* Number of cells */
10055   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10056   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
10057                            ** False if IPK must be strictly less than maxKey */
10058   u8 *data;                /* Page content */
10059   u8 *pCell;               /* Cell content */
10060   u8 *pCellIdx;            /* Next element of the cell pointer array */
10061   BtShared *pBt;           /* The BtShared object that owns pPage */
10062   u32 pc;                  /* Address of a cell */
10063   u32 usableSize;          /* Usable size of the page */
10064   u32 contentOffset;       /* Offset to the start of the cell content area */
10065   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
10066   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
10067   const char *saved_zPfx = pCheck->zPfx;
10068   int saved_v1 = pCheck->v1;
10069   int saved_v2 = pCheck->v2;
10070   u8 savedIsInit = 0;
10071 
10072   /* Check that the page exists
10073   */
10074   pBt = pCheck->pBt;
10075   usableSize = pBt->usableSize;
10076   if( iPage==0 ) return 0;
10077   if( checkRef(pCheck, iPage) ) return 0;
10078   pCheck->zPfx = "Page %u: ";
10079   pCheck->v1 = iPage;
10080   if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10081     checkAppendMsg(pCheck,
10082        "unable to get the page. error code=%d", rc);
10083     goto end_of_check;
10084   }
10085 
10086   /* Clear MemPage.isInit to make sure the corruption detection code in
10087   ** btreeInitPage() is executed.  */
10088   savedIsInit = pPage->isInit;
10089   pPage->isInit = 0;
10090   if( (rc = btreeInitPage(pPage))!=0 ){
10091     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
10092     checkAppendMsg(pCheck,
10093                    "btreeInitPage() returns error code %d", rc);
10094     goto end_of_check;
10095   }
10096   if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10097     assert( rc==SQLITE_CORRUPT );
10098     checkAppendMsg(pCheck, "free space corruption", rc);
10099     goto end_of_check;
10100   }
10101   data = pPage->aData;
10102   hdr = pPage->hdrOffset;
10103 
10104   /* Set up for cell analysis */
10105   pCheck->zPfx = "On tree page %u cell %d: ";
10106   contentOffset = get2byteNotZero(&data[hdr+5]);
10107   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
10108 
10109   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10110   ** number of cells on the page. */
10111   nCell = get2byte(&data[hdr+3]);
10112   assert( pPage->nCell==nCell );
10113 
10114   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10115   ** immediately follows the b-tree page header. */
10116   cellStart = hdr + 12 - 4*pPage->leaf;
10117   assert( pPage->aCellIdx==&data[cellStart] );
10118   pCellIdx = &data[cellStart + 2*(nCell-1)];
10119 
10120   if( !pPage->leaf ){
10121     /* Analyze the right-child page of internal pages */
10122     pgno = get4byte(&data[hdr+8]);
10123 #ifndef SQLITE_OMIT_AUTOVACUUM
10124     if( pBt->autoVacuum ){
10125       pCheck->zPfx = "On page %u at right child: ";
10126       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10127     }
10128 #endif
10129     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10130     keyCanBeEqual = 0;
10131   }else{
10132     /* For leaf pages, the coverage check will occur in the same loop
10133     ** as the other cell checks, so initialize the heap.  */
10134     heap = pCheck->heap;
10135     heap[0] = 0;
10136   }
10137 
10138   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10139   ** integer offsets to the cell contents. */
10140   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10141     CellInfo info;
10142 
10143     /* Check cell size */
10144     pCheck->v2 = i;
10145     assert( pCellIdx==&data[cellStart + i*2] );
10146     pc = get2byteAligned(pCellIdx);
10147     pCellIdx -= 2;
10148     if( pc<contentOffset || pc>usableSize-4 ){
10149       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10150                              pc, contentOffset, usableSize-4);
10151       doCoverageCheck = 0;
10152       continue;
10153     }
10154     pCell = &data[pc];
10155     pPage->xParseCell(pPage, pCell, &info);
10156     if( pc+info.nSize>usableSize ){
10157       checkAppendMsg(pCheck, "Extends off end of page");
10158       doCoverageCheck = 0;
10159       continue;
10160     }
10161 
10162     /* Check for integer primary key out of range */
10163     if( pPage->intKey ){
10164       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10165         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10166       }
10167       maxKey = info.nKey;
10168       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
10169     }
10170 
10171     /* Check the content overflow list */
10172     if( info.nPayload>info.nLocal ){
10173       u32 nPage;       /* Number of pages on the overflow chain */
10174       Pgno pgnoOvfl;   /* First page of the overflow chain */
10175       assert( pc + info.nSize - 4 <= usableSize );
10176       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10177       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10178 #ifndef SQLITE_OMIT_AUTOVACUUM
10179       if( pBt->autoVacuum ){
10180         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10181       }
10182 #endif
10183       checkList(pCheck, 0, pgnoOvfl, nPage);
10184     }
10185 
10186     if( !pPage->leaf ){
10187       /* Check sanity of left child page for internal pages */
10188       pgno = get4byte(pCell);
10189 #ifndef SQLITE_OMIT_AUTOVACUUM
10190       if( pBt->autoVacuum ){
10191         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10192       }
10193 #endif
10194       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10195       keyCanBeEqual = 0;
10196       if( d2!=depth ){
10197         checkAppendMsg(pCheck, "Child page depth differs");
10198         depth = d2;
10199       }
10200     }else{
10201       /* Populate the coverage-checking heap for leaf pages */
10202       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10203     }
10204   }
10205   *piMinKey = maxKey;
10206 
10207   /* Check for complete coverage of the page
10208   */
10209   pCheck->zPfx = 0;
10210   if( doCoverageCheck && pCheck->mxErr>0 ){
10211     /* For leaf pages, the min-heap has already been initialized and the
10212     ** cells have already been inserted.  But for internal pages, that has
10213     ** not yet been done, so do it now */
10214     if( !pPage->leaf ){
10215       heap = pCheck->heap;
10216       heap[0] = 0;
10217       for(i=nCell-1; i>=0; i--){
10218         u32 size;
10219         pc = get2byteAligned(&data[cellStart+i*2]);
10220         size = pPage->xCellSize(pPage, &data[pc]);
10221         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10222       }
10223     }
10224     /* Add the freeblocks to the min-heap
10225     **
10226     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10227     ** is the offset of the first freeblock, or zero if there are no
10228     ** freeblocks on the page.
10229     */
10230     i = get2byte(&data[hdr+1]);
10231     while( i>0 ){
10232       int size, j;
10233       assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10234       size = get2byte(&data[i+2]);
10235       assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10236       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10237       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10238       ** big-endian integer which is the offset in the b-tree page of the next
10239       ** freeblock in the chain, or zero if the freeblock is the last on the
10240       ** chain. */
10241       j = get2byte(&data[i]);
10242       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10243       ** increasing offset. */
10244       assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */
10245       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10246       i = j;
10247     }
10248     /* Analyze the min-heap looking for overlap between cells and/or
10249     ** freeblocks, and counting the number of untracked bytes in nFrag.
10250     **
10251     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
10252     ** There is an implied first entry the covers the page header, the cell
10253     ** pointer index, and the gap between the cell pointer index and the start
10254     ** of cell content.
10255     **
10256     ** The loop below pulls entries from the min-heap in order and compares
10257     ** the start_address against the previous end_address.  If there is an
10258     ** overlap, that means bytes are used multiple times.  If there is a gap,
10259     ** that gap is added to the fragmentation count.
10260     */
10261     nFrag = 0;
10262     prev = contentOffset - 1;   /* Implied first min-heap entry */
10263     while( btreeHeapPull(heap,&x) ){
10264       if( (prev&0xffff)>=(x>>16) ){
10265         checkAppendMsg(pCheck,
10266           "Multiple uses for byte %u of page %u", x>>16, iPage);
10267         break;
10268       }else{
10269         nFrag += (x>>16) - (prev&0xffff) - 1;
10270         prev = x;
10271       }
10272     }
10273     nFrag += usableSize - (prev&0xffff) - 1;
10274     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10275     ** is stored in the fifth field of the b-tree page header.
10276     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10277     ** number of fragmented free bytes within the cell content area.
10278     */
10279     if( heap[0]==0 && nFrag!=data[hdr+7] ){
10280       checkAppendMsg(pCheck,
10281           "Fragmentation of %d bytes reported as %d on page %u",
10282           nFrag, data[hdr+7], iPage);
10283     }
10284   }
10285 
10286 end_of_check:
10287   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10288   releasePage(pPage);
10289   pCheck->zPfx = saved_zPfx;
10290   pCheck->v1 = saved_v1;
10291   pCheck->v2 = saved_v2;
10292   return depth+1;
10293 }
10294 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10295 
10296 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10297 /*
10298 ** This routine does a complete check of the given BTree file.  aRoot[] is
10299 ** an array of pages numbers were each page number is the root page of
10300 ** a table.  nRoot is the number of entries in aRoot.
10301 **
10302 ** A read-only or read-write transaction must be opened before calling
10303 ** this function.
10304 **
10305 ** Write the number of error seen in *pnErr.  Except for some memory
10306 ** allocation errors,  an error message held in memory obtained from
10307 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
10308 ** returned.  If a memory allocation error occurs, NULL is returned.
10309 **
10310 ** If the first entry in aRoot[] is 0, that indicates that the list of
10311 ** root pages is incomplete.  This is a "partial integrity-check".  This
10312 ** happens when performing an integrity check on a single table.  The
10313 ** zero is skipped, of course.  But in addition, the freelist checks
10314 ** and the checks to make sure every page is referenced are also skipped,
10315 ** since obviously it is not possible to know which pages are covered by
10316 ** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
10317 ** checks are still performed.
10318 */
10319 char *sqlite3BtreeIntegrityCheck(
10320   sqlite3 *db,  /* Database connection that is running the check */
10321   Btree *p,     /* The btree to be checked */
10322   Pgno *aRoot,  /* An array of root pages numbers for individual trees */
10323   int nRoot,    /* Number of entries in aRoot[] */
10324   int mxErr,    /* Stop reporting errors after this many */
10325   int *pnErr    /* Write number of errors seen to this variable */
10326 ){
10327   Pgno i;
10328   IntegrityCk sCheck;
10329   BtShared *pBt = p->pBt;
10330   u64 savedDbFlags = pBt->db->flags;
10331   char zErr[100];
10332   int bPartial = 0;            /* True if not checking all btrees */
10333   int bCkFreelist = 1;         /* True to scan the freelist */
10334   VVA_ONLY( int nRef );
10335   assert( nRoot>0 );
10336 
10337   /* aRoot[0]==0 means this is a partial check */
10338   if( aRoot[0]==0 ){
10339     assert( nRoot>1 );
10340     bPartial = 1;
10341     if( aRoot[1]!=1 ) bCkFreelist = 0;
10342   }
10343 
10344   sqlite3BtreeEnter(p);
10345   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10346   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10347   assert( nRef>=0 );
10348   sCheck.db = db;
10349   sCheck.pBt = pBt;
10350   sCheck.pPager = pBt->pPager;
10351   sCheck.nPage = btreePagecount(sCheck.pBt);
10352   sCheck.mxErr = mxErr;
10353   sCheck.nErr = 0;
10354   sCheck.bOomFault = 0;
10355   sCheck.zPfx = 0;
10356   sCheck.v1 = 0;
10357   sCheck.v2 = 0;
10358   sCheck.aPgRef = 0;
10359   sCheck.heap = 0;
10360   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10361   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10362   if( sCheck.nPage==0 ){
10363     goto integrity_ck_cleanup;
10364   }
10365 
10366   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10367   if( !sCheck.aPgRef ){
10368     sCheck.bOomFault = 1;
10369     goto integrity_ck_cleanup;
10370   }
10371   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10372   if( sCheck.heap==0 ){
10373     sCheck.bOomFault = 1;
10374     goto integrity_ck_cleanup;
10375   }
10376 
10377   i = PENDING_BYTE_PAGE(pBt);
10378   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10379 
10380   /* Check the integrity of the freelist
10381   */
10382   if( bCkFreelist ){
10383     sCheck.zPfx = "Main freelist: ";
10384     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10385               get4byte(&pBt->pPage1->aData[36]));
10386     sCheck.zPfx = 0;
10387   }
10388 
10389   /* Check all the tables.
10390   */
10391 #ifndef SQLITE_OMIT_AUTOVACUUM
10392   if( !bPartial ){
10393     if( pBt->autoVacuum ){
10394       Pgno mx = 0;
10395       Pgno mxInHdr;
10396       for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10397       mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10398       if( mx!=mxInHdr ){
10399         checkAppendMsg(&sCheck,
10400           "max rootpage (%d) disagrees with header (%d)",
10401           mx, mxInHdr
10402         );
10403       }
10404     }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10405       checkAppendMsg(&sCheck,
10406         "incremental_vacuum enabled with a max rootpage of zero"
10407       );
10408     }
10409   }
10410 #endif
10411   testcase( pBt->db->flags & SQLITE_CellSizeCk );
10412   pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10413   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10414     i64 notUsed;
10415     if( aRoot[i]==0 ) continue;
10416 #ifndef SQLITE_OMIT_AUTOVACUUM
10417     if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10418       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10419     }
10420 #endif
10421     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10422   }
10423   pBt->db->flags = savedDbFlags;
10424 
10425   /* Make sure every page in the file is referenced
10426   */
10427   if( !bPartial ){
10428     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10429 #ifdef SQLITE_OMIT_AUTOVACUUM
10430       if( getPageReferenced(&sCheck, i)==0 ){
10431         checkAppendMsg(&sCheck, "Page %d is never used", i);
10432       }
10433 #else
10434       /* If the database supports auto-vacuum, make sure no tables contain
10435       ** references to pointer-map pages.
10436       */
10437       if( getPageReferenced(&sCheck, i)==0 &&
10438          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10439         checkAppendMsg(&sCheck, "Page %d is never used", i);
10440       }
10441       if( getPageReferenced(&sCheck, i)!=0 &&
10442          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10443         checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10444       }
10445 #endif
10446     }
10447   }
10448 
10449   /* Clean  up and report errors.
10450   */
10451 integrity_ck_cleanup:
10452   sqlite3PageFree(sCheck.heap);
10453   sqlite3_free(sCheck.aPgRef);
10454   if( sCheck.bOomFault ){
10455     sqlite3_str_reset(&sCheck.errMsg);
10456     sCheck.nErr++;
10457   }
10458   *pnErr = sCheck.nErr;
10459   if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10460   /* Make sure this analysis did not leave any unref() pages. */
10461   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10462   sqlite3BtreeLeave(p);
10463   return sqlite3StrAccumFinish(&sCheck.errMsg);
10464 }
10465 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10466 
10467 /*
10468 ** Return the full pathname of the underlying database file.  Return
10469 ** an empty string if the database is in-memory or a TEMP database.
10470 **
10471 ** The pager filename is invariant as long as the pager is
10472 ** open so it is safe to access without the BtShared mutex.
10473 */
10474 const char *sqlite3BtreeGetFilename(Btree *p){
10475   assert( p->pBt->pPager!=0 );
10476   return sqlite3PagerFilename(p->pBt->pPager, 1);
10477 }
10478 
10479 /*
10480 ** Return the pathname of the journal file for this database. The return
10481 ** value of this routine is the same regardless of whether the journal file
10482 ** has been created or not.
10483 **
10484 ** The pager journal filename is invariant as long as the pager is
10485 ** open so it is safe to access without the BtShared mutex.
10486 */
10487 const char *sqlite3BtreeGetJournalname(Btree *p){
10488   assert( p->pBt->pPager!=0 );
10489   return sqlite3PagerJournalname(p->pBt->pPager);
10490 }
10491 
10492 /*
10493 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10494 ** to describe the current transaction state of Btree p.
10495 */
10496 int sqlite3BtreeTxnState(Btree *p){
10497   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10498   return p ? p->inTrans : 0;
10499 }
10500 
10501 #ifndef SQLITE_OMIT_WAL
10502 /*
10503 ** Run a checkpoint on the Btree passed as the first argument.
10504 **
10505 ** Return SQLITE_LOCKED if this or any other connection has an open
10506 ** transaction on the shared-cache the argument Btree is connected to.
10507 **
10508 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10509 */
10510 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10511   int rc = SQLITE_OK;
10512   if( p ){
10513     BtShared *pBt = p->pBt;
10514     sqlite3BtreeEnter(p);
10515     if( pBt->inTransaction!=TRANS_NONE ){
10516       rc = SQLITE_LOCKED;
10517     }else{
10518       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10519     }
10520     sqlite3BtreeLeave(p);
10521   }
10522   return rc;
10523 }
10524 #endif
10525 
10526 /*
10527 ** Return true if there is currently a backup running on Btree p.
10528 */
10529 int sqlite3BtreeIsInBackup(Btree *p){
10530   assert( p );
10531   assert( sqlite3_mutex_held(p->db->mutex) );
10532   return p->nBackup!=0;
10533 }
10534 
10535 /*
10536 ** This function returns a pointer to a blob of memory associated with
10537 ** a single shared-btree. The memory is used by client code for its own
10538 ** purposes (for example, to store a high-level schema associated with
10539 ** the shared-btree). The btree layer manages reference counting issues.
10540 **
10541 ** The first time this is called on a shared-btree, nBytes bytes of memory
10542 ** are allocated, zeroed, and returned to the caller. For each subsequent
10543 ** call the nBytes parameter is ignored and a pointer to the same blob
10544 ** of memory returned.
10545 **
10546 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10547 ** allocated, a null pointer is returned. If the blob has already been
10548 ** allocated, it is returned as normal.
10549 **
10550 ** Just before the shared-btree is closed, the function passed as the
10551 ** xFree argument when the memory allocation was made is invoked on the
10552 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10553 ** on the memory, the btree layer does that.
10554 */
10555 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10556   BtShared *pBt = p->pBt;
10557   sqlite3BtreeEnter(p);
10558   if( !pBt->pSchema && nBytes ){
10559     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10560     pBt->xFreeSchema = xFree;
10561   }
10562   sqlite3BtreeLeave(p);
10563   return pBt->pSchema;
10564 }
10565 
10566 /*
10567 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10568 ** btree as the argument handle holds an exclusive lock on the
10569 ** sqlite_schema table. Otherwise SQLITE_OK.
10570 */
10571 int sqlite3BtreeSchemaLocked(Btree *p){
10572   int rc;
10573   assert( sqlite3_mutex_held(p->db->mutex) );
10574   sqlite3BtreeEnter(p);
10575   rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10576   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10577   sqlite3BtreeLeave(p);
10578   return rc;
10579 }
10580 
10581 
10582 #ifndef SQLITE_OMIT_SHARED_CACHE
10583 /*
10584 ** Obtain a lock on the table whose root page is iTab.  The
10585 ** lock is a write lock if isWritelock is true or a read lock
10586 ** if it is false.
10587 */
10588 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10589   int rc = SQLITE_OK;
10590   assert( p->inTrans!=TRANS_NONE );
10591   if( p->sharable ){
10592     u8 lockType = READ_LOCK + isWriteLock;
10593     assert( READ_LOCK+1==WRITE_LOCK );
10594     assert( isWriteLock==0 || isWriteLock==1 );
10595 
10596     sqlite3BtreeEnter(p);
10597     rc = querySharedCacheTableLock(p, iTab, lockType);
10598     if( rc==SQLITE_OK ){
10599       rc = setSharedCacheTableLock(p, iTab, lockType);
10600     }
10601     sqlite3BtreeLeave(p);
10602   }
10603   return rc;
10604 }
10605 #endif
10606 
10607 #ifndef SQLITE_OMIT_INCRBLOB
10608 /*
10609 ** Argument pCsr must be a cursor opened for writing on an
10610 ** INTKEY table currently pointing at a valid table entry.
10611 ** This function modifies the data stored as part of that entry.
10612 **
10613 ** Only the data content may only be modified, it is not possible to
10614 ** change the length of the data stored. If this function is called with
10615 ** parameters that attempt to write past the end of the existing data,
10616 ** no modifications are made and SQLITE_CORRUPT is returned.
10617 */
10618 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10619   int rc;
10620   assert( cursorOwnsBtShared(pCsr) );
10621   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10622   assert( pCsr->curFlags & BTCF_Incrblob );
10623 
10624   rc = restoreCursorPosition(pCsr);
10625   if( rc!=SQLITE_OK ){
10626     return rc;
10627   }
10628   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10629   if( pCsr->eState!=CURSOR_VALID ){
10630     return SQLITE_ABORT;
10631   }
10632 
10633   /* Save the positions of all other cursors open on this table. This is
10634   ** required in case any of them are holding references to an xFetch
10635   ** version of the b-tree page modified by the accessPayload call below.
10636   **
10637   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10638   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10639   ** saveAllCursors can only return SQLITE_OK.
10640   */
10641   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10642   assert( rc==SQLITE_OK );
10643 
10644   /* Check some assumptions:
10645   **   (a) the cursor is open for writing,
10646   **   (b) there is a read/write transaction open,
10647   **   (c) the connection holds a write-lock on the table (if required),
10648   **   (d) there are no conflicting read-locks, and
10649   **   (e) the cursor points at a valid row of an intKey table.
10650   */
10651   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10652     return SQLITE_READONLY;
10653   }
10654   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10655               && pCsr->pBt->inTransaction==TRANS_WRITE );
10656   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10657   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10658   assert( pCsr->pPage->intKey );
10659 
10660   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10661 }
10662 
10663 /*
10664 ** Mark this cursor as an incremental blob cursor.
10665 */
10666 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10667   pCur->curFlags |= BTCF_Incrblob;
10668   pCur->pBtree->hasIncrblobCur = 1;
10669 }
10670 #endif
10671 
10672 /*
10673 ** Set both the "read version" (single byte at byte offset 18) and
10674 ** "write version" (single byte at byte offset 19) fields in the database
10675 ** header to iVersion.
10676 */
10677 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10678   BtShared *pBt = pBtree->pBt;
10679   int rc;                         /* Return code */
10680 
10681   assert( iVersion==1 || iVersion==2 );
10682 
10683   /* If setting the version fields to 1, do not automatically open the
10684   ** WAL connection, even if the version fields are currently set to 2.
10685   */
10686   pBt->btsFlags &= ~BTS_NO_WAL;
10687   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10688 
10689   rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10690   if( rc==SQLITE_OK ){
10691     u8 *aData = pBt->pPage1->aData;
10692     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10693       rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10694       if( rc==SQLITE_OK ){
10695         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10696         if( rc==SQLITE_OK ){
10697           aData[18] = (u8)iVersion;
10698           aData[19] = (u8)iVersion;
10699         }
10700       }
10701     }
10702   }
10703 
10704   pBt->btsFlags &= ~BTS_NO_WAL;
10705   return rc;
10706 }
10707 
10708 /*
10709 ** Return true if the cursor has a hint specified.  This routine is
10710 ** only used from within assert() statements
10711 */
10712 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10713   return (pCsr->hints & mask)!=0;
10714 }
10715 
10716 /*
10717 ** Return true if the given Btree is read-only.
10718 */
10719 int sqlite3BtreeIsReadonly(Btree *p){
10720   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10721 }
10722 
10723 /*
10724 ** Return the size of the header added to each page by this module.
10725 */
10726 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10727 
10728 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10729 /*
10730 ** Return true if the Btree passed as the only argument is sharable.
10731 */
10732 int sqlite3BtreeSharable(Btree *p){
10733   return p->sharable;
10734 }
10735 
10736 /*
10737 ** Return the number of connections to the BtShared object accessed by
10738 ** the Btree handle passed as the only argument. For private caches
10739 ** this is always 1. For shared caches it may be 1 or greater.
10740 */
10741 int sqlite3BtreeConnectionCount(Btree *p){
10742   testcase( p->sharable );
10743   return p->pBt->nRef;
10744 }
10745 #endif
10746