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